Since: 2.0
Author: Roman Borschel (roman@code-factory.org)
 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);
 }
Example #2
0
 /**
  * @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;
 }
 public function __construct(EntityManager $em, $class)
 {
     $this->em = $em;
     $this->repository = $em->getRepository($class);
     $metadata = $em->getClassMetadata($class);
     $this->class = $metadata->name;
 }
Example #4
0
 public function resetDatabase()
 {
     $metadatas = $this->em->getMetadataFactory()->getAllMetadata();
     $tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
     $tool->dropDatabase();
     $tool->createSchema($metadatas);
 }
 /**
  * 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);
         }
     }
 }
 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;
 }
 /**
  * {@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;
 }
 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);
 }
 /**
  * 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;
 }
 /**
  *
  * @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;
 }
    /**
     * 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();
            }
        }
    }
Example #12
0
 /**
  * Rollback current transaction
  * @return none
  */
 public static function rollbackTransaction()
 {
     if (self::$_entityManager != NULL) {
         $conn = self::$_entityManager->getConnection();
         $conn->rollback();
     }
 }
 /**
  * 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();
 }
 public function down(Schema $schema)
 {
     $lookingFor = new Profile\LookingFor();
     $lookingFor->setName('Intimate');
     $this->em->persist($lookingFor);
     $this->em->flush();
 }
Example #15
0
 /**
  * Get filtered count
  *
  * @param array $params
  * @param array $cols
  * @return int
  */
 public function getFilteredCount(array $params, array $cols)
 {
     if (empty($params['sSearch'])) {
         return $this->getCount();
     }
     return $this->em->createQueryBuilder()->select('COUNT(e)')->from($this->entityName, 'e')->where($this->buildWhere($cols, $params['sSearch']))->getQuery()->getSingleScalarResult();
 }
 /**
  * @param FilterControllerEvent $event
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     $request = $event->getRequest();
     // Check if the event has a nodeTranslation, if not this method can be skipped
     if (!$request->attributes->has('_nodeTranslation')) {
         return;
     }
     $nodeTranslation = $request->attributes->get('_nodeTranslation');
     if (!$nodeTranslation instanceof NodeTranslation) {
         $nodeTranslation = $this->em->getRepository('KunstmaanNodeBundle:NodeTranslation')->find($nodeTranslation);
         $request->attributes->set('_nodeTranslation', $nodeTranslation);
     }
     $entity = $nodeTranslation->getRef($this->em);
     // If the entity is an instance of the SlugActionInterface, change the controller
     if ($entity instanceof SlugActionInterface) {
         $request->attributes->set('_entity', $entity);
         // Do security check by firing an event that gets handled by the SlugSecurityListener
         $securityEvent = new SlugSecurityEvent();
         $securityEvent->setNode($nodeTranslation->getNode())->setEntity($entity)->setRequest($request)->setNodeTranslation($nodeTranslation);
         $this->eventDispatcher->dispatch(Events::SLUG_SECURITY, $securityEvent);
         // Set the right controller
         $request->attributes->set('_controller', $entity->getControllerAction());
         $event->setController($this->resolver->getController($request));
     }
 }
 public function testProductShouldBeSuspendedAndFlushedWhenSuspendTheProduct()
 {
     $product = new Product('test');
     $this->entityManager->expects(self::once())->method('persist')->with($product);
     $this->entityManager->expects(self::once())->method('flush');
     $this->productService->suspend($product);
 }
 /**
  * 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;
 }
Example #19
0
    /**
     * Loads a locale.
     *
     * @param mixed $resource A resource
     * @param string $locale A locale
     * @param string $domain The domain
     *
     * @return MessageCatalogue A MessageCatalogue instance
     *
     * @throws NotFoundResourceException when the resource cannot be found
     * @throws InvalidResourceException  when the resource cannot be loaded
     */
    public function load($resource, $locale, $domain = 'messages')
    {
        if ($this->loadAll !== true) {
            return new MessageCatalogue($locale);
        }
        $dql = <<<'DQL'
                SELECT
                  t
                FROM
                  MjrLibraryEntitiesBundle:System\Translation t
              WHERE
                  t.Locale = :locale
              ORDER BY t.Id ASC
DQL;
        $query = $this->entityManager->createQuery($dql);
        $query->setParameter(':locale', $locale);
        /** @var Translation[] $results */
        $results = $query->getResult();
        $catalogue = new MessageCatalogue($locale);
        if (count($results) > 0) {
            foreach ($results as $result) {
                $catalogue->set($result->getIdentity(), $result->getTranslation(), $domain);
            }
        }
        return $catalogue;
    }
 /**
  * {@inheritDoc}
  */
 protected function tearDown()
 {
     parent::tearDown();
     if (!is_null($this->em)) {
         $this->em->close();
     }
 }
 /**
  * Sets up a PostMetaManager instance.
  */
 protected function setUp()
 {
     $this->entityManager = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $this->repository = $this->getMockBuilder('Ekino\\WordpressBundle\\Repository\\PostMetaRepository')->disableOriginalConstructor()->getMock();
     $this->entityManager->expects($this->any())->method('getRepository')->will($this->returnValue($this->repository));
     $this->manager = new PostMetaManager($this->entityManager, 'Ekino\\WordpressBundle\\Entity\\PostMeta');
 }
 public function clearCustomerShoppingCarts()
 {
     $customer = $this->getCustomer();
     $customer->setSessionId(new ArrayCollection());
     $this->entityManager->persist($customer);
     $this->entityManager->flush();
 }
 /**
  * @param EmailCampaign $emailCampaign
  * @param Campaign $campaign
  * @param bool $expected
  * @dataProvider staticCampaignProvider
  */
 public function testIsApplicableOnEmailCampaign($emailCampaign, $campaign, $expected)
 {
     $this->entityRepository->expects($this->any())->method('findOneBy')->will($this->returnValue($campaign));
     $this->managerRegistry->expects($this->any())->method('getManager')->will($this->returnValue($this->entityManager));
     $this->entityManager->expects($this->any())->method('getRepository')->will($this->returnValue($this->entityRepository));
     $this->assertEquals($expected, $this->placeholderFilter->isApplicableOnEmailCampaign($emailCampaign));
 }
 public function it_removes_objects(EntityManager $entityManager)
 {
     $object = new \stdClass();
     $entityManager->remove($object)->shouldBeCalled();
     $entityManager->flush()->shouldBeCalled();
     $this->remove($object);
 }
 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 = DoctrineOrmTestCase::createTestEntityManager();
     parent::setUp();
     $schemaTool = new SchemaTool($this->em);
     $classes = array($this->em->getClassMetadata(self::ENTITY_CLASS));
     try {
         $schemaTool->dropSchema($classes);
     } catch (\Exception $e) {
     }
     try {
         $schemaTool->createSchema($classes);
     } catch (\Exception $e) {
     }
     $ids = range(1, 300);
     foreach ($ids as $id) {
         $name = 65 + chr($id % 57);
         $this->em->persist(new SingleIdentEntity($id, $name));
     }
     $this->em->flush();
 }
 /**
  * {@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;
 }
 /**
  * @param RebalancerAction $rebalancerAction
  * @return array
  */
 public function prepareSummary(RebalancerAction $rebalancerAction)
 {
     /** @var SecurityTransactionRepository $securityTransactionRepo */
     $securityTransactionRepo = $this->em->getRepository('WealthbotAdminBundle:SecurityTransaction');
     $rebalancerQueue = $this->repository->findByRebalancerAction($rebalancerAction, false);
     $client = $rebalancerAction->getClientPortfolioValue()->getClientPortfolio()->getClient();
     $result = array('rebalance_total' => 0, 'short_term_gains' => 0, 'long_term_gains' => 0, 'short_term_losses' => 0, 'long_term_losses' => 0, 'transactions_costs' => 0, 'tlh_savings' => 0);
     /** @var RebalancerQueue $item */
     foreach ($rebalancerQueue as $item) {
         $result['rebalance_total'] += $item->getAmount();
         if ($item->getLot()) {
             if ($item->getLot()->isShortTerm()) {
                 $prefix = 'short';
             } else {
                 $prefix = 'long';
             }
             if ($item->getLot()->getShortTermGain() > 0) {
                 $suffix = 'gains';
             } else {
                 $suffix = 'losses';
             }
             $result[$prefix . '_term_' . $suffix] += abs($item->getLot()->getRealizedGain());
         }
         /** @var SecurityTransaction $securityTransaction */
         $securityTransaction = $securityTransactionRepo->findOneByRebalancerQueue($item);
         if ($securityTransaction) {
             $result['transactions_costs'] += $securityTransaction->getTransactionFee();
         }
     }
     //        $result['tlh_savings'] = ($result['short_term_losses'] * $client->getProfile()->getEstimatedIncomeTax()) + ($result['long_term_losses'] * 0.15 - $result['transactions_costs']) / beginning balance
     return $result;
 }
 /**
  * Guess the position of the widget relatively to the positionReference.
  *
  * @param Widget $widget            The widget to position
  * @param int    $positionReference Id of the parent widget
  *
  * @return WidgetMap The position of the widget
  */
 public function generateWidgetPosition(EntityManager $entityManager, WidgetMap $widgetMapEntry, $widget, $widgetMap, $positionReference)
 {
     $position = 1;
     $slotId = $widget->getSlot();
     if (empty($widgetMap[$slotId])) {
         $widgetMapEntry->setPosition($position);
         return $widgetMapEntry;
     }
     $slot = $widgetMap[$slotId];
     $referenceWidget = $entityManager->getRepository('Victoire\\Bundle\\WidgetBundle\\Entity\\Widget')->findOneById($positionReference);
     //If we added a widget just after a parent widget
     //The position of the new widget is the one just after the parent widget
     if ($referenceWidget && $widget->getView() !== $referenceWidget->getView()) {
         $position = 1;
         $widgetMapEntry->setPosition($position);
         $widgetMapEntry->setPositionReference($positionReference);
     } else {
         foreach ($slot as $key => $_widgetMap) {
             if ($_widgetMap->getWidgetId() === (int) $positionReference) {
                 $widgetMapEntry->setPosition($_widgetMap->getPosition() + 1);
                 break;
             } elseif (0 === (int) $positionReference) {
                 $widgetMapEntry->setPosition(1);
             }
         }
     }
     return $widgetMapEntry;
 }
Example #29
0
 public function testSchedule()
 {
     $testIntegrationType = 'testIntegrationType';
     $testConnectorType = 'testConnectorType';
     $testId = 22;
     $integration = new Integration();
     $integration->setType($testIntegrationType);
     $integration->setEnabled(true);
     $ref = new \ReflectionProperty(get_class($integration), 'id');
     $ref->setAccessible(true);
     $ref->setValue($integration, $testId);
     $this->typesRegistry->addChannelType($testIntegrationType, new TestIntegrationType());
     $this->typesRegistry->addConnectorType($testConnectorType, $testIntegrationType, new TestTwoWayConnector());
     $that = $this;
     $uow = $this->getMockBuilder('Doctrine\\ORM\\UnitOfWork')->disableOriginalConstructor()->getMock();
     $this->em->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($uow));
     $metadataFactory = $this->getMockBuilder('Doctrine\\ORM\\Mapping\\ClassMetadataFactory')->disableOriginalConstructor()->getMock();
     $metadataFactory->expects($this->once())->method('getMetadataFor')->will($this->returnValue(new ClassMetadata('testEntity')));
     $this->em->expects($this->once())->method('getMetadataFactory')->will($this->returnValue($metadataFactory));
     $uow->expects($this->once())->method('persist')->with($this->isInstanceOf('JMS\\JobQueueBundle\\Entity\\Job'))->will($this->returnCallback(function (Job $job) use($that, $testId, $testConnectorType) {
         $expectedArgs = ['--integration=' . $testId, sprintf('--connector=testConnectorType', $testConnectorType), '--params=a:0:{}'];
         $that->assertEquals($expectedArgs, $job->getArgs());
     }));
     $uow->expects($this->once())->method('computeChangeSet');
     $this->scheduler->schedule($integration, $testConnectorType, [], false);
 }
 /**
  * Flush on kernel terminate.
  */
 public function onKernelTerminate()
 {
     if ($this->em->isOpen()) {
         $this->em->flush();
         // That was not so hard... And you need a bundle to do that! Poor guy...
     }
 }