本文整理汇总了PHP中Doctrine\ORM\EntityManager类的典型用法代码示例。如果您正苦于以下问题:PHP EntityManager类的具体用法?PHP EntityManager怎么用?PHP EntityManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EntityManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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;
}
示例2: __construct
public function __construct(EntityManager $em, $class)
{
$this->em = $em;
$this->repository = $em->getRepository($class);
$metadata = $em->getClassMetadata($class);
$this->class = $metadata->name;
}
示例3: generateEntityManagerProxies
/**
* Generate doctrine proxy classes for extended entities for the given entity manager
*
* @param EntityManager $em
*/
protected function generateEntityManagerProxies(EntityManager $em)
{
$isAutoGenerated = $em->getConfiguration()->getAutoGenerateProxyClasses();
if (!$isAutoGenerated) {
$proxyDir = $em->getConfiguration()->getProxyDir();
if (!empty($this->cacheDir) && $this->kernelCacheDir !== $this->cacheDir && strpos($proxyDir, $this->kernelCacheDir) === 0) {
$proxyDir = $this->cacheDir . substr($proxyDir, strlen($this->kernelCacheDir));
}
$metadataFactory = $em->getMetadataFactory();
$proxyFactory = $em->getProxyFactory();
$extendConfigs = $this->extendConfigProvider->getConfigs(null, true);
foreach ($extendConfigs as $extendConfig) {
if (!$extendConfig->is('is_extend')) {
continue;
}
if ($extendConfig->in('state', [ExtendScope::STATE_NEW])) {
continue;
}
$entityClass = $extendConfig->getId()->getClassName();
$proxyFileName = $proxyDir . DIRECTORY_SEPARATOR . '__CG__' . str_replace('\\', '', $entityClass) . '.php';
$metadata = $metadataFactory->getMetadataFor($entityClass);
$proxyFactory->generateProxyClasses([$metadata], $proxyDir);
clearstatcache(true, $proxyFileName);
}
}
}
示例4: getAllCustomIndexes
/**
* get custom indexes from all entities
*
* @param EntityManager $em
*
* @return array - array with custom indexes
**/
protected function getAllCustomIndexes(EntityManager $em)
{
$metadata = $em->getMetadataFactory()->getAllMetadata();
$result = [];
$this->rememberAllAbstractWithIndex($metadata);
// add all custom indexes into $result array
$indexesToResult = function (ClassMetadata $meta, $tableName, $tablePostfix = false) use(&$result) {
if ($indexes = $this->readEntityIndexes($meta)) {
foreach ($indexes as $aIndex) {
$index = new CustomIndex($tableName, $aIndex->columns, $aIndex->name . ($aIndex->name && $tablePostfix ? '_' . $tableName : ''), $aIndex->unique, $aIndex->using, $aIndex->where, $meta->getSchemaName());
$result[$index->getName(true)] = $index;
}
}
};
// create index from non abstract entity annotation
foreach ($metadata as $meta) {
if (!$this->isAbstract($meta)) {
$indexesToResult($meta, $meta->getTableName());
// create index using abstract parent
$parentsMeta = $this->searchParentsWithIndex($meta);
foreach ($parentsMeta as $parentMeta) {
$indexesToResult($parentMeta, $meta->getTableName(), true);
}
}
}
return $result;
}
示例5: __construct
/**
* Initializes a new instance of a class derived from AbstractEntityPersister
* that uses the given EntityManager and persists instances of the class described
* by the given class metadata descriptor.
*/
public function __construct(EntityManager $em, ClassMetadata $class)
{
$this->_em = $em;
$this->_entityName = $class->name;
$this->_conn = $em->getConnection();
$this->_class = $class;
}
示例6: testBuild
public function testBuild()
{
$type = 'history';
$userId = 1;
$user = $this->getMockBuilder('stdClass')->setMethods(['getId'])->getMock();
$user->expects($this->once())->method('getId')->will($this->returnValue($userId));
$token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface');
$token->expects($this->once())->method('getUser')->will($this->returnValue($user));
$this->tokenStorage->expects($this->once())->method('getToken')->will($this->returnValue($token));
$item = $this->getMock('Oro\\Bundle\\NavigationBundle\\Entity\\NavigationItemInterface');
$this->factory->expects($this->once())->method('createItem')->with($type, [])->will($this->returnValue($item));
$repository = $this->getMockBuilder('Oro\\Bundle\\NavigationBundle\\Entity\\Repository\\HistoryItemRepository')->disableOriginalConstructor()->getMock();
$items = [['id' => 1, 'title' => 'test1', 'url' => '/'], ['id' => 2, 'title' => 'test2', 'url' => '/home']];
$repository->expects($this->once())->method('getNavigationItems')->with($userId, $type)->will($this->returnValue($items));
$this->em->expects($this->once())->method('getRepository')->with(get_class($item))->will($this->returnValue($repository));
$menu = $this->getMockBuilder('Knp\\Menu\\MenuItem')->disableOriginalConstructor()->getMock();
$childMock = $this->getMock('Knp\\Menu\\ItemInterface');
$childMock2 = clone $childMock;
$children = [$childMock, $childMock2];
$matcher = $this->getMock('\\Knp\\Menu\\Matcher\\Matcher');
$matcher->expects($this->once())->method('isCurrent')->will($this->returnValue(true));
$this->builder->setMatcher($matcher);
$menu->expects($this->exactly(2))->method('addChild');
$menu->expects($this->once())->method('setExtra')->with('type', $type);
$menu->expects($this->once())->method('getChildren')->will($this->returnValue($children));
$menu->expects($this->once())->method('removeChild');
$n = rand(1, 10);
$configMock = $this->getMockBuilder('Oro\\Bundle\\ConfigBundle\\Config\\UserConfigManager')->disableOriginalConstructor()->getMock();
$configMock->expects($this->once())->method('get')->with($this->equalTo('oro_navigation.maxItems'))->will($this->returnValue($n));
$this->manipulator->expects($this->once())->method('slice')->with($menu, 0, $n);
$this->builder->setOptions($configMock);
$this->builder->build($menu, [], $type);
}
示例7: resetDatabase
public function resetDatabase()
{
$metadatas = $this->em->getMetadataFactory()->getAllMetadata();
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
$tool->dropDatabase();
$tool->createSchema($metadatas);
}
示例8: convertFromLoanApp
public function convertFromLoanApp(LoanApplication $application)
{
$this->em->detach($application);
$vantage = $this->formatVantage($application);
$applicationXml = $this->container->get('templating')->render('SudouxMortgageBundle:LoanApplicationAdmin/formats:vantageFull.xml.twig', array('application' => $vantage), 'text/xml');
return $applicationXml;
}
示例9: transform
/**
* {@inheritdoc}
*
* @throws TransformationFailedException if object is not found.
*/
public function transform($id)
{
if (!$this->isArray) {
if (!$id) {
return null;
}
$column = is_numeric($id) ? 'id' : 'utmtag';
$entity = $this->em->getRepository($this->repository)->findOneBy(array($column => $id));
if ($entity === null) {
throw new TransformationFailedException(sprintf('UtmTag with "%s" does not exist!', $id));
}
return $entity;
}
if (empty($id) || !is_array($id)) {
return array();
}
$column = is_numeric($id[0]) ? 'id' : 'utmtag';
$repo = $this->em->getRepository($this->repository);
$prefix = $repo->getTableAlias();
$entities = $repo->getEntities(array('filter' => array('force' => array(array('column' => $prefix . '.' . $column, 'expr' => 'in', 'value' => $id))), 'ignore_paginator' => true));
if (!count($entities)) {
throw new TransformationFailedException(sprintf('UtmTags for "%s" does not exist!', $id[0]));
}
return $entities;
}
示例10: testProcessGoodScenario
public function testProcessGoodScenario()
{
$testWebsiteId = 1;
$testStoreId = 2;
$testStoresArray = new \ArrayIterator([['website_id' => $testWebsiteId, 'store_id' => $testStoreId]]);
$settingBag = new ParameterBag(['website_id' => $testWebsiteId]);
$testData = [['id' => 1, 'originId' => 11], ['id' => 2, 'originId' => 22], ['id' => 3, 'originId' => 33]];
$testExistedCarts = [(object) ['entity_id' => 22]];
$repo = $this->getMockBuilder('OroCRM\\Bundle\\MagentoBundle\\Entity\\Repository\\CartRepository')->disableOriginalConstructor()->getMock();
$this->em->expects($this->any())->method('getRepository')->with('OroCRMMagentoBundle:Cart')->will($this->returnValue($repo));
$transport = $this->getMockBuilder('Oro\\Bundle\\IntegrationBundle\\Entity\\Transport')->setMethods(['getSettingsBag'])->getMockForAbstractClass();
$transport->expects($this->any())->method('getSettingsBag')->will($this->returnValue($settingBag));
$realTransport = $this->getMock('OroCRM\\Bundle\\MagentoBundle\\Provider\\Transport\\MagentoTransportInterface');
$realTransport->expects($this->once())->method('isSupportedExtensionVersion')->will($this->returnValue(true));
$realTransport->expects($this->once())->method('getStores')->will($this->returnValue($testStoresArray));
$this->helper->expects($this->once())->method('getTransport')->will($this->returnValue($realTransport));
$channel = new Channel();
$channel->setTransport($transport);
$realTransport->expects($this->at(3))->method('call')->with(SoapTransport::ACTION_ORO_CART_LIST, ['filters' => ['complex_filter' => [['key' => 'store_id', 'value' => ['key' => 'in', 'value' => $testStoreId]], ['key' => 'entity_id', 'value' => ['key' => 'in', 'value' => '11,22']]]], 'pager' => ['page' => 1, 'pageSize' => self::BATCH_SIZE]])->will($this->returnValue($testExistedCarts));
$realTransport->expects($this->at(4))->method('call')->with(SoapTransport::ACTION_ORO_CART_LIST, ['filters' => ['complex_filter' => [['key' => 'store_id', 'value' => ['key' => 'in', 'value' => $testStoreId]], ['key' => 'entity_id', 'value' => ['key' => 'in', 'value' => '33']]]], 'pager' => ['page' => 1, 'pageSize' => self::BATCH_SIZE]])->will($this->returnValue([]));
$repo->expects($this->once())->method('getCartsByChannelIdsIterator')->with($channel)->will($this->returnValue($testData));
$repo->expects($this->at(1))->method('markExpired')->with([1]);
$repo->expects($this->at(2))->method('markExpired')->with([3]);
$this->processor->process($channel);
}
示例11: getStatisticForRangeAndType
/**
*
* @param \DateTime $startDate beginning >=
* @param \DateTime $endDate end <=
* @param $type - type of the StatisticEntryFilter
*
* @return StatisticEntry[]
*
* Note: can be replaced with DQL if performance issues are notable
*/
public function getStatisticForRangeAndType(\DateTime $startDate, \DateTime $endDate, $type = null)
{
/** @var TrainingDayRepository $trainingDayRepository */
$trainingDayRepository = $this->manager->getRepository('TrainingScheduleBundle:TrainingDay');
$expr = Criteria::expr();
$criteria = Criteria::create();
$criteria->where($expr->gte('date', $startDate));
$criteria->andWhere($expr->lte('date', $endDate));
$criteria->andWhere($expr->eq('user', $this->userToken->getUser()));
/** @var LazyCriteriaCollection $trainingDays */
$trainingDays = $trainingDayRepository->matching($criteria);
$result = array();
/** @var TrainingDay $trainingDay * */
foreach ($trainingDays as $trainingDay) {
foreach ($trainingDay->getStatistics() as $statistic) {
/** @var StatisticEntry $statistic */
if ($type != null) {
if ($statistic->getName() === $type) {
$result[] = $statistic;
}
} else {
$result[] = $statistic;
}
}
}
return $result;
}
示例12: setLastExportDate
/**
* Update configurable delta export.
*
* @param Channel $channel
* @param JobInstance $jobInstance
* @param string $identifier
*/
public function setLastExportDate(Channel $channel, JobInstance $jobInstance, $identifier)
{
$variantGroup = $this->groupRepository->findOneBy(['code' => $identifier]);
if ($variantGroup) {
$deltaConfigurableTable = $this->tableNameBuilder->getTableName('pim_magento_connector.entity.delta_configurable_export.class');
$exportableProducts = $this->productFilter->apply($channel, $variantGroup->getProducts());
foreach ($exportableProducts as $product) {
$sql = <<<SQL
INSERT INTO {$deltaConfigurableTable} (product_id, job_instance_id, last_export)
VALUES (:product_id, :job_instance_id, :last_export)
ON DUPLICATE KEY UPDATE last_export = :last_export
SQL;
$connection = $this->em->getConnection();
$query = $connection->prepare($sql);
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$lastExport = $now->format('Y-m-d H:i:s');
$productId = $product->getId();
$jobInstanceId = $jobInstance->getId();
$query->bindParam(':last_export', $lastExport, PDO::PARAM_STR);
$query->bindParam(':product_id', $productId, PDO::PARAM_INT);
$query->bindParam(':job_instance_id', $jobInstanceId, PDO::PARAM_INT);
$query->execute();
}
}
}
示例13: rollbackTransaction
/**
* Rollback current transaction
* @return none
*/
public static function rollbackTransaction()
{
if (self::$_entityManager != NULL) {
$conn = self::$_entityManager->getConnection();
$conn->rollback();
}
}
示例14: countEntities
/**
* Counting the entities in the repository (database table).
*
* @param string $repository name of repository.
* @return integer number of entities in the repository.
*/
private function countEntities($repository)
{
$qb = $this->em->createQueryBuilder();
$qb->select('count(e.id)');
$qb->from($repository, 'e');
return $qb->getQuery()->getSingleScalarResult();
}
示例15: down
public function down(Schema $schema)
{
$lookingFor = new Profile\LookingFor();
$lookingFor->setName('Intimate');
$this->em->persist($lookingFor);
$this->em->flush();
}