protected function setUp()
 {
     $this->initClient();
     $this->registry = $this->getContainer()->get('doctrine');
     $this->repository = $this->registry->getRepository('OroB2BCatalogBundle:Category');
     $this->loadFixtures(['OroB2B\\Bundle\\CatalogBundle\\Tests\\Functional\\DataFixtures\\LoadCategoryData']);
 }
예제 #2
0
 /**
  * {@inheritDoc}
  */
 public function process(DatagridInterface $grid, array $config)
 {
     $this->datagrid = $grid;
     if (isset($config['query'])) {
         $queryConfig = array_intersect_key($config, array_flip(['query']));
         $converter = new YamlConverter();
         $this->qb = $converter->parse($queryConfig, $this->doctrine);
     } elseif (isset($config['entity']) && isset($config['repository_method'])) {
         $entity = $config['entity'];
         $method = $config['repository_method'];
         $repository = $this->doctrine->getRepository($entity);
         if (method_exists($repository, $method)) {
             $qb = $repository->{$method}();
             if ($qb instanceof QueryBuilder) {
                 $this->qb = $qb;
             } else {
                 throw new DatasourceException(sprintf('%s::%s() must return an instance of Doctrine\\ORM\\QueryBuilder, %s given', get_class($repository), $method, is_object($qb) ? get_class($qb) : gettype($qb)));
             }
         } else {
             throw new DatasourceException(sprintf('%s has no method %s', get_class($repository), $method));
         }
     } else {
         throw new DatasourceException(get_class($this) . ' expects to be configured with query or repository method');
     }
     if (isset($config['hints'])) {
         $this->queryHints = $config['hints'];
     }
     $grid->setDatasource(clone $this);
 }
예제 #3
0
 /**
  * @param ChartViewBuilder $viewBuilder
  * @param array            $dateRange
  *
  * @return ChartView
  */
 public function getNewCustomerChartView(ChartViewBuilder $viewBuilder, $dateRange)
 {
     /** @var CustomerRepository $customerRepository */
     $customerRepository = $this->registry->getRepository('OroCRMMagentoBundle:Customer');
     /** @var ChannelRepository $channelRepository */
     $channelRepository = $this->registry->getRepository('OroCRMChannelBundle:Channel');
     list($past, $now) = $this->dateHelper->getPeriod($dateRange, 'OroCRMMagentoBundle:Customer', 'createdAt');
     $items = [];
     // get all integration channels
     $channels = $channelRepository->getAvailableChannelNames($this->aclHelper, ChannelType::TYPE);
     $channelIds = array_keys($channels);
     $dates = $this->dateHelper->getDatePeriod($past, $now);
     $data = $customerRepository->getGroupedByChannelArray($this->aclHelper, $this->dateHelper, $past, $now, $channelIds);
     foreach ($data as $row) {
         $key = $this->dateHelper->getKey($past, $now, $row);
         $channelId = (int) $row['channelId'];
         $channelName = $channels[$channelId]['name'];
         if (!isset($items[$channelName])) {
             $items[$channelName] = $dates;
         }
         if (isset($items[$channelName][$key])) {
             $items[$channelName][$key]['cnt'] = (int) $row['cnt'];
         }
     }
     // restore default keys
     foreach ($items as $channelName => $item) {
         $items[$channelName] = array_values($item);
     }
     $chartOptions = array_merge_recursive(['name' => 'multiline_chart'], $this->configProvider->getChartConfig('new_web_customers'));
     $chartType = $this->dateHelper->getFormatStrings($past, $now)['viewType'];
     $chartOptions['data_schema']['label']['type'] = $chartType;
     $chartOptions['data_schema']['label']['label'] = sprintf('oro.dashboard.chart.%s.label', $chartType);
     return $viewBuilder->setOptions($chartOptions)->setArrayData($items)->getView();
 }
예제 #4
0
 /**
  * @param string $entityName
  * @param array $criteria
  * @return object|null
  */
 public function findOneBy($entityName, array $criteria)
 {
     $serializationCriteria = [];
     $where = [];
     foreach ($criteria as $field => $value) {
         if (is_object($value)) {
             $serializationCriteria[$field] = $this->getIdentifier($value);
         } else {
             $serializationCriteria[$field] = $value;
         }
         $where[] = sprintf('e.%s = :%s', $field, $field);
     }
     $storageKey = serialize($serializationCriteria);
     if (empty($this->entities[$entityName]) || empty($this->entities[$entityName][$storageKey])) {
         /** @var EntityRepository $entityRepository */
         $entityRepository = $this->registry->getRepository($entityName);
         $queryBuilder = $entityRepository->createQueryBuilder('e')->andWhere(implode(' AND ', $where))->setParameters($criteria)->setMaxResults(1);
         if ($this->shouldBeAddedOrganizationLimits($entityName)) {
             $ownershipMetadataProvider = $this->ownershipMetadataProviderLink->getService();
             $organizationField = $ownershipMetadataProvider->getMetadata($entityName)->getOrganizationFieldName();
             $queryBuilder->andWhere('e.' . $organizationField . ' = :organization')->setParameter('organization', $this->securityFacadeLink->getService()->getOrganization());
         }
         $this->entities[$entityName][$storageKey] = $queryBuilder->getQuery()->getOneOrNullResult();
     }
     return $this->entities[$entityName][$storageKey];
 }
예제 #5
0
 /**
  * {@inheritDoc}
  */
 public function setDefaultOptions(OptionsResolverInterface $resolver)
 {
     $resolver->setDefaults(array('entity_class' => null, 'config_id' => null));
     $resolver->setNormalizers(array('choices' => function (Options $options, $value) {
         if (!empty($value)) {
             return $value;
         }
         $entityClass = $options['entity_class'];
         if (!$entityClass && $options->has('config_id')) {
             $configId = $options['config_id'];
             if ($configId && $configId instanceof ConfigIdInterface) {
                 $entityClass = $configId->getClassName();
             }
         }
         $choices = array();
         if ($entityClass) {
             /** @var WorkflowDefinition[] $definitions */
             $definitions = $this->registry->getRepository('OroWorkflowBundle:WorkflowDefinition')->findBy(array('relatedEntity' => $entityClass));
             foreach ($definitions as $definition) {
                 $name = $definition->getName();
                 $label = $definition->getLabel();
                 $choices[$name] = $label;
             }
         }
         return $choices;
     }));
 }
예제 #6
0
 /**
  * @return PaymentMethodRepository
  */
 public function getRepository()
 {
     if (null === $this->repository) {
         $this->repository = $this->registry->getRepository('CSBillPaymentBundle:PaymentMethod');
     }
     return $this->repository;
 }
예제 #7
0
 /**
  * {@inheritdoc}
  */
 public function getOrigin(OriginAwareInterface $originAware)
 {
     if (null === $originAware->getOriginId() || null === $originAware->getOriginType()) {
         return null;
     }
     return $this->manager->getRepository($originAware->getOriginType())->findOneBy(array($this->identifier => $originAware->getOriginId()));
 }
 /**
  * @param ConsoleTerminateEvent $event
  */
 public function onConsoleTerminate(ConsoleTerminateEvent $event)
 {
     if ($event->getCommand() instanceof UpdateSchemaDoctrineCommand) {
         $output = $event->getOutput();
         $input = $event->getInput();
         if ($input->getOption('force')) {
             $result = $this->fulltextIndexManager->createIndexes();
             $output->writeln('Schema update and create index completed.');
             if ($result) {
                 $output->writeln('Indexes were created.');
             }
         }
     }
     if ($event->getCommand() instanceof UpdateSchemaCommand) {
         $entities = $this->registry->getRepository('OroSearchBundle:UpdateEntity')->findAll();
         if (count($entities)) {
             $em = $this->registry->getManager();
             foreach ($entities as $entity) {
                 $job = new Job(ReindexCommand::COMMAND_NAME, ['class' => $entity->getEntity()]);
                 $em->persist($job);
                 $em->remove($entity);
             }
             $em->flush($job);
         }
     }
 }
예제 #9
0
 /**
  * {@inheritdoc}
  */
 public function reverseTransform($value)
 {
     if (!$value) {
         return [];
     }
     /** @var CalendarRepository $calendarRepository */
     $calendarRepository = $this->registry->getRepository('OroCalendarBundle:Calendar');
     $organizationId = $this->securityFacade->getOrganizationId();
     if (!$organizationId) {
         throw new TransformationFailedException('Can\'t get current organization');
     }
     $events = new ArrayCollection();
     /** @var User $user */
     $userIds = [];
     foreach ($value as $user) {
         $userIds[] = $user->getId();
     }
     $calendars = $calendarRepository->findDefaultCalendars($userIds, $organizationId);
     foreach ($calendars as $calendar) {
         $event = new CalendarEvent();
         $event->setCalendar($calendar);
         $events->add($event);
     }
     return $events;
 }
 /**
  * @param ManagerRegistry $registry
  * @param ScreenplayProducer $screenplayProducer
  */
 public function __construct(ManagerRegistry $registry, ScreenplayProducer $screenplayProducer)
 {
     parent::__construct();
     $this->languagesRepository = $registry->getRepository(Language::class);
     $this->scenariosRepository = $registry->getRepository(Screenplay::class);
     $this->screenplayProducer = $screenplayProducer;
 }
예제 #11
0
 /**
  * @param string       $entityName
  * @param Organization $organization
  */
 public function setSourceEntityName($entityName, Organization $organization = null)
 {
     /** @var QueryBuilder $qb */
     $queryBuilder = $this->registry->getRepository($entityName)->createQueryBuilder('o');
     $metadata = $queryBuilder->getEntityManager()->getClassMetadata($entityName);
     foreach (array_keys($metadata->getAssociationMappings()) as $fieldName) {
         // can't join with *-to-many relations because they affects query pagination
         if ($metadata->isAssociationWithSingleJoinColumn($fieldName)) {
             $alias = '_' . $fieldName;
             $queryBuilder->addSelect($alias);
             $queryBuilder->leftJoin('o.' . $fieldName, $alias);
         }
     }
     foreach ($metadata->getIdentifierFieldNames() as $fieldName) {
         $queryBuilder->orderBy('o.' . $fieldName, 'ASC');
     }
     // Limit data with current organization
     if ($organization) {
         $organizationField = $this->ownershipMetadata->getMetadata($entityName)->getOrganizationFieldName();
         if ($organizationField) {
             $queryBuilder->andWhere('o.' . $organizationField . ' = :organization')->setParameter('organization', $organization);
         }
     }
     $this->setSourceQueryBuilder($queryBuilder);
 }
예제 #12
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $repository = $this->manager->getRepository($options['class']);
     $transformer = new EntityToIdentifierTransformer($repository, $options['identifier']);
     $builder->addModelTransformer($transformer);
     $builder->setAttribute('repository', $repository);
 }
예제 #13
0
 /**
  * @param $dateRange array with key start, end and type values is DateTime
  *
  * @return array
  */
 public function getChartData($dateRange)
 {
     $start = $dateRange['start'];
     $end = $dateRange['end'];
     $dates = $items = [];
     $period = new \DatePeriod($start, new \DateInterval('P1M'), $end);
     /** @var \DateTime $dt */
     foreach ($period as $dt) {
         $key = $dt->format('Y-m');
         $dates[$key] = ['month_year' => sprintf('%s-01', $key), 'amount' => 0];
     }
     $endDateKey = $end->format('Y-m');
     if (!in_array($endDateKey, array_keys($dates))) {
         $dates[$endDateKey] = ['month_year' => sprintf('%s-01', $endDateKey), 'amount' => 0];
     }
     $channelNames = $this->registry->getRepository('OroCRMChannelBundle:Channel')->getAvailableChannelNames($this->aclHelper);
     $data = $this->registry->getRepository('OroCRMChannelBundle:LifetimeValueAverageAggregation')->findForPeriod($start, $end, array_keys($channelNames));
     foreach ($data as $row) {
         $key = date('Y-m', strtotime(sprintf('%s-%s', $row['year'], $row['month'])));
         $channelName = $channelNames[$row['channelId']]['name'];
         if (!isset($items[$channelName])) {
             $items[$channelName] = $dates;
         }
         $items[$channelName][$key]['amount'] = (int) $row['amount'];
     }
     // restore default keys
     foreach ($items as $channelName => $item) {
         $items[$channelName] = array_values($item);
     }
     return $items;
 }
 /**
  * Display association grids
  *
  * @param Request $request the request
  * @param integer $id      the product id (owner)
  *
  * @AclAncestor("pim_enrich_associations_view")
  *
  * @return Response
  */
 public function associationsAction(Request $request, $id)
 {
     $product = $this->findProductOr404($id);
     $this->productManager->ensureAllAssociationTypes($product);
     $associationTypes = $this->doctrine->getRepository('PimCatalogBundle:AssociationType')->findAll();
     return $this->templating->renderResponse('PimEnrichBundle:Association:_associations.html.twig', array('product' => $product, 'associationTypes' => $associationTypes, 'dataLocale' => $request->get('dataLocale', null)));
 }
 /**
  * @return \DateTime|null
  */
 public function getLastSyncDate()
 {
     $channel = $this->getChannel();
     $repository = $this->managerRegistry->getRepository('OroIntegrationBundle:Status');
     /**
      * @var Status $status
      */
     $status = $repository->findOneBy(['code' => Status::STATUS_COMPLETED, 'channel' => $channel, 'connector' => $this->getType()], ['date' => 'DESC']);
     $timezone = new \DateTimeZone('UTC');
     $date = new \DateTime('now', $timezone);
     $context = $this->getStepExecution()->getExecutionContext();
     $data = $context->get(ConnectorInterface::CONTEXT_CONNECTOR_DATA_KEY) ?: [];
     $context->put(ConnectorInterface::CONTEXT_CONNECTOR_DATA_KEY, array_merge($data, [self::LAST_SYNC_DATE_KEY => $date->format(\DateTime::ISO8601)]));
     if (!$status) {
         return null;
     }
     $data = $status->getData();
     if (empty($data)) {
         return null;
     }
     if (!empty($data[self::LAST_SYNC_DATE_KEY])) {
         return new \DateTime($data[self::LAST_SYNC_DATE_KEY], $timezone);
     }
     return null;
 }
예제 #16
0
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     if (!$options['class']) {
         throw new LogicException('Option "class" must be set.');
     }
     $modelTransformer = new IdentifierToObjectTransformer($this->manager->getRepository($options['class']), $options['identifier']);
     $builder->addModelTransformer($modelTransformer);
 }
 /**
  * @param integer[] $ids
  *
  * @return ScraperEntity[]
  */
 protected function findScrapers(array $ids)
 {
     $repo = $this->doctrine->getRepository('TreeHouseIoBundle:Scraper');
     if (!empty($ids)) {
         return $repo->findBy(['id' => $ids]);
     }
     return $repo->findAll();
 }
예제 #18
0
 /**
  * {@inheritdoc}
  */
 public function loadUserByUsername($username)
 {
     $user = $this->registry->getRepository('CSBillUserBundle:User')->findOneBy(['username' => $username]);
     if (!$user) {
         throw new UsernameNotFoundException();
     }
     return $user;
 }
예제 #19
0
 protected function removeAll()
 {
     /** @var EntityManager $em */
     $em = $this->doctrine->getManager();
     foreach ($this->doctrine->getRepository('NetNexusTimesheetBundle:Workitem')->findAll() as $wi) {
         $em->remove($wi);
     }
     $em->flush();
 }
예제 #20
0
파일: ItemType.php 프로젝트: csbill/csbill
 /**
  * {@inheritdoc}
  */
 public function buildForm(FormBuilderInterface $builder, array $options)
 {
     $builder->add('description', TextareaType::class, ['attr' => ['class' => 'input-medium invoice-item-name']]);
     $builder->add('price', MoneyType::class, ['attr' => ['class' => 'input-small invoice-item-price']]);
     $builder->add('qty', NumberType::class, ['empty_data' => 1, 'attr' => ['class' => 'input-mini invoice-item-qty']]);
     if ($this->registry->getRepository('CSBillTaxBundle:Tax')->taxRatesConfigured()) {
         $builder->add('tax', Tax::class, ['class' => 'CSBill\\TaxBundle\\Entity\\Tax', 'placeholder' => 'Choose Tax Type', 'attr' => ['class' => 'input-mini invoice-item-tax'], 'required' => false]);
     }
 }
예제 #21
0
 /**
  * @return true
  */
 public function taxRatesConfigured()
 {
     static $taxConfigured;
     if (null !== $taxConfigured) {
         return $taxConfigured;
     }
     $taxConfigured = $this->registry->getRepository('CSBillTaxBundle:Tax')->taxRatesConfigured();
     return $taxConfigured;
 }
 /**
  * @return Website[]
  */
 protected function getWebsites()
 {
     if (null === $this->websites) {
         /** @var EntityRepository $entityRepository */
         $entityRepository = $this->registry->getRepository($this->websiteClass);
         $this->websites = $entityRepository->createQueryBuilder('website')->addOrderBy('website.id', 'ASC')->getQuery()->getResult();
     }
     return $this->websites;
 }
 /**
  * @param string $value
  * @param Constraint|ProductBySku $constraint
  *
  * {@inheritdoc}
  */
 public function validate($value, Constraint $constraint)
 {
     if ($value) {
         $product = $this->registry->getRepository('OroB2BProductBundle:Product')->findOneBySku($value);
         if (empty($product)) {
             $this->context->addViolation($constraint->message);
         }
     }
 }
 /**
  * @param string $entityClass
  */
 protected function addReindexJob($entityClass)
 {
     $job = $this->registry->getRepository('JMSJobQueueBundle:Job')->createQueryBuilder('job')->select('job')->where('job.command = :command')->andWhere('cast(job.args as text) = :args')->andWhere('job.state in (\'pending\', \'running\')')->setParameter('command', ReindexCommand::COMMAND_NAME)->setParameter('args', ['class' => $entityClass], Type::JSON_ARRAY)->setMaxResults(1)->getQuery()->getOneOrNullResult();
     if (!$job) {
         $job = new Job(ReindexCommand::COMMAND_NAME, ['class' => $entityClass]);
         $em = $this->registry->getManager();
         $em->persist($job);
         $em->flush($job);
     }
 }
예제 #25
0
파일: ORMSource.php 프로젝트: csbill/csbill
 /**
  * {@inheritdoc}
  */
 public function fetch(array $parameters = [])
 {
     $repository = $this->registry->getRepository($this->repository);
     $method = $this->method;
     $qb = $repository->{$method}($parameters);
     if (!$qb instanceof QueryBuilder) {
         throw new \Exception('Grid source should return a query builder');
     }
     return $qb;
 }
예제 #26
0
 /**
  * Checks if the entity can have activities
  *
  * @param object|null $entity
  * @return bool
  */
 public function isApplicable($entity = null)
 {
     if (null === $entity || !is_object($entity)) {
         return false;
     }
     $entityClass = $this->doctrineHelper->getEntityClass($entity);
     $id = $this->doctrineHelper->getSingleEntityIdentifier($entity);
     $activityListRepo = $this->doctrine->getRepository('OroActivityListBundle:ActivityList');
     return in_array($entityClass, $this->activityListProvider->getTargetEntityClasses()) || (bool) $activityListRepo->getRecordsCountForTargetClassAndId($entityClass, $id);
 }
 /**
  * {@inheritdoc}
  */
 public function finishView(FormView $view, FormInterface $form, array $options)
 {
     /** @var PriceList[] $priceLists */
     $priceLists = $this->registry->getRepository($this->priceListClass)->findAll();
     $currencies = [];
     foreach ($priceLists as $priceList) {
         $currencies[$priceList->getId()] = $priceList->getCurrencies();
     }
     $view->vars['attr']['data-currencies'] = json_encode($currencies);
 }
 /**
  * @param Container $container
  * @param ManagerRegistry $registry
  */
 public function __construct(Container $container, ManagerRegistry $registry)
 {
     parent::__construct('dwarfSearch:import');
     $this->entityManager = $registry->getManager();
     $this->seasonsRepository = $registry->getRepository(Season::class);
     $this->episodesRepository = $registry->getRepository(Episode::class);
     $this->languagesRepository = $registry->getRepository(Language::class);
     $this->charactersRepository = $registry->getRepository(Character::class);
     $this->scenariosDir = Helpers::expand('%appDir%/../scenarios', $container->getParameters());
 }
예제 #29
0
 /**
  * Check whether job for export is already scheduled and waiting to be processed
  *
  * @param array $args
  *
  * @return bool
  */
 protected function isScheduled(array $args)
 {
     $qb = $this->registry->getRepository('JMSJobQueueBundle:Job')->createQueryBuilder('j');
     $qb->select('count(j.id)');
     $qb->andWhere('j.command = :command');
     $qb->andWhere('j.args = :args');
     $qb->andWhere($qb->expr()->in('j.state', [Job::STATE_PENDING, Job::STATE_NEW]));
     $qb->setParameter('command', self::JOB_NAME);
     $qb->setParameter('args', $args, Type::JSON_ARRAY);
     return $qb->getQuery()->getSingleScalarResult();
 }
예제 #30
0
 /**
  * Checks if the entity can have activities
  *
  * @param object|null $entity
  * @param int|null    $pageType
  * @return bool
  */
 public function isApplicable($entity = null, $pageType = null)
 {
     if ($pageType === null || !is_object($entity) || !$this->doctrineHelper->isManageableEntity($entity) || $this->doctrineHelper->isNewEntity($entity)) {
         return false;
     }
     $pageType = (int) $pageType;
     $id = $this->doctrineHelper->getSingleEntityIdentifier($entity);
     $entityClass = $this->doctrineHelper->getEntityClass($entity);
     $activityListRepo = $this->doctrine->getRepository('OroActivityListBundle:ActivityList');
     return $this->isAllowedOnPage($entity, $pageType) && (in_array($entityClass, $this->activityListProvider->getTargetEntityClasses()) || (bool) $activityListRepo->getRecordsCountForTargetClassAndId($entityClass, $id));
 }