本文整理匯總了PHP中Doctrine\ORM\EntityManager::getClassMetadata方法的典型用法代碼示例。如果您正苦於以下問題:PHP EntityManager::getClassMetadata方法的具體用法?PHP EntityManager::getClassMetadata怎麽用?PHP EntityManager::getClassMetadata使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Doctrine\ORM\EntityManager
的用法示例。
在下文中一共展示了EntityManager::getClassMetadata方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。
示例1: setUp
protected function setUp()
{
if (!class_exists('Symfony\\Component\\Form\\Form')) {
$this->markTestSkipped('The "Form" component is not available');
}
if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
$this->markTestSkipped('Doctrine DBAL is not available.');
}
if (!class_exists('Doctrine\\Common\\Version')) {
$this->markTestSkipped('Doctrine Common is not available.');
}
if (!class_exists('Doctrine\\ORM\\EntityManager')) {
$this->markTestSkipped('Doctrine ORM is not available.');
}
$this->em = DoctrineTestHelper::createTestEntityManager();
$schemaTool = new SchemaTool($this->em);
$classes = array($this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS), $this->em->getClassMetadata(self::SINGLE_STRING_ID_CLASS), $this->em->getClassMetadata(self::COMPOSITE_ID_CLASS), $this->em->getClassMetadata(self::GROUPABLE_CLASS));
try {
$schemaTool->dropSchema($classes);
} catch (\Exception $e) {
}
try {
$schemaTool->createSchema($classes);
} catch (\Exception $e) {
}
parent::setUp();
}
示例2: fetchQuery
/**
*
* {@inheritDoc}
*/
public function fetchQuery($context, array $args)
{
$this->checkContext($context);
$metadataActivity = $this->em->getClassMetadata('ChillActivityBundle:Activity');
$metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person');
return array('id' => $metadataActivity->getTableName() . '.' . $metadataActivity->getColumnName('id'), 'type' => 'activity', 'date' => $metadataActivity->getTableName() . '.' . $metadataActivity->getColumnName('date'), 'FROM' => $this->getFromClause($metadataActivity, $metadataPerson), 'WHERE' => $this->getWhereClause($metadataActivity, $metadataPerson, $args['person']));
}
示例3: search
/**
* {@inheritdoc}
*/
public function search($entityClass, array $conditionGroups, $resultSize = null, $pageSize = null)
{
$queryBuilder = $this->entityManager->getRepository($entityClass)->createQueryBuilder('t');
$metadata = $this->entityManager->getClassMetadata($entityClass);
$tableIndex = 0;
$parameters = [];
foreach ($conditionGroups as $conditions) {
$condition = $queryBuilder->expr()->orX();
foreach ($conditions as $field => $term) {
if ($metadata->hasField($field)) {
$mapping = $metadata->getFieldMapping($field);
if ($mapping !== 'array') {
$param = $field . '__value';
$condition->add('t.' . $field . ' LIKE :' . $param);
$parameters[$param] = '%' . $term . '%';
}
} else {
if ($metadata->hasAssociation($field)) {
$association = $metadata->getAssociationMapping($field);
$param = $field . '__value';
$table = 't' . $tableIndex;
++$tableIndex;
$queryBuilder->join('t.' . $field, $table);
$condition->add($table . '.id IN (:' . $param . ')');
$parameters[$param] = $term;
}
}
}
$queryBuilder->andWhere($condition);
}
$queryBuilder->setParameters($parameters);
$query = $queryBuilder->getQuery()->setMaxResults($resultSize)->setFirstResult($pageSize * $resultSize);
return $query->getResult();
}
示例4: getExtensionMetadata
/**
* Reads extension metadata
*
* @param ClassMetadataInfo $meta
* @return array - the metatada configuration
*/
public function getExtensionMetadata(ClassMetadataInfo $meta)
{
if ($meta->isMappedSuperclass) {
return;
// ignore mappedSuperclasses for now
}
$config = array();
// collect metadata from inherited classes
foreach (array_reverse(class_parents($meta->name)) as $parentClass) {
// read only inherited mapped classes
if ($this->_em->getMetadataFactory()->hasMetadataFor($parentClass)) {
$this->_driver->readExtendedMetadata($this->_em->getClassMetadata($parentClass), $config);
}
}
$this->_driver->readExtendedMetadata($meta, $config);
$this->_driver->validateFullMetadata($meta, $config);
if ($config) {
// cache the metadata
$cacheId = self::getCacheId($meta->name, $this->_extensionNamespace);
if ($cacheDriver = $this->_em->getMetadataFactory()->getCacheDriver()) {
$cacheDriver->save($cacheId, $config, null);
}
}
return $config;
}
示例5: getMetaData
/**
* get Metadata from entity
*
* @param string|Object $entity
*
* @return Doctrine\ORM\Mapping\ClassMetaData
*/
public function getMetaData($entity)
{
if (is_object($entity)) {
$entity = get_class($entity);
}
return $this->em->getClassMetadata($entity);
}
示例6: buildInsertSql
/**
* Build an sql insert into query by the paramters provided
* @param ORM\Entity $entities Result array with all entities to create an insert for
* @param string $entityClassName Class of the specified entity (same as entities)
* @param array $ignoreFields fields not to use in the insert query
* @return string an insert sql query, of no result nul
*/
public function buildInsertSql($entities, $entityClassName, $ignoreFields = array())
{
if (count($entities) <= 0) {
return null;
}
$fieldNames = $this->entityManager->getClassMetadata($entityClassName)->getFieldNames();
$tableName = $this->entityManager->getClassMetadata($entityClassName)->getTableName();
$tableName = $this->entityManager->getConnection()->quoteIdentifier($tableName);
$fieldNames = array_diff($fieldNames, $ignoreFields);
$values = array();
foreach ($entities as $entity) {
$insertValues = array();
foreach ($fieldNames as $fieldName) {
$value = $entity->{'get' . $fieldName}();
if ($value instanceof \DateTime) {
$value = $value->format('Y-m-d H:i:s');
}
$insertValues[] = $this->entityManager->getConnection()->quote($value);
}
$values[] = '(' . implode(',', $insertValues) . ')';
}
foreach ($fieldNames as $key => $fieldName) {
$columnName = $this->entityManager->getClassMetadata($entityClassName)->getColumnName($fieldName);
$fieldNames[$key] = $this->entityManager->getConnection()->quoteIdentifier($columnName);
}
$sql = sprintf('INSERT INTO %s (%s) VALUES %s', $tableName, implode(",", $fieldNames), implode(', ', $values));
return $sql;
}
示例7: __construct
/**
* Constructor.
*
* @param EntityManager $em
* @param string $class
* @param string $metaClass
*/
public function __construct(EntityManager $em, $class, $metaClass)
{
$this->em = $em;
$this->repository = $em->getRepository($class);
$this->class = $em->getClassMetadata($class)->name;
$this->metaClass = $em->getClassMetadata($metaClass)->name;
}
示例8: getObjectIdFromEntity
/**
* Use reflection to extract the entity's id
*
* @param object $entity
* @return mixed The object id
*/
protected function getObjectIdFromEntity(&$entity)
{
$meta = $this->em->getClassMetadata(get_class($entity));
$identifierField = $meta->getSingleIdentifierFieldName();
$objectId = $meta->getReflectionProperty($identifierField)->getValue($entity);
return $objectId;
}
示例9: serializeEntity
/**
* @param $entity
* @param array $parentEntities
* @param int $currentDepth
* @return array
*/
protected function serializeEntity($entity, $parentEntities = array(), $currentDepth = 0)
{
$className = get_class($entity);
$metadata = $this->em->getClassMetadata($className);
$data = array();
$currentDepth++;
if ($this->maxRecursionDepth === 0 || $this->maxRecursionDepth >= $currentDepth) {
foreach ($metadata->fieldMappings as $field => $mapping) {
$value = $metadata->reflFields[$field]->getValue($entity);
if ($value instanceof \DateTime) {
// We cast DateTime to array to keep consistency with array result
$data[$field] = (array) $value;
} elseif (is_object($value)) {
$data[$field] = (string) $value;
} else {
$data[$field] = $value;
}
}
foreach ($metadata->associationMappings as $field => $mapping) {
if ($mapping['targetEntity'] != $className) {
$parentEntities[] = get_class($entity);
}
if (!in_array($mapping['targetEntity'], $parentEntities)) {
$key = $field;
if ($mapping['isCascadeDetach'] || $mapping['type'] == ClassMetadata::MANY_TO_MANY) {
if ('Doctrine\\ORM\\PersistentCollection' == get_class($entity->{$field})) {
if (!in_array($mapping['targetEntity'], $parentEntities) && ($this->maxRecursionDepth === 0 || $this->maxRecursionDepth > $currentDepth)) {
$data[$key] = array();
$parentEntities[] = $mapping['targetEntity'];
foreach ($entity->{$field} as $child) {
$data[$key][] = $this->serializeEntity($child, $parentEntities, $currentDepth);
}
}
} else {
$data[$key] = $metadata->reflFields[$field]->getValue($entity);
if (null !== $data[$key]) {
$data[$key] = $this->serializeEntity($data[$key], $parentEntities, $currentDepth);
}
}
} elseif ($mapping['isOwningSide'] && in_array($mapping['type'], array(ClassMetadata::TO_ONE, ClassMetadata::MANY_TO_ONE))) {
if (null !== $metadata->reflFields[$field]->getValue($entity)) {
if ($this->entityRecursionDepth < $this->maxEntityRecursionDepth || $this->maxEntityRecursionDepth === 0) {
$this->entityRecursionDepth++;
$parentEntities[] = $mapping['targetEntity'];
$data[$key] = $this->serializeEntity($metadata->reflFields[$field]->getValue($entity), $parentEntities, $currentDepth);
$this->entityRecursionDepth--;
} else {
$data[$key] = $this->getEntityManager()->getUnitOfWork()->getEntityIdentifier($metadata->reflFields[$field]->getValue($entity));
}
} else {
// In some case the relationship may not exist, but we want
// to know about it
$data[$key] = null;
}
}
}
}
}
return $data;
}
示例10: setUp
protected function setUp()
{
parent::setUp();
if (!class_exists('Symfony\\Component\\Form\\Form')) {
$this->markTestSkipped('The "Form" component is not available');
}
if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) {
$this->markTestSkipped('Doctrine DBAL is not available.');
}
if (!class_exists('Doctrine\\Common\\Version')) {
$this->markTestSkipped('Doctrine Common is not available.');
}
if (!class_exists('Doctrine\\ORM\\EntityManager')) {
$this->markTestSkipped('Doctrine ORM is not available.');
}
$this->em = DoctrineTestHelper::createTestEntityManager();
$this->emRegistry = $this->createRegistryMock('default', $this->em);
$this->items = array();
$schemaTool = new SchemaTool($this->em);
$classes = array($this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS));
try {
$schemaTool->dropSchema($classes);
} catch (\Exception $e) {
}
try {
$schemaTool->createSchema($classes);
} catch (\Exception $e) {
}
$this->createEntities();
$this->factory = Forms::createFormFactoryBuilder()->addExtensions($this->getExtensions())->addTypeExtension(new ChoiceSelect2TypeExtension($this->dispatcher, $this->requestStack, $this->router, $this->getExtensionTypeName(), 10))->addType(new EntityType($this->emRegistry))->addTypeExtension(new EntitySelect2TypeExtension())->getFormFactory();
$this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory);
}
示例11: hydrateEntity
public function hydrateEntity($entity, array $values)
{
$classMetadata = $this->em->getClassMetadata(get_class($entity));
foreach ($values as $fieldName => $value) {
if ($classMetadata->hasField($fieldName)) {
$fieldMappping = $classMetadata->getFieldMapping($fieldName);
if (null === $fieldMappping) {
throw new HydrationException($fieldName);
}
$type = Type::getType($classMetadata->fieldMappings[$fieldName]['type']);
$value = $type->convertToPHPValue($value, $this->em->getConnection()->getDatabasePlatform());
$classMetadata->setFieldValue($entity, $fieldName, $value);
} elseif (isset($classMetadata->associationMappings[$fieldName])) {
$fieldMapping = $classMetadata->associationMappings[$fieldName];
if (ClassMetadataInfo::MANY_TO_MANY === $fieldMapping['type']) {
// expecting an array of ids in $value
if (1 === count($fieldMapping['relationToTargetKeyColumns'])) {
$columnName = array_pop($fieldMapping['relationToTargetKeyColumns']);
$otherSideMapping = $this->em->getClassMetadata($fieldMapping['targetEntity']);
$value = $this->em->getRepository($fieldMapping['targetEntity'])->findBy(array($otherSideMapping->fieldNames[$columnName] => $value));
}
$classMetadata->setFieldValue($entity, $fieldName, $value);
} elseif (ClassMetadataInfo::MANY_TO_ONE === $fieldMapping['type']) {
// expecting an array of ids in $value
$value = $this->em->getRepository($fieldMapping['targetEntity'])->find($value);
$classMetadata->setFieldValue($entity, $fieldName, $value);
}
} else {
throw new HydrationException($fieldName);
}
}
}
示例12: getProductCountByTree
/**
* {@inheritdoc}
*/
public function getProductCountByTree(ProductInterface $product)
{
$categories = $product->getCategories();
$categoryIds = array();
foreach ($categories as $category) {
$categoryIds[] = $category->getId();
}
$categoryRepository = $this->entityManager->getRepository($this->categoryClass);
$categoryTable = $this->entityManager->getClassMetadata($this->categoryClass)->getTableName();
$categoryIds = implode(',', $categoryIds);
if (!empty($categoryIds)) {
$sql = "SELECT" . " tree.id AS tree_id," . " COUNT(category.id) AS product_count" . " FROM {$categoryTable} tree" . " LEFT JOIN {$categoryTable} category" . " ON category.root = tree.id" . " AND category.id IN ({$categoryIds})" . " WHERE tree.parent_id IS NULL" . " GROUP BY tree.id";
} else {
$sql = "SELECT" . " tree.id AS tree_id," . " '0' AS product_count" . " FROM {$categoryTable} tree" . " LEFT JOIN {$categoryTable} category" . " ON category.root = tree.id" . " WHERE tree.parent_id IS NULL" . " GROUP BY tree.id";
}
$stmt = $this->entityManager->getConnection()->prepare($sql);
$stmt->execute();
$productCounts = $stmt->fetchAll();
$trees = array();
foreach ($productCounts as $productCount) {
$tree = array();
$tree['productCount'] = $productCount['product_count'];
$tree['tree'] = $categoryRepository->find($productCount['tree_id']);
$trees[] = $tree;
}
return $trees;
}
示例13: getMetaData
/**
* @return array
*/
protected function getMetaData()
{
if (null === $this->metadata) {
$this->metadata = $this->em->getClassMetadata($this->class)->getMetaData();
}
return $this->metadata;
}
示例14: uninstall
/**
* @param \Venne\Module\IModule $module
*/
public function uninstall(IModule $module)
{
if (!$this->context->hasService('doctrine') || !$this->context->doctrine->createCheckConnection()) {
throw new \Exception('Database connection not found!');
}
$classes = $this->getClasses($module);
$metadata = array();
foreach ($classes as $class) {
$metadata[] = $this->entityManager->getClassMetadata($class);
}
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager);
$this->entityManager->getConnection()->beginTransaction();
try {
foreach ($classes as $class) {
$repository = $this->entityManager->getRepository($class);
foreach ($repository->findAll() as $entity) {
$repository->delete($entity);
}
}
$tool->dropSchema($metadata);
$this->entityManager->getConnection()->commit();
} catch (Exception $e) {
$this->entityManager->getConnection()->rollback();
$this->entityManager->close();
throw $e;
}
$this->cleanCache();
}
示例15: onFlush
/**
* @param OnFlushEventArgs $args
*/
public function onFlush(OnFlushEventArgs $args)
{
$this->initializeFromEventArgs($args);
$entities = array_merge($this->uow->getScheduledEntityInsertions(), $this->uow->getScheduledEntityDeletions(), $this->uow->getScheduledEntityUpdates());
/** @var Opportunity[] $entities */
$entities = array_filter($entities, function ($entity) {
return 'OroCRM\\Bundle\\SalesBundle\\Entity\\Opportunity' === ClassUtils::getClass($entity);
});
foreach ($entities as $entity) {
if (!$entity->getId() && $this->isValuable($entity)) {
// handle creation, just add to prev lifetime value and recalculate change set
$b2bCustomer = $entity->getCustomer();
$b2bCustomer->setLifetime($b2bCustomer->getLifetime() + $entity->getCloseRevenue());
$this->scheduleUpdate($b2bCustomer);
$this->uow->computeChangeSet($this->em->getClassMetadata(ClassUtils::getClass($b2bCustomer)), $b2bCustomer);
} elseif ($this->uow->isScheduledForDelete($entity) && $this->isValuable($entity)) {
$this->scheduleUpdate($entity->getCustomer());
} elseif ($this->uow->isScheduledForUpdate($entity)) {
// handle update
$changeSet = $this->uow->getEntityChangeSet($entity);
if ($this->isChangeSetValuable($changeSet)) {
if (!empty($changeSet['customer']) && $changeSet['customer'][0] instanceof B2bCustomer && B2bCustomerRepository::VALUABLE_STATUS === $this->getOldStatus($entity, $changeSet)) {
// handle change of b2b customer
$this->scheduleUpdate($changeSet['customer'][0]);
}
if ($this->isValuable($entity, isset($changeSet['closeRevenue'])) || B2bCustomerRepository::VALUABLE_STATUS === $this->getOldStatus($entity, $changeSet) && $entity->getCustomer()) {
$this->scheduleUpdate($entity->getCustomer());
}
}
}
}
}