Removed some bugs in abstract class, added testcase

This commit is contained in:
2019-05-22 15:26:24 +02:00
parent b3e28d7884
commit b868f0fe86
5 changed files with 103 additions and 8 deletions

View File

@@ -0,0 +1,135 @@
<?php
// No direct access.
use Joomla\CMS\Factory;
defined('_JEXEC') or die;
class ElementNotFoundException extends Exception
{}
abstract class AbstractCommonClubsModelFactory
{
/*
* This method should return an array to configure the trivially accessible values.
* The key must be a unique key describing the information and will be reused in the getValues() method.
* The value of each key should be an associative array describing the object field.
* Example of an array returned by this method is
* array(
* 'name'=>array('col'=>'Name', type=>'string'),
* 'size'=>array('col'=>'area', type=>'int')
* )
*
* The inner arrays contain the following entries:
* - col: The name of the column in the database. Defaults to the key name
* - type: The type of the column. If nothing is specified, string is assumed.
* - string
* - int
* - float
* - ref
* - ref: (only with type='ref') The name of the class that is referenced
*/
public abstract function getAttributes();
private $attributes = null;
private function fetchAttributes()
{
if($this->attributes === null)
$this->attributes = $this->getAttributes();
return $this->attributes;
}
public abstract function getTableName();
public abstract function getClassName();
/**
*
* @param string $condition
* @return array
*/
public function loadElements($condition = null)
{
$db = Factory::getDbo();
$q = $db->getQuery(true);
// $columns = array_map(function($arr) use ($q){ return $q->qn('main' . $arr['col']); }, $this->fetchAttributes());
// $columns = array();
// foreach($this->fetchAttributes() as $k=>$v)
// {
// $columns[] = $q->qn('main' . $v['col'], $k);
// }
$q->select('main.id AS id');//->select($columns);
$q->from($this->getTableName() . ' AS main');
// TODO Joins
if($condition !== null)
$q->where($condition);
$db->setQuery($q);
$db->execute();
$rows = $db->loadAssocList();
$ret = array();
foreach($rows as $row)
{
$ret[] = $this->generateObject($row);
}
return $ret;
}
/**
*
* @param int $id
*/
public function loadById($id) {
$arr = $this->loadElements("main.id = " . ((int)$id) );
if(sizeof($arr) == 0)
throw new ElementNotFoundException();
return $arr[0];
}
private function generatePlainObject($id)
{
$name = $this->getClassName();
$obj = new $name();
$obj->setId($id);
return $obj;
}
protected function generateObject($row)
{
$obj = $this->generatePlainObject($row['id']);
$obj->markAsNew(false);
//unset($row['id']);
//$obj->setValues($row);
// Do not trigger cache if no needed
//$obj->getValues();
return $obj;
}
public function createNew()
{
$obj = $this->generatePlainObject('new');
$obj->markAsNew(true);
$attribs = array_map(function($v){
return Null;
}, $this->fetchAttributes());
$obj->setValues($attribs);
$obj->fillDefaultValues();
return $obj;
}
}