/** * Overrides the base getFormSpecification() to additionally iterate through each * field/association in the metadata and trigger the associated event. * * This allows building of a form from metadata instead of requiring annotations. * Annotations are still allowed through the ElementAnnotationsListener. * * {@inheritDoc} */ public function getFormSpecification($entity) { $formSpec = parent::getFormSpecification($entity); $metadata = $this->objectManager->getClassMetadata(is_object($entity) ? get_class($entity) : $entity); $inputFilter = $formSpec['input_filter']; foreach ($formSpec['elements'] as $key => $elementSpec) { $name = isset($elementSpec['spec']['name']) ? $elementSpec['spec']['name'] : null; if (!$name) { continue; } if (!isset($inputFilter[$name])) { $inputFilter[$name] = new \ArrayObject(); } $params = array('metadata' => $metadata, 'name' => $name, 'elementSpec' => $elementSpec, 'inputSpec' => $inputFilter[$name]); if ($this->checkForExcludeElementFromMetadata($metadata, $name)) { $elementSpec = $formSpec['elements']; unset($elementSpec[$key]); $formSpec['elements'] = $elementSpec; if (isset($inputFilter[$name])) { unset($inputFilter[$name]); } $formSpec['input_filter'] = $inputFilter; continue; } if ($metadata->hasField($name)) { $this->getEventManager()->trigger(static::EVENT_CONFIGURE_FIELD, $this, $params); } elseif ($metadata->hasAssociation($name)) { $this->getEventManager()->trigger(static::EVENT_CONFIGURE_ASSOCIATION, $this, $params); } } return $formSpec; }
/** * Overrides the base getFormSpecification() to additionally iterate through each * field/association in the metadata and trigger the associated event. * * This allows building of a form from metadata instead of requiring annotations. * Annotations are still allowed through the ElementAnnotationsListener. * * {@inheritDoc} */ public function getFormSpecification($entity) { $formSpec = parent::getFormSpecification($entity); $metadata = $this->objectManager->getClassMetadata(is_object($entity) ? get_class($entity) : $entity); $inputFilter = $formSpec['input_filter']; $formElements = array('DoctrineModule\\Form\\Element\\ObjectSelect', 'DoctrineModule\\Form\\Element\\ObjectMultiCheckbox', 'DoctrineModule\\Form\\Element\\ObjectRadio'); foreach ($formSpec['elements'] as $key => $elementSpec) { $name = isset($elementSpec['spec']['name']) ? $elementSpec['spec']['name'] : null; $isFormElement = isset($elementSpec['spec']['type']) && in_array($elementSpec['spec']['type'], $formElements); if (!$name) { continue; } if (!isset($inputFilter[$name])) { $inputFilter[$name] = new \ArrayObject(); } $params = array('metadata' => $metadata, 'name' => $name, 'elementSpec' => $elementSpec, 'inputSpec' => $inputFilter[$name]); if ($this->checkForExcludeElementFromMetadata($metadata, $name)) { $elementSpec = $formSpec['elements']; unset($elementSpec[$key]); $formSpec['elements'] = $elementSpec; if (isset($inputFilter[$name])) { unset($inputFilter[$name]); } $formSpec['input_filter'] = $inputFilter; continue; } if ($metadata->hasField($name) || !$metadata->hasAssociation($name) && $isFormElement) { $this->getEventManager()->trigger(static::EVENT_CONFIGURE_FIELD, $this, $params); } elseif ($metadata->hasAssociation($name)) { $this->getEventManager()->trigger(static::EVENT_CONFIGURE_ASSOCIATION, $this, $params); } } $formSpec['options'] = array('prefer_form_input_filter' => true); return $formSpec; }
/** * Test setup */ protected function setUp() { // setup entity aliases $this->em = DoctrineTestHelper::createTestEntityManager(); $entityManagerNamespaces = $this->em->getConfiguration()->getEntityNamespaces(); $entityManagerNamespaces['WebtownPhpBannerBundle'] = 'WebtownPhp\\BannerBundle\\Entity'; $this->em->getConfiguration()->setEntityNamespaces($entityManagerNamespaces); // setup schema $schemaTool = new SchemaTool($this->em); $classes = []; foreach ($this->getEntities() as $entityClass) { $classes[] = $this->em->getClassMetadata($entityClass); } try { $schemaTool->dropSchema($classes); } catch (\Exception $e) { } try { $schemaTool->createSchema($classes); } catch (\Exception $e) { } $registry = \Mockery::mock('Doctrine\\Bundle\\DoctrineBundle\\Registry'); $registry->shouldReceive('getManager')->andReturn($this->em); $this->bm = new ORMManager($registry, new EventDispatcher()); }
/** * {@inheritDoc} */ protected function doGetIdentificator($model) { $modelMetadata = $this->objectManager->getClassMetadata(get_class($model)); $id = $modelMetadata->getIdentifierValues($model); if (count($id) > 1) { throw new \LogicException('Storage not support composite primary ids'); } return new Identificator(array_shift($id), $model); }
public function __construct(ObjectManager $om, $accountSignatureClass, $accountOwnerSignatureClass) { $this->om = $om; $this->documentSignatureRepository = $om->getRepository($accountSignatureClass); $this->ownerSignatureRepository = $om->getRepository($accountOwnerSignatureClass); $accountSignatureMetadata = $om->getClassMetadata($accountSignatureClass); $this->accountSignatureClass = $accountSignatureMetadata->getName(); $ownerSignatureMetadata = $om->getClassMetadata($accountOwnerSignatureClass); $this->ownerSignatureClass = $ownerSignatureMetadata->getName(); }
/** * {@inheritDoc} */ public function getOptions($object) { $meta = $this->om->getClassMetadata(get_class($object)); if (!isset($this->options[$meta->name])) { $config = $this->sluggable->getConfiguration($this->om, $meta->name); $options = $config['handlers'][get_called_class()]; $default = array('separator' => '/'); $this->options[$meta->name] = array_merge($default, $options); } return $this->options[$meta->name]; }
/** * @param $command * @param $entity * @param bool $addExtractedEntity * * @return Result */ protected function createResult($command, $entity, $addExtractedEntity = true) { $meta = $this->objectManager->getClassMetadata($this->className); $identifiers = $meta->getIdentifierValues($entity); $result = new Result($command, current($identifiers)); if (!$addExtractedEntity) { return $result; } $data = $this->hydrator->extract($entity); $result->addParams(['item' => $data]); return $result; }
/** * Transforms an array including an identifier to an object. * * @param array $idObject * * @throws TransformationFailedException if object is not found. * * @return object|null */ public function reverseTransform($idObject) { if (!is_array($idObject)) { return; } $identifier = current(array_values($this->om->getClassMetadata($this->entityName)->getIdentifier())); $id = $idObject[$identifier]; $object = $this->om->getRepository($this->entityName)->findOneBy([$identifier => $id]); if (null === $object) { throw new TransformationFailedException(sprintf('An object with identifier key "%s" and value "%s" does not exist!', $identifier, $id)); } return $object; }
/** * Hydrate $object with the provided $data. * * @param array $data * @param object $object * @throws \Exception * @return object */ public function hydrate(array $data, $object) { $this->metadata = $this->objectManager->getClassMetadata(get_class($object)); foreach ($data as $field => &$value) { if ($this->metadata->hasAssociation($field)) { $target = $this->metadata->getAssociationTargetClass($field); if ($this->metadata->isSingleValuedAssociation($field)) { $value = $this->toOne($value, $target); } elseif ($this->metadata->isCollectionValuedAssociation($field)) { $value = $this->toMany($value, $target); } } } return $this->hydrator->hydrate($data, $object); }
/** * (non-PHPdoc) * @see \Symfony\Component\Form\DataTransformerInterface::transform() */ public function transform($entity) { if (null === $entity || '' === $entity) { return null; } if (!is_object($entity)) { throw new UnexpectedTypeException($entity, 'object'); } if ($entity instanceof Proxy && !$entity->__isInitialized()) { $entity->__load(); } $meta = $this->om->getClassMetadata(get_class($entity)); $id = $meta->getSingleIdReflectionProperty()->getValue($entity); return $id; }
/** * Returns objects extracted from simple search * * @param User $user * @param string $entityClass * @param string $searchString * @param int $offset * @param int $maxResults * * @return array */ protected function getObjects(User $user, $entityClass, $searchString, $offset, $maxResults) { $objects = []; if (!$this->configManager->hasConfig($entityClass)) { return $objects; } $classNames = $this->shareScopeProvider->getClassNamesBySharingScopeConfig($entityClass); if (!$classNames) { return $objects; } $tables = []; foreach ($classNames as $className) { $metadata = $this->em->getClassMetadata($className); $tables[] = $metadata->getTableName(); } $searchResults = $this->indexer->simpleSearch($searchString, $offset, $maxResults, $tables); list($userIds, $buIds, $orgIds) = $this->getIdsByClass($searchResults, $user); if ($orgIds) { $organizations = $this->em->getRepository('OroOrganizationBundle:Organization')->getEnabledOrganizations($orgIds); $objects = array_merge($objects, $organizations); } if ($buIds) { $businessUnits = $this->em->getRepository('OroOrganizationBundle:BusinessUnit')->getBusinessUnits($buIds); $objects = array_merge($objects, $businessUnits); } if ($userIds) { $users = $this->em->getRepository('OroUserBundle:User')->findUsersByIds($userIds); $objects = array_merge($objects, $users); } return $objects; }
public function load(ObjectManager $manager) { $data = (include __DIR__ . '/../fixtures/user/users.php'); $encoder = $this->container->get('security.password_encoder'); $userManager = $this->container->get('medievistes.user_manager'); $connection = $manager->getConnection(); if ($connection->getDatabasePlatform()->getName() === 'mysql') { $connection->exec("ALTER TABLE {$manager->getClassMetadata(User::class)->getTableName()} AUTO_INCREMENT = 1;"); } foreach ($data as $userData) { $class = $userManager->getUserClass($userData['type']); $user = (new $class())->setId((int) $userData['id'])->setUsername($userData['username'])->setEmail($userData['email'])->setPlainPassword($userData['plain_password'])->setSalt(md5(uniqid(null, true)))->enable((bool) $userData['is_active'])->setCreatedAt(new \DateTime($userData['created_at']))->setUpdatedAt(new \DateTime($userData['updated_at'])); if (!empty($userData['activation_link_id'])) { $user->setActivationLink($this->getReference("activation-link-{$userData['activation_link_id']}")); } foreach ($userData['roles'] as $role) { $user->addRole($role); } foreach ($userData['troops'] as $troop) { $association = (new Association())->setUser($user)->setTroop($this->getReference("troop-{$troop['troop_id']}"))->setRole($this->getReference("troop-role-{$troop['role_id']}")); $user->addTroopAssociation($association); $manager->persist($association); } $password = $encoder->encodePassword($user, $userData['plain_password']); $user->setPassword($password); $manager->persist($user); $manager->flush(); $this->addReference("user-{$user->getId()}", $user); } $manager->clear($class); $manager->clear(Association::class); }
/** * * @param ObjectManager|EntityManager $manager * @param * $class * @return bool */ public static function truncate(ObjectManager $manager, $class) { /** * @var $connection \Doctrine\DBAL\Connection */ $connection = $manager->getConnection(); /** * @var $cmd ClassMetadata */ $cmd = $manager->getClassMetadata($class); $connection->beginTransaction(); try { if ($connection->getDatabasePlatform()->getName() !== 'sqlite') { $connection->query('SET FOREIGN_KEY_CHECKS=0'); $connection->executeUpdate($connection->getDatabasePlatform()->getTruncateTableSql($cmd->getTableName())); $connection->query('SET FOREIGN_KEY_CHECKS=1'); } else { $connection->executeUpdate($connection->getDatabasePlatform()->getTruncateTableSql($cmd->getTableName())); } $connection->commit(); return true; } catch (\Exception $e) { $connection->rollback(); return false; } }
/** * Builds the association value. * * @param ClassMetadata $metadata * @param string $propertyPath * @param string $value * * @return array|object * @throws \Exception */ private function buildAssociationValue(ClassMetadata $metadata, $propertyPath, $value) { $childMetadata = $this->manager->getClassMetadata($metadata->getAssociationTargetClass($propertyPath)); // Single association if ($metadata->isSingleValuedAssociation($propertyPath)) { if (is_string($value) && '#' === substr($value, 0, 1)) { return $this->getReference(substr($value, 1)); } elseif (is_array($value)) { return $this->buildEntity($childMetadata, $value); } throw new \Exception("Unexpected value for single association '{$propertyPath}'."); // Collection association } elseif ($metadata->isCollectionValuedAssociation($propertyPath)) { if (!is_array($value)) { throw new \Exception('Expected array.'); } $builtValue = []; foreach ($value as $childData) { if (is_string($childData) && '#' === substr($childData, 0, 1)) { array_push($builtValue, $this->getReference(substr($childData, 1))); } elseif (is_array($value)) { array_push($builtValue, $this->buildEntity($childMetadata, $childData)); } else { throw new \Exception("Unexpected value for association '{$propertyPath}'."); } } return $builtValue; } throw new \Exception("Unexpected association path '{$propertyPath}'."); }
/** * @param string $className * @return ClassMetadata */ private function getClassMetadata($className) { if (null === $this->objectManager) { return null; } return $this->objectManager->getClassMetadata($className); }
/** * Doctrine Entity annotations including references * * @param $class * @return \Doctrine\ORM\Mapping\ClassMetadata */ public function getDoctrineAnnotations($class) { if ($this->doctrineProxyResolver->isDoctrineProxy($class)) { $class = $this->doctrineProxyResolver->unwrapDoctrineProxyClass($class); } return $this->objectManager->getClassMetadata($class); }
/** * * @return \Doctrine\Common\Persistence\Mapping\ClassMetadata */ public function getClassMetadata() { if ($this->classMetadata) { return $this->classMetadata; } return $this->objectManager->getClassMetadata($this->identityClass); }
public function __construct($class, ObjectManager $om) { $this->objectManager = $om; $this->repository = $om->getRepository($class); $metadata = $om->getClassMetadata($class); $this->class = $metadata->getName(); }
/** * Hydrate $object with the provided $data. * * @param array $data * @param object $object * @throws \Exception * @return object */ public function hydrate(array $data, $object) { $this->metadata = $this->objectManager->getClassMetadata(get_class($object)); $object = $this->tryConvertArrayToObject($data, $object); foreach ($data as $field => &$value) { $value = $this->hydrateValue($field, $value); if ($value === null) { continue; } // @todo DateTime (and other types) conversion should be handled by doctrine itself in future if (in_array($this->metadata->getTypeOfField($field), array('datetime', 'time', 'date'))) { if (is_int($value)) { $dt = new DateTime(); $dt->setTimestamp($value); $value = $dt; } elseif (is_string($value)) { $value = new DateTime($value); } } if ($this->metadata->hasAssociation($field)) { $target = $this->metadata->getAssociationTargetClass($field); if ($this->metadata->isSingleValuedAssociation($field)) { $value = $this->toOne($value, $target); } elseif ($this->metadata->isCollectionValuedAssociation($field)) { $value = $this->toMany($value, $target); // Automatically merge collections using helper utility $propertyRefl = $this->metadata->getReflectionClass()->getProperty($field); $propertyRefl->setAccessible(true); $previousValue = $propertyRefl->getValue($object); $value = CollectionUtils::intersectUnion($previousValue, $value); } } } return $this->hydrator->hydrate($data, $object); }
/** * @param User $user * @param string $searchString * @param int $offset * @param int $maxResults * @return array */ public function autocompleteSearch(User $user, $searchString, $offset = 0, $maxResults = 0) { $classNameMap = []; $entities = $this->entityProvider->getEntities(); foreach ($entities as $description) { $classNameMap[$description['name']] = true; } $tables = []; $configs = $this->configManager->getProvider('activity')->getConfigs(); foreach ($configs as $config) { $className = $config->getId()->getClassName(); if (!isset($classNameMap[$className])) { continue; } $activities = $config->get('activities'); if (!empty($activities) && in_array(Email::ENTITY_CLASS, $activities, true)) { $tables[] = $this->em->getClassMetadata($className)->getTableName(); } } $results = []; $searchResults = $this->simpleSearch($searchString, $offset, $maxResults, $tables); foreach ($searchResults->getElements() as $item) { $this->dispatcher->dispatch(PrepareResultItemEvent::EVENT_NAME, new PrepareResultItemEvent($item)); $className = $item->getEntityName(); if (ClassUtils::getClass($user) === $className && $user->getId() === $item->getRecordId()) { continue; } $text = $item->getRecordTitle(); if ($label = $this->getClassLabel($className)) { $text .= ' (' . $label . ')'; } $results[] = ['text' => $text, 'id' => json_encode(['entityClass' => $className, 'entityId' => $item->getRecordId()])]; } return $results; }
/** * @param DoctrineSqlFilter $sqlFilter * @param QuoteStrategy $quoteStrategy * @param ClassMetadata $targetEntity * @param string $targetTableAlias * @param string $targetEntityPropertyName * @return string * @throws InvalidQueryRewritingConstraintException * @throws \Exception */ protected function getSqlForManyToOneAndOneToOneRelationsWithoutPropertyPath(DoctrineSqlFilter $sqlFilter, QuoteStrategy $quoteStrategy, ClassMetadata $targetEntity, $targetTableAlias, $targetEntityPropertyName) { $associationMapping = $targetEntity->getAssociationMapping($targetEntityPropertyName); $constraints = array(); foreach ($associationMapping['joinColumns'] as $joinColumn) { $quotedColumnName = $quoteStrategy->getJoinColumnName($joinColumn, $targetEntity, $this->entityManager->getConnection()->getDatabasePlatform()); $propertyPointer = $targetTableAlias . '.' . $quotedColumnName; $operandAlias = $this->operandDefinition; if (is_array($this->operandDefinition)) { $operandAlias = key($this->operandDefinition); } $currentReferencedOperandName = $operandAlias . $joinColumn['referencedColumnName']; if (is_object($this->operand)) { $operandMetadataInfo = $this->entityManager->getClassMetadata(TypeHandling::getTypeForValue($this->operand)); $currentReferencedValueOfOperand = $operandMetadataInfo->getFieldValue($this->operand, $operandMetadataInfo->getFieldForColumn($joinColumn['referencedColumnName'])); $this->setParameter($sqlFilter, $currentReferencedOperandName, $currentReferencedValueOfOperand, $associationMapping['type']); } elseif (is_array($this->operandDefinition)) { foreach ($this->operandDefinition as $operandIterator => $singleOperandValue) { if (is_object($singleOperandValue)) { $operandMetadataInfo = $this->entityManager->getClassMetadata(TypeHandling::getTypeForValue($singleOperandValue)); $currentReferencedValueOfOperand = $operandMetadataInfo->getFieldValue($singleOperandValue, $operandMetadataInfo->getFieldForColumn($joinColumn['referencedColumnName'])); $this->setParameter($sqlFilter, $operandIterator, $currentReferencedValueOfOperand, $associationMapping['type']); } elseif ($singleOperandValue === NULL) { $this->setParameter($sqlFilter, $operandIterator, NULL, $associationMapping['type']); } } } $constraints[] = $this->getConstraintStringForSimpleProperty($sqlFilter, $propertyPointer, $currentReferencedOperandName); } return ' (' . implode(' ) AND ( ', $constraints) . ') '; }
/** * Get the validator * * @return ValidatorInterface */ protected function getValidator() { if (null === $this->validator) { $this->validator = new ObjectExistsValidator(array('object_repository' => $this->objectManager->getRepository($this->targetClass), 'fields' => $this->objectManager->getClassMetadata($this->targetClass)->getIdentifierFieldNames())); } return $this->validator; }
/** * @param \Doctrine\Common\Persistence\ObjectManager $objectManager */ protected function stubMetaData($objectManager) { $prophet = new Prophet(); $meta = $prophet->prophesize('Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata'); $meta->getIdentifierFieldNames()->willReturn(['id']); $meta->getIdentifierValues(Argument::any())->willReturn([1]); $objectManager->getClassMetadata('stdClass')->willReturn($meta); }
/** * Constructor. * * @param EncoderFactoryInterface $encoderFactory * @param CanonicalizerInterface $usernameCanonicalizer * @param CanonicalizerInterface $emailCanonicalizer * @param ObjectManager $om * @param string $class */ public function __construct(EncoderFactoryInterface $encoderFactory, CanonicalizerInterface $usernameCanonicalizer, CanonicalizerInterface $emailCanonicalizer, ObjectManager $om, $class) { parent::__construct($encoderFactory, $usernameCanonicalizer, $emailCanonicalizer); $this->objectManager = $om; $this->repository = $om->getRepository($class); $metadata = $om->getClassMetadata($class); $this->class = $metadata->getName(); }
/** * (Partially) hydrates the object and removes the affected (key, value) pairs from the return set. * * @param object $object * @param array $data * @return array */ public function hydrate($object, array $data) { if (!$object instanceof TaxonomyTermAwareInterface) { return $data; } $metadata = $this->objectManager->getClassMetadata(get_class($object)); foreach ($data as $field => $value) { if ($metadata->hasAssociation($field) && is_object($value)) { $target = $metadata->getAssociationTargetClass($field); if ($target == 'Taxonomy\\Entity\\TaxonomyTerm') { $this->taxonomyManager->associateWith($value, $object); unset($data[$field]); } } } return $data; }
/** * Constructor. * * @param ObjectManager $om * @param $class */ public function __construct(ObjectManager $om, $class) { $this->objectManager = $om; $this->repository = $om->getRepository($class); $metadata = $om->getClassMetadata($class); $this->class = $metadata->getName(); $this->clonedSecurityAssignments = array(); }
/** * Constructor * * @param ObjectManager $objectManager The ObjectManager to use * @param string $targetClass The FQCN of the hydrated/extracted object * @param bool $byValue If set to true, hydrator will always use entity's public API */ public function __construct(ObjectManager $objectManager, $targetClass, $byValue = true) { parent::__construct(); $this->objectManager = $objectManager; $this->metadata = $objectManager->getClassMetadata($targetClass); $this->byValue = (bool) $byValue; $this->prepare(); }
public function __construct(ObjectManager $om, $class, SecurityContextInterface $securityContext) { $this->om = $om; $this->securityContext = $securityContext; $this->repository = $om->getRepository($class); $metadata = $om->getClassMetadata($class); $this->class = $metadata->getName(); }
/** * @param ObjectManager $om Doctrine object manager * @param string $class Entity class name * @param string $prefix Prefix of a lock record */ public function __construct(ObjectManager $om, $class, $prefix = 'abc-lock') { $this->objectManager = $om; $this->repository = $om->getRepository($class); $this->prefix = $prefix; $metadata = $om->getClassMetadata($class); $this->class = $metadata->getName(); }
/** * Constructs * * @param EntityManager $em * @param string $class * @param string $property * @param QueryBuilder $qb * @param array|\Closure $choices * @param string $groupBy * @param boolean $ajax */ public function __construct(ObjectManager $em, $class, $property = null, $qb = null, $choices = null, $groupBy = null, $ajax = false) { $this->ajax = $ajax; $this->classMetadata = $em->getClassMetadata($class); if ($property) { $this->propertyPath = new PropertyPath($property); } parent::__construct($em, $class, $property, $qb, $choices, $groupBy); }