/** * * Object constructor * @param t41_Data_Object|t41_Object_Uri|string $val * @param array $params */ public function __construct($val = null, array $params = null) { $this->_setParameterObjects(); if (is_array($params)) { $this->_setParameters($params); } /* build data object and populate it if possible */ if ($val instanceof DataObject) { if ($val->getClass() != get_class($this)) { throw new Exception("Provided Data Object is not build on class definition"); } $this->_dataObject = $val; /* get object rules from config */ $this->setRules(); } else { $this->_dataObject = DataObject::factory(get_class($this)); /* get object rules from config */ $this->setRules(); /* get object rules from config */ //$this->_rules = t41_Object::getRules(get_class($this), $this->_dataObject); if (!is_null($val)) { if (!$val instanceof ObjectUri) { $val = new ObjectUri($val); $val->setClass(get_class($this)); } $this->_dataObject->setUri($val); $this->read(); } } }
public function getValue(DataObject $do) { $property = $do->getProperty($this->getParameter('property')); if ($property instanceof CollectionProperty) { $subParts = explode('.', $this->getParameter('action')); $collection = $property->getValue(); return $collection->{$subParts[0]}(isset($subParts[1]) ? $subParts[1] : null); } else { if ($property instanceof AbstractProperty) { return $property->getValue(); } else { return $this->_value; //parent::getValue(); } } }
/** * * Object constructor * @param t41\ObjectModel\DataObject|t41\ObjectModel\ObjectUri|string $val * @param array $params */ public function __construct($val = null, array $params = null) { $this->_setParameterObjects(); if (is_array($params)) { $this->_setParameters($params); } /* build data object and populate it if possible */ if ($val instanceof DataObject) { if ($val->getClass() != get_class($this)) { throw new Exception("Provided Data Object is not build on class definition"); } $this->_dataObject = $val; } else { if (!is_null($val)) { if (!$val instanceof ObjectUri) { // provide backend if uri is partial $backendUri = null; //substr($val,0,1) != Backend::PREFIX ? ObjectModel::getObjectBackend(get_class($this)) : null; $val = new ObjectUri($val, $backendUri); $val->setClass(get_class($this)); } $this->_dataObject = Core::_($val, get_class($this), ObjectModel::DATA); } else { $this->_dataObject = DataObject::factory(get_class($this)); } } /* get object rules from config */ $this->setRules(); }
public function build(ObjectModel\DataObject $do, array $display = null, $identifier = false) { if ($identifier === true) { $identifier = new FieldElement(ObjectUri::IDENTIFIER); $identifier->setTitle("Identifiant unique")->setConstraint(Property::CONSTRAINT_MANDATORY, true)->setConstraint(Property::CONSTRAINT_MAXLENGTH, 10); $this->addElement($identifier); } if (is_null($display)) { $display = array_keys($do->getProperties()); } foreach ($display as $element) { $property = $do->getRecursiveProperty($element); if ($property instanceof AbstractProperty) { /* convert property to form element */ $this->addElementFromProperty($property, $element, (count($this->_elements) + 1) * 100); } } }
/** * Delete record in backend * * @param t41\ObjectModel\DataObject $do * @return boolean */ public function delete(ObjectModel\DataObject $do) { $uri = $do->getUri(); $table = $this->_mapper instanceof Backend\Mapper ? $this->_mapper->getDatastore($uri->getClass()) : $do->getClass(); $pkey = $this->_mapper ? $this->_mapper->getPrimaryKey($uri->getClass()) : 'id'; // @todo add a try/catch block return (bool) $this->_ressource->delete($table, $this->_ressource->quoteInto("{$pkey} = ?" . $uri->getIdentifier())); }
/** * Returns an array of objects queried from the given t41_Object_Collection instance parameters * * The given collection is populated if it comes empty of members. * * In any other case, this method doesn't directly populate the collection. This action is under the responsability of * the caller. For example, the t41_Object_Collection::find() method takes care of it. * * @param t41_Object_Collection $collection * @return array */ public function find(t41_Object_Collection $collection) { $class = $collection->getDataObject()->getClass(); $filters = $sortings = array(); $searchMode = '&'; // primary key is either part of the mapper configuration or 'dn' $pkey = $this->_mapper ? $this->_mapper->getPrimaryKey($class) : 'dn'; /* @var $condition t41_Condition */ foreach ($collection->getConditions() as $conditionArray) { $condition = $conditionArray[0]; /* does condition contain another condition object ? */ if ($condition->isRecursive()) { // not supported with LDAP continue; } $property = $condition->getProperty(); if ($property instanceof Property\ObjectProperty) { } else { $field = $property->getId(); if ($this->_mapper) { $field = $this->_mapper->propertyToDatastoreName($class, $field); } } $filters[] = $this->_buildConditionStatement($field, $condition->getClauses()); switch ($conditionArray[1]) { case 'OR': // $select->orWhere($statement); break; case 'AND': default: // $select->where($statement); break; } } foreach ($collection->getSortings() as $sorting) { if ($this->_mapper) { $class = $sorting[0]->getParent() ? $sorting[0]->getParent()->getId() : $collection->getDataObject()->getClass(); $field = $this->_mapper->propertyToDatastoreName($class, $sorting[0]->getId()); } else { $field = $sorting[0]->getId(); } $sortings[] = $field; } $filter = implode($filters); if (count($sortings) > 0) { $filter .= sprintf('(sort=%s)', implode(',', $sortings)); } if ($filter) { $filter = sprintf('%s%s', $searchMode, $filter); } $filter = $filter ? '(' . $filter . ')' : "(objectClass=*)"; try { if ($this->_mapper) { $this->_connect($this->_mapper->getDatastore($collection->getDataObject()->getClass())); } else { $this->_connect(); } /* @var $result Zend_Ldap_Collection */ /* $result = $this->_ressource->search( $filter , $this->_currentDn // Base DN , null //Zend_Ldap::SEARCH_SCOPE_ONE // Scope , null//array('sizeLimit' => $collection->getBoundaryBatch()) ); // query result */ $search = ldap_search($this->_ressource, $this->_currentDn, $filter); $result = ldap_get_entries($this->_ressource, $search); } catch (Exception $e) { throw new Exception("LDAP Query error: " . $e->getMessage()); } // first result is total records unset($result['count']); // populate array with relevant objects type $array = array(); $uri = new ObjectModel\ObjectUri(); $uri->setBackendUri($this->_uri); $uri->setClass($class); if ($collection->getParameter('memberType') != 'uri') { $do = new ObjectModel\DataObject($class); } foreach ($result as $entry) { $entry = $this->_flattenArray($entry, true); $uri->setUrl($this->_uri->getAlias() . '/' . $entry['dn']); switch ($collection->getParameter('memberType')) { case 'uri': $data = clone $uri; break; case 'data': default: $do->setUri(clone $uri); $do->populate($entry, $this->_mapper); $data = clone $do; break; case 'model': $do->setUri(clone $uri); $do->populate($entry, $this->_mapper); /* @var $obj t41_Object_Model */ $data = new $class(null, null, clone $do); break; } $array[] = $data; } return $array; }
/** * Universal factory for DataObject() and BaseObject() instances with caching capabilities * @param ObjectUri $uri * @param string $class * @param string $type * @throws Exception * @return \t41\ObjectModel\DataObject|t41\ObjectModel\BaseObject */ public static function _($uri, $class = null, $type = ObjectModel::MODEL) { if (!$uri instanceof ObjectUri) { if (is_null($class)) { throw new Exception("Give ObjectUri() instance or specify object class as second argument"); } $uri = new ObjectUri($uri); $uri->setClass($class); } else { $class = $uri->getClass(); } if (self::getEnvData('cache_objects') !== true) { $obj = DataObject::factory($class); $obj->setUri($uri); Backend::read($obj); return $type == ObjectModel::MODEL ? new $class($obj) : $obj; } $def = ObjectModel::getObjectDna($class); if ($def && isset($def['unchanging'])) { // get cache version if (($obj = self::cacheGet($uri->getPermanentUUID())) !== false) { self::log(sprintf('[Persistence] Loaded %s object (%s) from cache', $class, $uri)); } else { // done this away to avoid infinite recursion in BaseObject::__construct() $obj = DataObject::factory($class); $obj->setUri($uri); Backend::read($obj); $obj = new $class($obj); self::cacheSet($obj, $uri->getPermanentUUID(), true, array('tags' => array('permanent'))); self::log(sprintf('[Persistence] Saved %s object (%s) in cache', $class, $uri)); } return $type == ObjectModel::MODEL ? $obj : $obj->getDataObject(); } else { $obj = DataObject::factory($class); $obj->setUri($uri); Backend::read($obj); return $type == ObjectModel::MODEL ? new $class($obj) : $obj; } }
protected function _contentRendering() { $i = 0; $p = ''; $aliases = $this->_obj->getAliases(); // print out rows foreach ($this->_obj->getCollection()->getMembers(ObjectModel::DATA) as $this->_key => $this->_do) { $css = $i % 2 == 0 ? 'odd' : 'even'; // \Zend_Debug::dump($this->_do->getProperty('marche')->getValue(ObjectModel::MODEL)); die; // @todo handle objects coming from different backends $p .= sprintf('<tr data-member="%s" data-alias="%s" class="%s">', $this->_key, $this->_do->getUri() ? $aliases[$this->_do->getUri()->getIdentifier()] : null, $css); $i++; if ($this->_obj->getParameter('selectable') === true) { // make list items selectable $p .= sprintf('<td><input type="checkbox" name="t41_selection[]" value="%s"/></td>', $this->_do->getUri()->getIdentifier()); } $altDec = (array) $this->_obj->getParameter('decorators'); foreach ($this->_obj->getColumns() as $column) { if ($column instanceof Element\IdentifierElement) { $p .= sprintf('<td>%s</td>', $this->_do->getUri()->getIdentifier()); continue; } if ($column instanceof Element\MetaElement) { $attrib = $column->getParameter('type') == 'currency' ? ' class="cellcurrency"' : null; $p .= "<td{$attrib}>" . $column->getDisplayValue($this->_do) . '</td>'; continue; } $property = $this->_do->getProperty($column->getParameter('property')); if (!$property) { $p .= '<td>??</td>'; continue; } $column->setValue($property->getValue()); /* if a decorator has been declared for property/element, use it */ if (isset($altDec[$column->getId()])) { $column->setDecorator($altDec[$column->getId()]); $deco = Decorator::factory($column); $p .= sprintf('<td>%s</td>', $deco->render()); continue; } $attrib = sprintf(' class="tb-%s', $column->getId()); $attrib .= $property instanceof Property\CurrencyProperty ? ' cellcurrency"' : '"'; if ($column->getParameter('recursion')) { $parts = $column->getParameter('recursion'); foreach ($parts as $rkey => $recursion) { if ($property instanceof ArrayProperty) { // property won't be a property here ! $property = $property->getValue(); $property = $property[$recursion]; if ($property instanceof BaseObject && isset($parts[$rkey + 1])) { $property = $property->{$parts[$rkey + 1]}; } break; } // property is an object property if ($property instanceof AbstractProperty && $property->getValue()) { $property = $property->getValue(ObjectModel::DATA)->getProperty($recursion); } if ($property instanceof ObjectModel || $property instanceof DataObject) { $property = $property->getProperty($recursion); } else { if ($property instanceof ObjectUri) { $property = ObjectModel::factory($property)->getProperty($recursion); } } } } if ($property instanceof Property\MediaProperty) { $column->setValue($property->getDisplayValue()); $deco = Decorator::factory($column); $value = $deco->render(); } else { $value = $property instanceof Property\AbstractProperty ? $property->getDisplayValue() : $property; } //$p .= "<td$attrib>" . $this->_escape($value) . '</td>'; $p .= "<td{$attrib}>" . $value . '</td>'; } $p .= '<td class="tb-actions">'; foreach ($this->_obj->getEvents('row') as $button) { $button->setParameter('uri', $this->_do->getUri()); $p .= $this->_renderButton($button, $aliases[$this->_do->getUri()->getIdentifier()]); } $p .= '</td></tr>' . "\n"; } return $p; }
/** * Define an array of printable columns based on list or setted parameter * @return array */ public function getColumns() { if (!is_array($this->_columns)) { $alt = $this->getParameter('altlabels'); $do = $this->_collection->getDataObject(); $columns = $this->getParameter('columns') ? $this->getParameter('columns') : array_keys($do->getProperties()); $this->_columns = array(); foreach ($columns as $column) { // meta columns are useful to display calculated (not stored) values if (substr($column, 0, 1) == self::METACOL) { $parts = explode(':', substr($column, 1)); $obj = new Element\MetaElement($parts[0]); $obj->setParameter('property', $parts[0]); if (isset($parts[1])) { $obj->setParameter('action', $parts[1]); } $this->_columns[] = $obj; continue; } else { if ($column instanceof MetaElement) { $this->_columns[] = $column; continue; } } if ($column == ObjectUri::IDENTIFIER) { $obj = new Element\IdentifierElement(); $obj->setTitle(isset($alt[$column]) ? $alt[$column] : 'ID'); $this->_columns[] = $obj; continue; } // $column may contain recursive property reference $parts = explode('.', $column); // find matching property $property = $do->getRecursiveProperty($column); if (!$property instanceof Property\AbstractProperty) { continue; } $obj = new Element\ColumnElement($column); if (count($parts) > 1) { $obj->setParameter('recursion', array_slice($parts, 1)); foreach (array_slice($parts, 1) as $recursion) { // recursion to find the related property if ($property instanceof Property\ObjectProperty) { $do2 = ObjectModel\DataObject::factory($property->getParameter('instanceof')); if (($nproperty = $do2->getProperty($recursion)) !== false) { $property = $nproperty; } } } } if (!is_object($property)) { $alt[$column] = 'Erreur'; } $obj->setParameter('property', $parts[0]); $obj->setTitle(isset($alt[$column]) ? $alt[$column] : $property->getLabel()); $obj->setParameter('align', $property instanceof CurrencyProperty ? 'R' : 'L'); $this->_columns[] = $obj; } } return $this->_columns; }
/** * Add content from a data object and optional columns ids * * @param t41\ObjectModel\DataObject $do * @param array $columns * @return t41\View\TableComponent */ public function setContent(DataObject $do, array $columns = array()) { foreach ($columns as $column) { if (($prop = $do->getRecursiveProperty($column)) !== false) { $format = $prop instanceof CurrencyProperty ? self::FORM_CURRENCY : self::FORM_DEFAULT; $this->addColumn($column, $prop->getLabel(), $format); } } $data = $do->toArray(null, false, true); // \Zend_Debug::dump($data); die; $this->addDataRow($data['data']); return $this; }
/** * This class is used for manipulation of collection * * Possible parameters are: * - memberType: [uri|data|model] * Defines which type of members we expect to get returned from backend. * uri: returns t41_Object_Uri references * data: returns populated t41_Data_Object instances * model: returns populated t41_Object_Model-based instances * default value is data * * @param \t41\ObjectModel\DataObject|string $do * @param array $params */ public function __construct($do, array $params = null) { if ($do instanceof ObjectModel\DataObject) { $this->_do = $do; } else { if (is_string($do)) { $this->_do = ObjectModel\DataObject::factory($do); } else { throw new Exception("Collection must be instanced from data object or class name"); } } /* deal with class parameters first */ $this->_setParameterObjects(); if (is_array($params)) { $this->_setParameters($params); } }
/** * Returns the property matching the pattern in $name, recursively if needed * @param string $name * @return t41\ObjectModel\Property\AbstractProperty */ public function getRecursiveProperty($name) { if ($name == ObjectUri::IDENTIFIER) { return new IdentifierProperty('id'); } if (strpos($name, '.') === false) { return $this->getProperty($name); } $parts = explode('.', $name); $data = $this; foreach ($parts as $part) { $property = $data->getProperty($part); // stop recursion if property is an ArrayProperty because recursion is not possible in do's property if ($property instanceof ArrayProperty) { return $property; } if ($property instanceof Property\ObjectProperty) { if ($property->getValue() instanceof ObjectModel\DataObject) { $data = $property->getValue(); } else { if ($property->getValue() instanceof BaseObject) { $data = $property->getValue()->getDataObject(); } else { if ($property->getValue() instanceof ObjectUri) { $data = DataObject::factory($property->getParameter('instanceof')); $data->setUri($property->getValue()); Backend::read($data); } else { $data = DataObject::factory($property->getParameter('instanceof')); } } } } } return $data->getProperty($part) ? $data->getProperty($part) : $property; }
/** * Load and return a blob * @param ObjectModel\DataObject $do * @param Property\AbstractProperty $property * @return binary */ public static function loadBlob(ObjectModel\DataObject $do, Property\AbstractProperty $property) { $backend = self::getInstance($do->getUri()->getBackendUri()->getAlias()); if ($backend instanceof Backend\Adapter\AbstractAdapter) { return $backend->loadBlob($do, $property); } return null; }
public function find(Collection $collection, $returnCount = false) { $url = str_replace('{basepath}', Core::$basePath, $this->_uri->getUrl()); $class = $collection->getDataObject()->getClass(); if ($this->_mapper) { $file = $this->_mapper->getDatastore($class); } else { throw new Exception("Csv backends need a mapper where datastores are defined"); } if (substr($file, 0, 1) != DIRECTORY_SEPARATOR) { $file = $url . $file; } try { $file = fopen($file, 'r'); } catch (Exception $e) { throw new Exception("Error opening file: " . $e->getMessage()); } // prepare defined conditions to be used next $this->_prepareConditionBlock($collection); // populate array with relevant objects type $uri = new ObjectModel\ObjectUri(); $uri->setBackendUri($this->_uri); $uri->setClass($class); if ($collection->getParameter('memberType') != 'uri') { $do = new ObjectModel\DataObject($class); } $separator = $this->_mapper->getExtraArg('separator', $class); if (!$separator) { $separator = ','; } $separator = str_replace(array('{tab}'), array("\t"), $separator); $array = array(); $key = -1; // csv file current line key $selected = 0; // selected members counter $offset = $collection->getBoundaryOffset(); $limit = $collection->getBoundaryBatch(); while (($data = fgetcsv($file, 1000, $separator)) !== false) { if ($this->_mapper->getExtraArg('firstlineisheader', $class) !== false && $key == -1) { /* ignore first line if it is declared as header */ $key += 1; $offset += 1; continue; } /* test data array against defined conditions */ if ($this->_testAgainstConditionBlock($data) === false) { continue; } $key++; // ignore everything before offset value if ($key < $offset && $returnCount != true) { continue; } // break after limit value is reached except if we count lines if ($selected == $limit && $returnCount !== true) { return $array; } // increment selected counter $selected++; if ($returnCount !== true) { $uri = new ObjectModel\ObjectUri(); $uri->setBackendUri($this->_uri); $uri->setClass($collection->getDataObject()->getClass()); $uri->setUrl($url . '/' . $key); $do = DataObject::factory($class); $do->setUri($uri); $do->populate($data, $this->_mapper); $array[] = new $class($do); } } return $returnCount ? $key : $array; }
/** * Objects collection factory * @param string $class * @return t41\ObjectModel\Collection * @throws t41\ObjectModel\Exception */ public static function collectionFactory($class) { try { $do = ObjectModel\DataObject::factory($class); $collection = new ObjectModel\Collection($do); return $collection; } catch (\Exception $e) { throw new Exception($e->getMessage()); } }
/** * Efface la ligne la base identifié par l'Uri en paramètre * * @param t41_Data_Object $do * @return mixed */ public function delete(ObjectModel\DataObject $do) { // on découpe l'url de l'URI afin d'obtenir les parties qui nous interesse. $uri = $do->getUri(); // on trouve la base de donnée à utiliser $database = $this->_selectDatabase($uri); // on trouve la table à utiliser $table = $this->_selectTable($uri); //return $this->_ressource->delete($table, $table . "_id = " . $url['id']); }
/** * Delete record in backend * * @param t41\ObjectModel\DataObject $do * @return boolean */ public function delete(ObjectModel\DataObject $do) { $uri = $do->getUri(); if (!$uri) { return false; } // get table to use $table = $this->_getTableFromUri($uri); if (!$table) { throw new Exception('MISSING_DBTABLE_PARAM'); } $pkey = $this->_mapper ? $this->_mapper->getPrimaryKey($uri->getClass()) : Backend::DEFAULT_PKEY; try { $this->_connect(); $res = $this->_ressource->delete($table, $this->_ressource->quoteInto("{$pkey} = ?", $uri->getIdentifier())); $this->_setLastQuery('delete', null, array('table' => $table)); } catch (\Exception $e) { $this->_setLastQuery('delete', null, array('table' => $table, 'context' => $e->getMessage())); return false; } return (bool) $res; }
protected function _getColumns(DataObject $do) { $columns = array(); foreach ($do->getProperties() as $property) { if ($property instanceof Property\BlobProperty || $property instanceof Property\CollectionProperty || $property instanceof Property\MetaProperty) { continue; } $columns[] = $this->_mapper ? $this->_mapper->propertyToDatastoreName($do->getClass(), $property->getId()) : $property->getId(); } return $columns; }
/** * Set a new condition on property given id or throws an exception if property doesn't exist * * @param string $name * @param return \t41\Backend\Condition * @throws t41_Exception */ public function having($name) { // condition on the identifier part of the uri if ($name == ObjectUri::IDENTIFIER) { $this->_condition = new self(new Property\IdentifierProperty(ObjectUri::IDENTIFIER)); return $this->_condition; } else { if (!$this->_property instanceof Property\ObjectProperty && !$this->_property instanceof Property\CollectionProperty) { throw new Exception("CONDITION_INCORRECT_PROPERTY"); } } $do = ObjectModel\DataObject::factory($this->_property->getParameter('instanceof')); if (($property = $do->getProperty($name)) !== false) { $this->_condition = new self($property); return $this->_condition; } throw new Exception(array("CONDITION_UNKNOWN_PROPERTY", $name)); }
public function find(ObjectModel\Collection $collection) { $class = $collection->getDataObject()->getClass(); $mode = $collection->getParameter('memberType'); $expr = ''; $this->_setRessource($class); /* @var $condition t41_Condition */ foreach ($collection->getConditions() as $conditionArray) { $condition = $conditionArray[0]; // map property to field if ($this->_mapper) { $field = $this->_mapper->propertyToDatastoreName($class, $condition->getProperty()->getId()); } else { $field = $condition->getProperty()->getId(); } if ($expr) { switch ($conditionArray[1]) { case 'OR': $expr .= ' or '; break; case 'AND': default: $expr .= ' and '; break; } } $expr .= sprintf("%s %s '%s'", $field, is_numeric($condition->getOperator()) ? $this->_operators[$condition->getOperator()] : $condition->getOperator(), $condition->getValue()); } // get all nodes id $result = $this->_findNodes($expr, '@id'); $dataSet = array(); foreach ($result as $node) { $dataSet[] = $node->nodeValue; } if (count($collection->getSortings()) > 0) { $sort = array(); foreach ($collection->getSortings() as $key => $sorting) { if ($this->_mapper) { $field = $this->_mapper->propertyToDatastoreName($class, $sorting[0]->getId()); } else { $field = $sorting[0]->getId(); } $sort = $this->_sortNodes($sort, $field, $sorting[1], $key == 0 ? $dataSet : null); } } // Flatten array $sort = $this->_arrayflat($sort); //Zend_Debug::dump($sort); $array = array(); $uri = new ObjectModel\ObjectUri(); $uri->setBackendUri($this->_uri); $uri->setClass($class); if ($mode != 'uri') { $do = new ObjectModel\DataObject($class); } $count = $collection->getBoundaryOffset(); $limit = $count + $collection->getBoundaryBatch(); /* iterate over result set as long as requested */ while ($count < $limit) { if (!isset($dataSet[$count])) { // if end of result data set has been reached, return array return $array; } $id = $dataSet[$count]; $uri->setUrl($this->_alias . '/' . $id); switch ($mode) { case 'uri': $data = clone $uri; break; case 'data': $do->setUri(clone $uri); $do->populate(); $data = clone $do; break; case 'model': $do->setUri(clone $uri); $do->populate(); /* @var $obj t41_Object_Model */ $data = new $class(null, null, clone $do); break; } $array[] = $data; $count++; } return $array; }
public function delete(ObjectModel\DataObject $do) { return unlink($this->_basePath . $do->getUri()->getUrl()); }