/** * Implementation of filterSet() to call set on Translation relationship to allow * access to I18n properties from the main object. * * @param Doctrine_Record $record * @param string $name Name of the property * @param string $value Value of the property * @return void */ public function filterSet(Doctrine_Record $record, $fieldName, $value) { $translation = $record->get('Translation'); $culture = myDoctrineRecord::getDefaultCulture(); if ($translation->contains($culture)) { $i18n = $record->get('Translation')->get($culture); } else { $i18n = $record->get('Translation')->get($culture); /* * If translation is new * populate it with i18n fallback */ if ($i18n->state() == Doctrine_Record::STATE_TDIRTY) { if ($fallback = $record->getI18nFallBack()) { $fallBackData = $fallback->toArray(); unset($fallBackData['id'], $fallBackData['lang']); $i18n->fromArray($fallBackData); } } } if (!ctype_lower($fieldName) && !$i18n->contains($fieldName)) { $underscoredFieldName = dmString::underscore($fieldName); if (strpos($underscoredFieldName, '_') !== false && $i18n->contains($underscoredFieldName)) { $fieldName = $underscoredFieldName; } } $i18n->set($fieldName, $value); return $value; }
function updatedAtBy(Doctrine_Record $record) { $user = $record->get('UpdatedBy'); if ($user && $user->isNew()) { $user = null; } return format_date($record->get('updated_at'), 'f') . ($user ? ' - ' . $user : ''); }
protected function doPreSave(Doctrine_Record $record, sfForm $form) { // loop through relations if ($relations = $form->getOption('dynamic_relations')) { foreach ($relations as $field => $config) { $collection = $record->get($config['relation']->getAlias()); // collect form objects for comparison $search = array(); foreach ($form->getEmbeddedForm($field)->getEmbeddedForms() as $i => $embed) { $search[] = $embed->getObject(); } foreach ($collection as $i => $object) { if (false === ($pos = array_search($object, $search, true))) { // if a related object exists in the record but isn't represented // in the form, the reference has been removed $collection->remove($i); // if the foreign column is a notnull columns, delete the object $column = $config['relation']->getTable()->getColumnDefinition($config['relation']->getForeignColumnName()); if ($object->exists() && isset($column['notnull']) && $column['notnull']) { $object->delete(); } } } } } }
public function get($name, $load = true) { if ($name === 'content') { return file_get_contents(parent::get('url')); } return parent::get($name, $load); }
/** * fetchRelatedFor * * fetches a component related to given record * * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $localFieldName = $record->getTable()->getFieldName($this->definition['local']); $id = $record->get($localFieldName); if (is_null($id) || ! $this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); // Ticket #1131 Patch. if ( ! is_null($id)) { $related->assignIdentifier($id); $related->state(Doctrine_Record::STATE_PROXY); } } else { $dql = 'FROM ' . $this->getTable()->getComponentName() . ' WHERE ' . $this->getCondition() . $this->getOrderBy(null, false); $related = $this->getTable() ->getConnection() ->query($dql, array($id)) ->getFirst(); if ( ! $related || empty($related)) { $related = $this->getTable()->create(); } } $record->set($localFieldName, $id, false); return $related; }
/** * fetchRelatedFor * * fetches a component related to given record * * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $id = array(); $localTable = $record->getTable(); foreach ((array) $this->definition['local'] as $local) { $value = $record->get($localTable->getFieldName($local)); if (isset($value)) { $id[] = $value; } } if ($this->isOneToOne()) { if (!$record->exists() || empty($id) || !$this->definition['table']->getAttribute(Doctrine::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); } else { $dql = 'FROM ' . $this->getTable()->getComponentName() . ' WHERE ' . $this->getCondition(); $coll = $this->getTable()->getConnection()->query($dql, $id); $related = $coll[0]; } $related->set($related->getTable()->getFieldName($this->definition['foreign']), $record, false); } else { if (!$record->exists() || empty($id) || !$this->definition['table']->getAttribute(Doctrine::ATTR_LOAD_REFERENCES)) { $related = Doctrine_Collection::create($this->getTable()); } else { $query = $this->getRelationDql(1); $related = $this->getTable()->getConnection()->query($query, $id); } $related->setReference($record, $this); } return $related; }
protected function doPreSave(Doctrine_Record $record, sfForm $form) { // loop through relations if ($relations = $form->getOption('dynamic_relations')) { foreach ($relations as $field => $config) { $collection = $record->get($config['relation']->getAlias()); // collect form objects for comparison $search = array(); try { foreach ($form->getEmbeddedForm($field)->getEmbeddedForms() as $i => $embed) { $search[] = $embed->getObject(); } } catch (InvalidArgumentException $e) { // previously embedded form was removed at the end of form.filter_values as there were no values for it. // @see sfDoctrineDynamicFormRelations::correctValidators() } foreach ($collection as $i => $object) { $pos = array_search($object, $search, true); if (false === $pos && $this->filterObject($object, $config['arguments'])) { // if a related object exists in the record but isn't represented // in the form, the reference has been removed $collection->remove($i); // if the foreign column is a notnull columns, delete the object $column = $config['relation']->getTable()->getColumnDefinition($config['relation']->getForeignColumnName()); if ($object->exists() && isset($column['notnull']) && $column['notnull']) { $object->delete(); } } } } } }
/** * Get a record attribute. Allows overriding Doctrine record accessors with Propel style functions * * @param string $name * @param string $load * @return void */ public function get($name, $load = true) { $getter = 'get' . Doctrine_Inflector::classify($name); if (method_exists($this, $getter)) { return $this->{$getter}($load); } return parent::get($name, $load); }
public function get($column, $load = true) { $val = parent::get($column, $load); if (is_resource($val)) { $val = stream_get_contents($val); } if ($col = $this->getTable()->getColumnDefinition($column)) { if ($col["type"] == 'blob') { $val = base64_decode($val); } } return $val; }
/** * Get the version * * @param Doctrine_Record $record * @param mixed $version * @return array An array with version information */ public function getVersion(Doctrine_Record $record, $version) { $className = $this->_options['className']; $q = new Doctrine_Query(); $values = array(); foreach ((array) $this->_options['table']->getIdentifier() as $id) { $conditions[] = $className . '.' . $id . ' = ?'; $values[] = $record->get($id); } $where = implode(' AND ', $conditions) . ' AND ' . $className . '.' . $this->_options['versionColumn'] . ' = ?'; $values[] = $version; $q->from($className)->where($where); return $q->execute($values, Doctrine::HYDRATE_ARRAY); }
/** * fetchRelatedFor * * fetches a component related to given record * * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->get($this->definition['local']); if (empty($id) || !$this->definition['table']->getAttribute(Doctrine::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); } else { $related = $this->getTable()->find($id); if (!$related) { $related = $this->getTable()->create(); } } $record->set($this->definition['local'], $related, false); return $related; }
/** * fetchRelatedFor * * fetches a component related to given record * * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $id = $record->get($this->definition['local']); if (empty($id) || !$this->definition['table']->getAttribute(Doctrine::ATTR_LOAD_REFERENCES)) { $related = $this->getTable()->create(); } else { $dql = 'FROM ' . $this->getTable()->getComponentName() . ' WHERE ' . $this->getCondition(); $related = $this->getTable()->getConnection()->query($dql, array($id))->getFirst(); if (!$related || empty($related)) { $related = $this->getTable()->create(); } } $record->set($this->definition['local'], $related, false); return $related; }
public function getDistance(Doctrine_Record $record, $kilometers = false) { $query = $this->getDistanceQuery($kilometers); $conditions = array(); $values = array(); foreach ((array) $record->getTable()->getIdentifier() as $id) { $conditions[] = $query->getRootAlias() . '.' . $id . ' = ?'; $values[] = $record->get($id); } $where = implode(' AND ', $conditions); $query->addWhere($where, $values); $query->limit(1); $result = $query->execute()->getFirst(); if (isset($result['kilometers']) && $result['miles']) { return $kilometers ? $result->get('kilometers') : $result->get('miles'); } else { return 0; } }
public function buildIntegrityRelationQuery(Doctrine_Record $record) { $q = new Doctrine_Query(); $aliases = array(); $indexes = array(); $root = $record->getTable()->getComponentName(); $rootAlias = strtolower(substr($root, 0, 1)); $aliases[$rootAlias] = $root; foreach ((array) $record->getTable()->getIdentifier() as $id) { $field = $rootAlias . '.' . $id; $cond[] = $field . ' = ?'; $fields[] = $field; $params = $record->get($id); } $fields = implode(', ', $fields); $components[] = $root; $this->buildIntegrityRelations($record->getTable(), $aliases, $fields, $indexes, $components); $q->select($fields)->from($root . ' ' . $rootAlias); foreach ($aliases as $alias => $name) { $q->leftJoin($rootAlias . '.' . $name . ' ' . $alias); } $q->where(implode(' AND ', $cond)); return $q->execute(array($params)); }
/** * Return a recrd as XML. * * In order to control how this is done set the "xml" option in a record. * This option is an array that has the keys "ignore_fields" and "include_relations". Both of these are arrays that list the name of fields/relations to include/process. * * If you want to insert this xml as a part inside another xml send a * SimpleXMLElement to the function. Because of the nature of SimpleXML the * content you add to this element will be avilable after the function is * complete. * * @param Doctrine_Record $record * @param SimpleXMLElement $xml * @return string Xml as string */ public static function getRecordAsXml(Doctrine_Record $record, SimpleXMlElement $incomming_xml = NULL) { $recordname = $record->getTable()->tableName; if (!isset($incomming_xml)) { $new_xml_string = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><" . $recordname . "></" . $recordname . ">"; $xml = new SimpleXMLElement($new_xml_string); } else { $xml = $incomming_xml->addChild($recordname); } foreach ($record->obtainIdentifier() as $pk_field => $pk_value) { $xml->addChild($pk_field, $pk_value); } $xml_options = $record->option("xml"); if (isset($xml_options["record_name"])) { $recordname = $xml_options["record_name"]; } foreach ($record->getData() as $field => $value) { if (isset($xml_options["ignore_fields"]) && !in_array($field, $xml_options["ignore_fields"]) || !isset($xml_options["ignore_fields"])) { if ($value instanceof Doctrine_Null) { $xml->addChild($field); } else { $xml->addChild($field, $value); } } } if (!isset($xml_options["include_relations"])) { return $xml->asXML(); } $relations = $record->getTable()->getRelations(); foreach ($relations as $name => $relation) { if (in_array($name, $xml_options["include_relations"])) { $relation_type = $relation->getType(); $related_records = $record->get($name); if ($relation_type == Doctrine_Relation::ONE && $related_records instanceof Doctrine_Record) { Doctrine_Lib::getRecordAsXml($related_records, $xml); } else { Doctrine_Lib::getCollectionAsXml($related_records, $xml); } } } return $xml->asXML(); }
/** * saveRelatedLocalKeys * saves all related (through LocalKey) records to $record * * @throws PDOException if something went wrong at database level * @param Doctrine_Record $record */ public function saveRelatedLocalKeys(Doctrine_Record $record) { $state = $record->state(); $record->state($record->exists() ? Doctrine_Record::STATE_LOCKED : Doctrine_Record::STATE_TLOCKED); foreach ($record->getReferences() as $k => $v) { $rel = $record->getTable()->getRelation($k); $local = $rel->getLocal(); $foreign = $rel->getForeign(); if ($rel instanceof Doctrine_Relation_LocalKey) { // ONE-TO-ONE relationship $obj = $record->get($rel->getAlias()); // Protection against infinite function recursion before attempting to save if ($obj instanceof Doctrine_Record && $obj->isModified()) { $obj->save($this->conn); $id = array_values($obj->identifier()); if (!empty($id)) { foreach ((array) $rel->getLocal() as $k => $columnName) { $field = $record->getTable()->getFieldName($columnName); if (isset($id[$k]) && $id[$k] && $record->getTable()->hasField($field)) { $record->set($field, $id[$k]); } } } } } } $record->state($state); }
/** * Create and return a unique key for the the given record * * @author Florian Zumkeller-Quast <*****@*****.**> * * @since 2010-07-02 * * @param Doctrine_Record $record The record to create the object key for * * @return string The object key for the given record */ private function getObjectKey(Doctrine_Record $record) { $fields = $record->getTable()->getIdentifier(); // Check if its a composite PK if (is_array($fields) === false) { $fields = array($fields); } $key = ''; foreach ($fields as $field) { $value = $record->get($field); $key = sprintf('%s|%s:%s', $key, $field, base64_encode($value)); } return sha1($key); }
/** * saveRelated * saves all related records to $record * * @throws PDOException if something went wrong at database level * @param Doctrine_Record $record */ public function saveRelated(Doctrine_Record $record) { $saveLater = array(); foreach ($record->getReferences() as $k => $v) { $rel = $record->getTable()->getRelation($k); $local = $rel->getLocal(); $foreign = $rel->getForeign(); if ($rel instanceof Doctrine_Relation_ForeignKey) { $saveLater[$k] = $rel; } else { if ($rel instanceof Doctrine_Relation_LocalKey) { // ONE-TO-ONE relationship $obj = $record->get($rel->getAlias()); // Protection against infinite function recursion before attempting to save if ($obj instanceof Doctrine_Record && $obj->isModified()) { $obj->save($this->conn); $id = array_values($obj->identifier()); if (!empty($id)) { foreach ((array) $rel->getLocal() as $k => $field) { if (isset($id[$k]) && $id[$k] && $record->getTable()->hasField($k)) { $record->set($field, $id[$k]); } } } } } } } return $saveLater; }
/** * Get the max version number for a given Doctrine_Record * * @param Doctrine_Record $record * @return Integer $versionnumber */ public function getMaxVersion(Doctrine_Record $record) { $className = $this->_options['className']; $select = 'MAX(' . $className . '.' . $this->_options['version']['name'] . ') max_version'; foreach ((array) $this->_options['table']->getIdentifier() as $id) { $conditions[] = $className . '.' . $id . ' = ?'; $values[] = $record->get($id); } // Lock the version table using 'FOR UPDATE' $q = Doctrine_Core::getTable($className)->createQuery()->select($select)->forUpdate()->where(implode(' AND ', $conditions)); // Try to execute the FOR UPDATE query // this can result in a deadlock, in which case we should try again $querySucceeded = false; $num = 0; do { try { $result = $q->execute($values, Doctrine_Core::HYDRATE_ARRAY); $querySucceeded = true; } catch (Doctrine_Connection_Exception $e) { if (++$num > 10 || strpos($e->getMessage(), 'SQLSTATE[40001]') === false) { // not a deadlock, or more than 10 tries? rethrow exception throw $e; } } } while (!$querySucceeded); return isset($result[0]['max_version']) ? $result[0]['max_version'] : 0; }
/** * adds a record to collection * @param Doctrine_Record $record record to be added * @param string $key optional key for the record * @return boolean */ public function add(Doctrine_Record $record, $key = null) { if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocal()); if ($value !== null) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } } /** * for some weird reason in_array cannot be used here (php bug ?) * * if used it results in fatal error : [ nesting level too deep ] */ foreach ($this->data as $val) { if ($val === $record) { return false; } } if (isset($key)) { if (isset($this->data[$key])) { return false; } $this->data[$key] = $record; return true; } if (isset($this->keyColumn)) { $value = $record->get($this->keyColumn); if ($value === null) { throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '" . $this->keyColumn . "' was null."); } $this->data[$value] = $record; } else { $this->data[] = $record; } return true; }
/** * Get the max version number for a given Doctrine_Record * * @param Doctrine_Record $record * @return Integer $versionnumber */ public function getMaxVersion(Doctrine_Record $record) { $className = $this->_options['className']; $select = 'MAX(' . $className . '.' . $this->_options['version']['name'] . ') max_version'; foreach ((array) $this->_options['table']->getIdentifier() as $id) { $conditions[] = $className . '.' . $id . ' = ?'; $values[] = $record->get($id); } $q = Doctrine_Query::create($record->getTable()->getConnection())->select($select)->from($className)->where(implode(' AND ', $conditions)); $result = $q->execute($values, Doctrine_Core::HYDRATE_ARRAY); return isset($result[0]['max_version']) ? $result[0]['max_version'] : 0; }
/** * Adds a record to collection * * @param Doctrine_Record $record record to be added * @param string $key optional key for the record * @return boolean */ public function add($record, $key = null) { if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocalFieldName()); if ($value !== null) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } $relations = $this->relation['table']->getRelations(); foreach ($relations as $relation) { if ($this->relation['class'] == $relation['localTable']->getOption('name') && $relation->getLocal() == $this->relation->getForeignFieldName()) { $record->{$relation}['alias'] = $this->reference; break; } } } /** * for some weird reason in_array cannot be used here (php bug ?) * * if used it results in fatal error : [ nesting level too deep ] */ foreach ($this->data as $val) { if ($val === $record) { return false; } } if (isset($key)) { if (isset($this->data[$key])) { return false; } $this->data[$key] = $record; return true; } if (isset($this->keyColumn)) { $value = $record->get($this->keyColumn); if ($value === null) { throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '" . $this->keyColumn . "' was null."); } $this->data[$value] = $record; } else { $this->data[] = $record; } return true; }
protected function renderRelatedRecord(Doctrine_Record $record, Doctrine_Relation $relation) { $value = $record->get($relation->getLocal()); $cacheKey = md5(implode('|', array($this->versionModel, $relation->getClass(), $value))); if (isset($this->relatedRecordCache[$cacheKey])) { return $this->relatedRecordCache[$cacheKey]; } try { if ('DmMedia' === $relation->getClass()) { $relatedRecord = $relation->getTable()->findOneByIdWithFolder($value); if ($relatedRecord && $relatedRecord->isImage()) { $return = $this->helper->media($relatedRecord)->size($this->getOption('media_width'), $this->getOption('media_height'))->render(); } else { $return = $relatedRecord; } } else { $return = $relation->getTable()->findOneById($value); } } catch (Exception $e) { $return = get_class($relation->getClass()) . ' #' . $value; } return $this->relatedRecordCache[$cacheKey] = $return; }
/** * fetchRelatedFor * * fetches a component related to given record * * @param Doctrine_Record $record * @return Doctrine_Record|Doctrine_Collection */ public function fetchRelatedFor(Doctrine_Record $record) { $id = -1; try { $recId = $record->get($this->getLocalRefFieldName()); if ($recId) { $id = $recId; } else { $id = $record->getIncremented(); } } catch (Exception $e) { $id = $record->getIncremented(); } $this->tmp_rec = $record; if (empty($id) || !$this->definition['table']->getAttribute(Doctrine_Core::ATTR_LOAD_REFERENCES)) { $coll = Doctrine_Collection::create($this->getTable()); } else { $coll = $this->getTable()->getConnection()->query($this->getRelationDql(1), array($id)); } $coll->setReference($record, $this); return $coll; }
public static function copyDoctrineFields(Doctrine_Record $a, Doctrine_Record $b, array $fields) { foreach ($fields as $field) { $b->set($field, $a->get($field)); } }
/** * Refreshs the position of the object * * @param Doctrine_Record $object */ private function refreshPosition(Doctrine_Record $object) { $identifiers = $object->getTable()->getIdentifierColumnNames(); $query = $object->getTable()->createQuery()->select($this->_options['name']); foreach ($identifiers as $identifier) { $query->andWhere($identifier . ' = ?', $object->get($identifier)); } $position = $query->fetchOne(array(), Doctrine::HYDRATE_ARRAY); $object->set($this->_options['name'], $position['position'], false); }
public function onPreUpdate(Doctrine_Record $record) { $versionColumn = $this->_auditLog->getOption('versionColumn'); $version = $record->get($versionColumn); $record->set($versionColumn, ++$version); }
/** * Adds a record to collection * * @param Doctrine_Record $record record to be added * @param string $key optional key for the record * @return boolean */ public function add($record, $key = null) { if (isset($this->referenceField)) { $value = $this->reference->get($this->relation->getLocalFieldName()); if ($value !== null) { $record->set($this->referenceField, $value, false); } else { $record->set($this->referenceField, $this->reference, false); } $relations = $this->relation['table']->getRelations(); foreach ($relations as $relation) { if ($this->relation['class'] == $relation['localTable']->getOption('name') && $relation->getLocal() == $this->relation->getForeignFieldName()) { $record->{$relation}['alias'] = $this->reference; break; } } } $oid = $record->oid(); if (isset($this->oids[$oid])) { return false; } if (isset($key)) { if (isset($this->data[$key])) { return false; } $this->data[$key] = $record; $this->oids[$oid] = true; return true; } if (isset($this->keyColumn)) { $value = $record->get($this->keyColumn); if ($value === null) { throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '" . $this->keyColumn . "' was null."); } $this->data[$value] = $record; } else { $this->data[] = $record; } $this->oids[$oid] = true; return true; }
/** * Creates root node from given record or from a new record. * * Note: When using a tree with multiple root nodes (hasManyRoots), you MUST pass in a * record to use as the root. This can either be a new/transient record that already has * the root id column set to some numeric value OR a persistent record. In the latter case * the records id will be assigned to the root id. You must use numeric columns for the id * and root id columns. * * @param object $record instance of Doctrine_Record */ public function createRoot(Doctrine_Record $record = null) { if ($this->getAttribute('hasManyRoots')) { if (!$record || !$record->exists() && !$record->getNode()->getRootValue() || $record->getTable()->isIdentifierComposite()) { throw new Doctrine_Tree_Exception("Node must have a root id set or must " . " be persistent and have a single-valued numeric primary key in order to" . " be created as a root node. Automatic assignment of a root id on" . " transient/new records is no longer supported."); } if ($record->exists() && !$record->getNode()->getRootValue()) { // Default: root_id = id $identifier = $record->getTable()->getIdentifier(); $record->getNode()->setRootValue($record->get($identifier)); } } if (!$record) { $record = $this->table->create(); } $record->set('lft', '1'); $record->set('rgt', '2'); $record->set('level', 0); $record->save(); return $record; }
/** * deletes all related composites * this method is always called internally when a record is deleted * * @throws PDOException if something went wrong at database level * @return void */ public function deleteComposites(Doctrine_Record $record) { foreach ($record->getTable()->getRelations() as $fk) { switch ($fk->getType()) { case Doctrine_Relation::ONE_COMPOSITE: case Doctrine_Relation::MANY_COMPOSITE: $obj = $record->get($fk->getAlias()); if ($obj instanceof Doctrine_Record && $obj->state() != Doctrine_Record::STATE_LOCKED) { $obj->delete($this->conn); } break; } } }