Exemple #1
0
    /**
     * Adds support for magic finders.
     *
     * @return array|object The found entity/entities.
     * @throws BadMethodCallException  If the method called is an invalid find* method
     *                                 or no find* method at all and therefore an invalid
     *                                 method call.
     */
    public function __call($method, $arguments)
    {
        if (substr($method, 0, 6) == 'findBy') {
            $by = substr($method, 6, strlen($method));
            $method = 'findBy';
        } else if (substr($method, 0, 9) == 'findOneBy') {
            $by = substr($method, 9, strlen($method));
            $method = 'findOneBy';
        } else {
            throw new \BadMethodCallException(
                "Undefined method '$method'. The method name must start with ".
                "either findBy or findOneBy!"
            );
        }

        if ( !isset($arguments[0])) {
            // we dont even want to allow null at this point, because we cannot (yet) transform it into IS NULL.
            throw ORMException::findByRequiresParameter($method.$by);
        }

        $fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by));

        if ($this->_class->hasField($fieldName) || $this->_class->hasAssociation($fieldName)) {
            return $this->$method(array($fieldName => $arguments[0]));
        } else {
            throw ORMException::invalidFindByCall($this->_entityName, $fieldName, $method.$by);
        }
    }
 /**
  * Adds support for magic finders.
  *
  * @return array|object The found entity/entities.
  * @throws BadMethodCallException  If the method called is an invalid find* method
  *                                 or no find* method at all and therefore an invalid
  *                                 method call.
  */
 public function __call($method, $arguments)
 {
     if (substr($method, 0, 6) == 'findBy') {
         $by = substr($method, 6, strlen($method));
         $method = 'findBy';
     } else {
         if (substr($method, 0, 9) == 'findOneBy') {
             $by = substr($method, 9, strlen($method));
             $method = 'findOneBy';
         } else {
             throw new \BadMethodCallException("Undefined method '{$method}'. The method name must start with " . "either findBy or findOneBy!");
         }
     }
     if (!isset($arguments[0])) {
         throw ORMException::findByRequiresParameter($method . $by);
     }
     $fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by));
     if ($this->_class->hasField($fieldName)) {
         return $this->{$method}(array($fieldName => $arguments[0]));
     } else {
         throw ORMException::invalidFindByCall($this->_entityName, $fieldName, $method . $by);
     }
 }
 /**
  * Adds support for magic finders.
  *
  * @return array|object The found entity/entities.
  * @throws BadMethodCallException  If the method called is an invalid find* method
  *                                 or no find* method at all and therefore an invalid
  *                                 method call.
  */
 public function __call($method, $arguments)
 {
     if (substr($method, 0, 6) == 'findBy') {
         $by = substr($method, 6, strlen($method));
         $method = 'findBy';
     } else {
         if (substr($method, 0, 9) == 'findOneBy') {
             $by = substr($method, 9, strlen($method));
             $method = 'findOneBy';
         } else {
             throw new \BadMethodCallException("Undefined method '{$method}'.");
         }
     }
     if (!isset($arguments[0])) {
         throw DoctrineException::findByNameRequired();
     }
     $fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by));
     if ($this->_class->hasField($fieldName)) {
         return $this->{$method}(array($fieldName => $arguments[0]));
     } else {
         throw \Doctrine\Common\DoctrineException::invalidFindBy($by);
     }
 }
 /**
  * Adds support for magic finders.
  *
  * @return array|object The found entity/entities.
  * @throws BadMethodCallException  If the method called is an invalid find* method
  *                                 or no find* method at all and therefore an invalid
  *                                 method call.
  */
 public function __call($method, $arguments)
 {
     switch (true) {
         case substr($method, 0, 6) == 'findBy':
             $by = substr($method, 6, strlen($method));
             $method = 'findBy';
             break;
         case substr($method, 0, 9) == 'findOneBy':
             $by = substr($method, 9, strlen($method));
             $method = 'findOneBy';
             break;
         default:
             throw new \BadMethodCallException("Undefined method '{$method}'. The method name must start with " . "either findBy or findOneBy!");
     }
     if (empty($arguments)) {
         throw ORMException::findByRequiresParameter($method . $by);
     }
     $fieldName = lcfirst(\Doctrine\Common\Util\Inflector::classify($by));
     if ($this->_class->hasField($fieldName) || $this->_class->hasAssociation($fieldName)) {
         return $this->{$method}(array($fieldName => $arguments[0]));
     }
     throw ORMException::invalidFindByCall($this->_entityName, $fieldName, $method . $by);
 }
 /**
  * This function saves the data of an entity to its class.
  * This only prepares the database store, but does not store it in database
  * To store them in database use persist and flush from doctrine
  *
  * @access protected
  * @param object $entity object of the class we want to save
  * @param Doctrine\ORM\Mapping\ClassMetadata $entityClassMetadata MetaData for the entity
  * @param array $entityData array with data to save to class
  * @param string $associatedTo the class which is oneToManyAssociated if it exists
  */
 protected function savePropertiesToClass($entity, $entityClassMetadata, $entityData = array(), $associatedTo = '')
 {
     // if entityData is not set, we use $_POST as default, because the data are normally submitted over post
     if (empty($entityData)) {
         $entityData = $_POST;
     }
     $cx = \Cx\Core\Core\Controller\Cx::instanciate();
     $em = $cx->getDb()->getEntityManager();
     $primaryKeyName = $entityClassMetadata->getSingleIdentifierFieldName();
     //get primary key name
     $entityColumnNames = $entityClassMetadata->getColumnNames();
     //get the names of all fields
     //If the view is sortable, get the 'sortBy' field name and store it to the variable
     $sortByFieldName = isset($this->options['functions']['sortBy']) && isset($this->options['functions']['sortBy']['field']) && !empty($this->options['functions']['sortBy']['field']) ? key($this->options['functions']['sortBy']['field']) : '';
     //check the 'sortBy' field is self-healing or not
     $isSortSelfHealing = isset($this->options['fields']) && isset($this->options['fields'][$sortByFieldName]) && isset($this->options['fields'][$sortByFieldName]['showDetail']) && !$this->options['fields'][$sortByFieldName]['showDetail'] ? true : false;
     // Foreach possible attribute in the database we try to find the matching entry in the $entityData array and add it
     // as property to the object
     foreach ($entityColumnNames as $column) {
         $name = $entityClassMetadata->getFieldName($column);
         $fieldSetMethodName = 'set' . preg_replace('/_([a-z])/', '\\1', ucfirst($name));
         $fieldGetMethodName = 'get' . preg_replace('/_([a-z])/', '\\1', ucfirst($name));
         if (isset($this->options['fields']) && isset($this->options['fields'][$name]) && isset($this->options['fields'][$name]['storecallback'])) {
             $storecallback = $this->options['fields'][$name]['storecallback'];
             $postedValue = null;
             if (isset($entityData[$name])) {
                 $postedValue = contrexx_input2raw($entityData[$name]);
             }
             /* We use json to do the storecallback. The 'else if' is for backwards compatibility so you can declare
              * the function directly without using json. This is not recommended and not working over session */
             if (is_array($storecallback) && isset($storecallback['adapter']) && isset($storecallback['method'])) {
                 $json = new \Cx\Core\Json\JsonData();
                 $jsonResult = $json->data($storecallback['adapter'], $storecallback['method'], array('postedValue' => $postedValue));
                 if ($jsonResult['status'] == 'success') {
                     $entityData[$name] = $jsonResult["data"];
                 }
             } else {
                 if (is_callable($storecallback)) {
                     $entityData[$name] = $storecallback($postedValue);
                 }
             }
         }
         if (isset($entityData[$name]) && $name != $primaryKeyName) {
             $fieldDefinition = $entityClassMetadata->getFieldMapping($name);
             if ($fieldDefinition['type'] == 'datetime') {
                 $newValue = new \DateTime($entityData[$name]);
             } elseif ($fieldDefinition['type'] == 'array') {
                 $newValue = unserialize($entityData[$name]);
                 // verify that the value is actually an array -> prevent to store other php data
                 if (!is_array($newValue)) {
                     $newValue = array();
                 }
             } else {
                 $newValue = contrexx_input2raw($entityData[$name]);
             }
             // set the value as property of the current object, so it is ready to be stored in the database
             $entity->{$fieldSetMethodName}($newValue);
         }
         //While adding a new entity, if the view is sortable and 'sortBy' field is disabled in the edit view
         //then the new entity sort order gets automatically adjusted.
         if ($isSortSelfHealing && !empty($sortByFieldName) && $sortByFieldName === $name && !$entity->{$fieldGetMethodName}()) {
             $qb = $em->createQueryBuilder();
             $qb->select('e')->from(get_class($entity), 'e')->orderBy('e.' . $name, 'DESC')->setMaxResults(1);
             $result = $qb->getQuery()->getResult();
             $newValue = isset($result[0]) ? $result[0]->{$fieldGetMethodName}() + 1 : 1;
             // set the value as property of the current object,
             // so it is ready to be stored in the database
             $entity->{$fieldSetMethodName}($newValue);
         }
     }
     // save singleValuedAssociations
     foreach ($entityClassMetadata->getAssociationMappings() as $associationMapping) {
         // we're only interested in single valued associations here, so skip others
         if (!$entityClassMetadata->isSingleValuedAssociation($associationMapping['fieldName'])) {
             continue;
         }
         // we're only interested if there's a target entity other than $associatedTo, so skip others
         if ($associationMapping['targetEntity'] == '' || $associatedTo == $associationMapping['targetEntity']) {
             continue;
         }
         // save it:
         // case a) was open in form directly
         $firstOffset = str_replace('\\', '_', strtolower($associationMapping['sourceEntity']));
         $secondOffset = $associationMapping['fieldName'];
         if (isset($entityData[$secondOffset])) {
             $this->storeSingleValuedAssociation($associationMapping['targetEntity'], array($associationMapping['joinColumns'][0]['referencedColumnName'] => $entityData[$secondOffset]), $entity, 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $associationMapping['fieldName']))));
             continue;
         }
         // base b) was open in a modal form
         foreach ($_POST[$firstOffset] as $foreignEntityDataEncoded) {
             $foreignEntityData = array();
             parse_str($foreignEntityDataEncoded, $foreignEntityData);
             if (!isset($foreignEntityData[$secondOffset])) {
                 // todo: remove entity!
                 continue;
             }
             // todo: add/save entity
             $this->storeSingleValuedAssociation($associationMapping['targetEntity'], array($associationMapping['joinColumns'][0]['referencedColumnName'] => $foreignEntityData[$secondOffset]), $entity, 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $associationMapping['fieldName']))));
         }
     }
 }
 public function testLoadPrefixedMetadata()
 {
     $this->_generator->setAnnotationPrefix('ORM\\');
     $metadata = $this->generateBookEntityFixture();
     $reader = new \Doctrine\Common\Annotations\AnnotationReader();
     $driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader, array());
     $book = $this->newInstance($metadata);
     $cm = new \Doctrine\ORM\Mapping\ClassMetadata($metadata->name);
     $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService());
     $driver->loadMetadataForClass($cm->name, $cm);
     $this->assertEquals($cm->columnNames, $metadata->columnNames);
     $this->assertEquals($cm->getTableName(), $metadata->getTableName());
     $this->assertEquals($cm->lifecycleCallbacks, $metadata->lifecycleCallbacks);
     $this->assertEquals($cm->identifier, $metadata->identifier);
     $this->assertEquals($cm->idGenerator, $metadata->idGenerator);
     $this->assertEquals($cm->customRepositoryClassName, $metadata->customRepositoryClassName);
 }
 public function testClassWithSleepProxyGeneration()
 {
     $className = "\\Doctrine\\Tests\\ORM\\Proxy\\SleepClass";
     $proxyName = "DoctrineTestsORMProxySleepClassProxy";
     $classMetadata = new \Doctrine\ORM\Mapping\ClassMetadata($className);
     $classMetadata->mapField(array('fieldName' => 'id', 'type' => 'integer'));
     $classMetadata->setIdentifier(array('id'));
     $this->_proxyFactory->generateProxyClasses(array($classMetadata));
     $classCode = file_get_contents(dirname(__FILE__) . "/generated/" . $proxyName . ".php");
     $this->assertEquals(1, substr_count($classCode, 'function __sleep'));
 }
Exemple #8
0
 /**
  * Gibt ein Entity-Meta für ein Entity zurück
  *
  * ein EntityMeta enthält jede Menge Labels, URLs, und weitere Infos über das Entity im CMS (in verschiedenen Contexten)
  *
  * Ich habe lange überlegt, wo die "zentrale" Stelle für die EntityMetas sein soll und mich für das Modul entschieden, da es sowohl im DCPackage ist (und damit im Controller eines EntityServices)
  * sowohl auch in einer "Main" vorhanden sein muss (und man es damit injecten kann)
  * 
  * EntityMetas die hier erzeugt werden haben die ClassMetadata von Doctrine aus der übergebenen Connection bzw EntityManager
  * @param string|NULL|EntityManager|Doctrine\ORM\Mapping\ClassMetadata $classMetadataInjection der Manager nach dem nach der ClassMetadata gefragt wird angeben durch $con oder durch einen EntityManager, oder die ClassMetadata selbst
  */
 public function getEntityMeta($entityName, $classMetadataInjection = NULL)
 {
     $entityClass = $this->getEntityName($entityName);
     // normalize
     // cache
     if (!array_key_exists($entityClass, $this->entityMetas)) {
         if ($classMetadataInjection instanceof EntityManager) {
             $classMetadata = $classMetadataInjection->getClassMetadata($entityClass);
         } elseif ($classMetadataInjection instanceof \Doctrine\ORM\Mapping\ClassMetadata) {
             $classMetadata = $classMetadataInjection;
         } else {
             $classMetadata = $this->getEntityManager($classMetadataInjection)->getClassMetadata($entityClass);
         }
         // erstelle ein "doofes" EntityMeta ohne viele Infos
         $meta = new \Psc\CMS\EntityMeta($entityClass, $classMetadata, $entityName);
         $this->entityMetas[$entityClass] = $meta;
         $this->manager->dispatchEvent('Psc.Doctrine.initEntityMeta', (object) array('module' => $this), $meta);
     }
     return $this->entityMetas[$entityClass];
 }
 /**
  * Executes all entity deletions for entities of the specified type.
  *
  * @param Doctrine\ORM\Mapping\ClassMetadata $class
  */
 private function _executeDeletions($class)
 {
     $className = $class->name;
     $persister = $this->getEntityPersister($className);
     $hasLifecycleCallbacks = isset($class->lifecycleCallbacks[Events::postRemove]);
     $hasListeners = $this->_evm->hasListeners(Events::postRemove);
     foreach ($this->_entityDeletions as $oid => $entity) {
         if (get_class($entity) == $className || $entity instanceof Proxy && $entity instanceof $className) {
             $persister->delete($entity);
             unset($this->_entityDeletions[$oid], $this->_entityIdentifiers[$oid], $this->_originalEntityData[$oid]);
             // Entity with this $oid after deletion treated as NEW, even if the $oid
             // is obtained by a new entity because the old one went out of scope.
             $this->_entityStates[$oid] = self::STATE_NEW;
             if ($hasLifecycleCallbacks) {
                 $class->invokeLifecycleCallbacks(Events::postRemove, $entity);
             }
             if ($hasListeners) {
                 $this->_evm->dispatchEvent(Events::postRemove, new LifecycleEventArgs($entity, $this->_em));
             }
         }
     }
 }
 /**
  * @group DDC-1771
  */
 public function testSkipAbstractClassesOnGeneration()
 {
     $cm = new \Doctrine\ORM\Mapping\ClassMetadata(__NAMESPACE__ . '\\AbstractClass');
     $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService());
     $this->assertNotNull($cm->reflClass);
     $num = $this->_proxyFactory->generateProxyClasses(array($cm));
     $this->assertEquals(0, $num, "No proxies generated.");
 }