/**
  * Transforms a collection os files on session on entities
  *
  * @throws TransformationFailedException if object (issue) is not found.
  */
 public function reverseTransform($id)
 {
     // Pasar los ficheros almacenados en la sesión a la carpeta web y devolver el array de ficheros
     $manager = $this->orphanageManager->get('gallery');
     $images = $manager->uploadFiles();
     if (count($images) == 0) {
         return null;
     } else {
         if (count($images) == 1) {
             $file = $this->om->getRepository('AppBundle:File')->findOneByPath('uploads/gallery/' . $images[0]->getFilename());
             if ($file == null) {
                 $file = new File();
                 $file->setPath('uploads/gallery/' . $images[0]->getFilename());
                 $this->om->persist($file);
                 $this->om->flush();
             }
             $data = $file;
         } else {
             $data = array();
             foreach ($images as $image) {
                 $file = $this->om->getRepository('AppBundle:File')->findOneByPath('uploads/gallery/' . $image->getFilename());
                 if ($file == null) {
                     $file = new File();
                     $file->setPath('uploads/gallery/' . $image->getFilename());
                     $this->om->persist($file);
                     $this->om->flush();
                 }
                 $data[] = $file;
             }
             $this->om->flush();
         }
     }
     return $data;
 }
 /**
  * @param string                                                      $class
  * @param \Doctrine\Common\Persistence\ManagerRegistry                $manager_registry
  * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispatcher
  */
 public function __construct($class, ManagerRegistry $manager_registry, EventDispatcherInterface $event_dispatcher = null)
 {
     $this->class = $class;
     $this->event_dispatcher = $event_dispatcher;
     $this->entity_manager = $manager_registry->getManagerForClass($class);
     $this->entity_repository = $this->entity_manager->getRepository($class);
 }
 /**
  * Load data fixtures with the passed EntityManager
  *
  * @param \Doctrine\Common\Persistence\ObjectManager $manager
  */
 function load(ObjectManager $manager)
 {
     $typeRepo = $manager->getRepository('GotChosenSiteBundle:NotificationCommType');
     $general = $typeRepo->findOneBy(['typeName' => 'General Notifications']);
     if (!$general) {
         $general = new NotificationCommType();
         $general->setTypeName('General Notifications');
         $manager->persist($general);
     }
     $eg = $typeRepo->findOneBy(['typeName' => 'Evolution Games Notifications']);
     if (!$eg) {
         $eg = new NotificationCommType();
         $eg->setTypeName('Evolution Games Notifications');
         $manager->persist($eg);
     }
     $manager->flush();
     $notificationTypes = [['Newsletters', $general, true], ['Scholarship Information', $general, false], ['Sponsor Notifications', $general, false], ['Developer Feedback Notifications', $eg, false], ['Scholarship Notifications', $eg, false], ['EG News', $eg, false]];
     $repo = $manager->getRepository('GotChosenSiteBundle:NotificationType');
     foreach ($notificationTypes as $nt) {
         if (!$repo->findOneBy(['name' => $nt[0]])) {
             $type = new NotificationType();
             $type->setName($nt[0]);
             $type->setCommType($nt[1]);
             $type->setIsDefault($nt[2]);
             $manager->persist($type);
         }
     }
     $manager->flush();
 }
Beispiel #4
0
 /**
  * This method is executed after initialize(). It usually contains the logic
  * to execute to complete this command task.
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $maxResults = $input->getOption('max-results');
     // Use ->findBy() instead of ->findAll() to allow result sorting and limiting
     $users = $this->entityManager->getRepository('AppBundle:User')->findBy(array(), array('id' => 'DESC'), $maxResults);
     // Doctrine query returns an array of objects and we need an array of plain arrays
     $usersAsPlainArrays = array_map(function (User $user) {
         return array($user->getId(), $user->getUsername(), $user->getEmail(), implode(', ', $user->getRoles()));
     }, $users);
     // In your console commands you should always use the regular output type,
     // which outputs contents directly in the console window. However, this
     // particular command uses the BufferedOutput type instead.
     // The reason is that the table displaying the list of users can be sent
     // via email if the '--send-to' option is provided. Instead of complicating
     // things, the BufferedOutput allows to get the command output and store
     // it in a variable before displaying it.
     $bufferedOutput = new BufferedOutput();
     $table = new Table($bufferedOutput);
     $table->setHeaders(array('ID', 'Username', 'Email', 'Roles'))->setRows($usersAsPlainArrays);
     $table->render();
     // instead of displaying the table of users, store it in a variable
     $tableContents = $bufferedOutput->fetch();
     if (null !== ($email = $input->getOption('send-to'))) {
         $this->sendReport($tableContents, $email);
     }
     $output->writeln($tableContents);
 }
Beispiel #5
0
 /**
  * Load data fixtures with the passed EntityManager
  *
  * @param ObjectManager $manager
  */
 public function load(ObjectManager $manager)
 {
     $countries = $manager->getRepository('SehBundle:Country')->findAll();
     foreach ($countries as $country) {
         $countryBrand = new Country();
         $countryBrand->setCountry($country);
         $manager->persist($countryBrand);
     }
     $regions = $manager->getRepository('SehBundle:Region')->findAll();
     foreach ($regions as $region) {
         $regionBrand = new Region();
         $regionBrand->setRegion($region);
         $manager->persist($regionBrand);
     }
     $departments = $manager->getRepository('SehBundle:Department')->findAll();
     foreach ($departments as $department) {
         $departmentBrand = new Department();
         $departmentBrand->setDepartment($department);
         $manager->persist($departmentBrand);
     }
     $thematics = $manager->getRepository('SehBundle:Thematic')->findAll();
     foreach ($thematics as $thematic) {
         $thematicBrand = new Thematic();
         $thematicBrand->setThematic($thematic);
         $manager->persist($thematicBrand);
     }
     $cities = $manager->getRepository('SehBundle:City')->findAll();
     foreach ($cities as $city) {
         $cityBrand = new City();
         $cityBrand->setCity($city);
         $manager->persist($cityBrand);
     }
     $manager->flush();
 }
 /**
  * Update activity
  * @param ObjectManager $manager
  */
 public function updateEmailActivityDescription(ObjectManager $manager)
 {
     /** @var QueryBuilder $activityListBuilder */
     $activityListBuilder = $manager->getRepository('OroActivityListBundle:ActivityList')->createQueryBuilder('e');
     $iterator = new BufferedQueryResultIterator($activityListBuilder);
     $iterator->setBufferSize(self::BATCH_SIZE);
     $itemsCount = 0;
     $entities = [];
     $emailRepository = $manager->getRepository('OroEmailBundle:Email');
     $activityProvider = $this->container->get('oro_email.activity_list.provider');
     foreach ($iterator as $activity) {
         $email = $emailRepository->find($activity->getRelatedActivityId());
         if ($email) {
             $itemsCount++;
             $activity->setDescription($activityProvider->getDescription($email));
             $entities[] = $activity;
         }
         if (0 === $itemsCount % self::BATCH_SIZE) {
             $this->saveEntities($manager, $entities);
             $entities = [];
         }
     }
     if ($itemsCount % self::BATCH_SIZE > 0) {
         $this->saveEntities($manager, $entities);
     }
 }
Beispiel #7
0
 public function load(ObjectManager $manager)
 {
     // Obtener todas las ofertas y usuarios de la base de datos
     $offers = $manager->getRepository('TestBundle:Offer')->findAll();
     $users = $manager->getRepository('TestBundle:User')->findAll();
     foreach ($users as $user) {
         $shopping = rand(0, 3);
         $bought = array();
         for ($i = 0; $i < $shopping; $i++) {
             $sale = new Sale();
             $sale->setDate(new \DateTime('now - ' . rand(0, 250) . ' hours'));
             // Sólo se añade una venta:
             //   - si este mismo usuario no ha comprado antes la misma oferta
             //   - si la oferta seleccionada ha sido revisada
             //   - si la fecha de publicación de la oferta es posterior a ahora mismo
             $offer = $offers[array_rand($offers)];
             while (in_array($offer->getId(), $bought) || $offer->getChecked() == false || $offer->getPublicationDate() > new \DateTime('now')) {
                 $offer = $offers[array_rand($offers)];
             }
             $bought[] = $offer->getId();
             $sale->setOffer($offer);
             $sale->setUser($user);
             $manager->persist($sale);
             $offer->setShopping($offer->getShopping() + 1);
             $manager->persist($offer);
         }
         unset($bought);
     }
     $manager->flush();
 }
 /**
  * WishlistManager constructor.
  *
  * @param ObjectManager $objectManager
  * @param string        $class
  */
 public function __construct(ObjectManager $objectManager, string $class)
 {
     $this->objectManager = $objectManager;
     $this->repository = $this->objectManager->getRepository($class);
     $metadata = $objectManager->getClassMetadata($class);
     $this->class = $metadata->getName();
 }
Beispiel #9
0
 public function load(ObjectManager $manager)
 {
     $conn = $manager->getConnection();
     $stmt = $conn->prepare('select id from lots');
     $stmt->execute();
     $lotIds = [];
     while ($lotId = $stmt->fetchColumn()) {
         $lotIds[] = (int) $lotId;
     }
     $stmt = $conn->prepare('select id from users');
     $stmt->execute();
     $usrIds = [];
     while ($usrId = $stmt->fetchColumn()) {
         $usrIds[] = (int) $usrId;
     }
     for ($i = 0, $l = count($lotIds) * count($usrIds); $i < $l; $i++) {
         $lot = $manager->getRepository('BankrotSiteBundle:Lot')->find($lotIds[array_rand($lotIds)]);
         if ($lot->getBeginDate()) {
             if (0 === rand(0, 2)) {
                 $lw = new LotWatch();
                 $lw->setOwner($manager->getRepository('BankrotSiteBundle:User')->find($usrIds[array_rand($usrIds)]));
                 $lw->setLot($lot);
                 $lw->setPrice(rand(0, 1000000));
                 $lw->setCutOffPrice(rand(10, 5000));
                 $lw->setDay(new \DateTime('@' . rand($lot->getBeginDate()->getTimestamp(), $lot->getEndDate()->getTimestamp())));
                 $manager->persist($lw);
             }
         }
     }
     $manager->flush();
 }
 /**
  * Import Projects
  */
 private function importProjects()
 {
     $this->output->write(sprintf('%-30s', 'Importing projects'));
     $previewProjects = $this->previewService->getProjects();
     $created = 0;
     $updated = 0;
     foreach ($previewProjects as $previewProject) {
         /**
          * @var Project $project
          */
         $project = $this->entityManager->getRepository('ProjectPreviewProjectBundle:Project')->find($previewProject->id);
         if (is_null($project)) {
             $project = new Project();
             $project->setId($previewProject->id);
             $created++;
         } else {
             $updated++;
         }
         $project->setName($previewProject->name);
         $project->setArchived($previewProject->archived);
         $this->entityManager->persist($project);
     }
     $this->output->writeln(sprintf('done (total: % 4d, created: % 4d, updated: % 4d)', $created + $updated, $created, $updated));
     $this->entityManager->flush();
 }
 /**
  * Prepare & process form
  *
  * @author Jeremie Samson <*****@*****.**>
  *
  * @return bool
  */
 public function process()
 {
     if ($this->request->isMethod('POST')) {
         $this->form->handleRequest($this->request);
         if ($this->form->isValid()) {
             /** @var ModelUserRole $model */
             $model = $this->form->getData();
             if (!$model->getUser() || !$model->getRole()) {
                 $this->form->addError(new FormError('Missing parameter(s)'));
             }
             /** @var User $user */
             $user = $this->em->getRepository('UserBundle:User')->find($model->getUser());
             /** @var Post $role */
             $role = $this->em->getRepository('FaucondorBundle:Post')->find($model->getRole());
             if (!$user) {
                 $this->form->get('user')->addError(new FormError('User with id ' . $model->getUser() . ' not found '));
             }
             if (!$role) {
                 $this->form->get('role')->addError(new FormError('Role with id ' . $model->getRole() . ' not found '));
             }
             $this->onSuccess($user, $role);
             return true;
         }
     }
     return false;
 }
 /**
  * @param FormEvent $event
  *
  * @throws FormException
  */
 public function initAttachmentEntity(FormEvent $event)
 {
     /** @var AttachmentModel $attachment */
     $attachment = $event->getData();
     // this check is necessary due to inability to capture file input dialog cancel event
     if (!$attachment) {
         return;
     }
     if (!$attachment->getEmailAttachment()) {
         switch ($attachment->getType()) {
             case AttachmentModel::TYPE_ATTACHMENT:
                 $repo = $this->em->getRepository('OroAttachmentBundle:Attachment');
                 $oroAttachment = $repo->find($attachment->getId());
                 $emailAttachment = $this->emailAttachmentTransformer->oroToEntity($oroAttachment);
                 break;
             case AttachmentModel::TYPE_EMAIL_ATTACHMENT:
                 $repo = $this->em->getRepository('OroEmailBundle:EmailAttachment');
                 $emailAttachment = $repo->find($attachment->getId());
                 break;
             case AttachmentModel::TYPE_UPLOADED:
                 $emailAttachment = $this->emailAttachmentTransformer->entityFromUploadedFile($attachment->getFile());
                 break;
             default:
                 throw new FormException(sprintf('Invalid attachment type: %s', $attachment->getType()));
         }
         $attachment->setEmailAttachment($emailAttachment);
     }
     $event->setData($attachment);
 }
Beispiel #13
0
 /**
  * @return array
  */
 public function getData()
 {
     /** @var ClientRepository $clientRepository */
     $clientRepository = $this->manager->getRepository('CSBillClientBundle:Client');
     $clients = $clientRepository->getRecentClients();
     return ['clients' => $clients];
 }
Beispiel #14
0
 /**
  * @return array
  */
 public function getData()
 {
     /** @var PaymentRepository $paymentRepository */
     $paymentRepository = $this->manager->getRepository('CSBillPaymentBundle:Payment');
     $payments = $paymentRepository->getRecentPayments();
     return ['payments' => $payments];
 }
Beispiel #15
0
 /**
  * @return BaseFaqRepository
  */
 public function getRepository()
 {
     if ($this->repository === null) {
         $this->repository = $this->objectManager->getRepository($this->faqClass);
     }
     return $this->repository;
 }
Beispiel #16
0
 /**
  * @return array
  */
 public function getData()
 {
     /** @var QuoteRepository $quoteRepository */
     $quoteRepository = $this->manager->getRepository('CSBillQuoteBundle:Quote');
     $quotes = $quoteRepository->getRecentQuotes();
     return array('quotes' => $quotes);
 }
 /**
  * Import Users
  */
 private function importUsers()
 {
     $this->output->write(sprintf('%-30s', 'Importing users'));
     $previewUsers = $this->previewService->getUsers();
     $created = 0;
     $updated = 0;
     foreach ($previewUsers as $previewUser) {
         if (!strlen($previewUser->email)) {
             continue;
         }
         /**
          * @var User $user
          */
         $user = $this->entityManager->getRepository('ProjectPreviewUserBundle:User')->find($previewUser->id);
         if (is_null($user)) {
             $user = new User();
             $user->setId($previewUser->id);
             $user->setPassword('toto');
             $created++;
         } else {
             $updated++;
         }
         $user->setEmail($previewUser->email);
         $user->setUsername($previewUser->email);
         $user->setLastname($previewUser->lastname);
         $user->setFirstname($previewUser->firstname);
         if (isset($previewUser->avatar->urls->avatar_xs)) {
             $user->setAvatar($previewUser->avatar->urls->avatar_xs);
         }
         $this->entityManager->persist($user);
     }
     $this->output->writeln(sprintf('done (total: % 4d, created: % 4d, updated: % 4d)', $created + $updated, $created, $updated));
     $this->entityManager->flush();
 }
 public function __construct(ObjectManager $em, $className)
 {
     $this->handlers = array();
     $this->em = $em;
     $this->className = $className;
     $this->notificationRules = $this->em->getRepository($this->className)->getRules();
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->init();
     $limit = 50;
     $offset = 0;
     $repository = $this->em->getRepository('AppBundle:Sale');
     $existingInvoices = $repository->findExistingInvoices();
     try {
         $json = $this->getSales($limit, $offset);
         $this->saveSales($json['sales'], $existingInvoices);
         $output->writeln('Saving bunch of sales...');
         $total = $json['numSales'];
         $this->em->flush();
         do {
             $offset += $limit;
             $json = $this->getSales($limit, $offset);
             $this->saveSales($json['sales'], $existingInvoices);
             $output->writeln('Saving bunch of sales...');
             $this->em->flush();
         } while ($total > $limit + $offset);
     } catch (\Exception $e) {
         $output->writeln($e->getMessage());
         return;
     }
     $output->writeln(sprintf('Imported %s sales', $total));
 }
 public function reverseTransform($string)
 {
     if (!$string) {
         return;
     }
     $tags = new ArrayCollection();
     foreach (explode(',', $string) as $tagTitle) {
         $tag = $this->om->getRepository('AppBundle:Tag')->findOneByTitle($tagTitle);
         if (!$tag && ($tagTranslation = $this->om->getRepository('AppBundle:Translations\\TagTranslation')->findOneByContent($tagTitle))) {
             $tag = $tagTranslation->getObject();
         }
         if (!$tag) {
             $tag = new Tag();
             $tag->setTitle($tagTitle);
             $tag->setLocale($this->defaultLocale);
             foreach ($this->localeCollection as $locale) {
                 if ($locale !== $this->defaultLocale) {
                     $tagTranslation = new TagTranslation();
                     $tagTranslation->setLocale($locale);
                     $tagTranslation->setField('title');
                     $tagTranslation->setContent($tagTitle);
                     $tagTranslation->setObject($tag);
                     $tag->addTranslation($tagTranslation);
                     $this->om->persist($tagTranslation);
                 }
             }
             $this->om->persist($tag);
         }
         $tags->add($tag);
     }
     return $tags;
 }
Beispiel #21
0
 public function load(ObjectManager $manager)
 {
     $user1 = $manager->getRepository('StepUserBundle:User')->findOneByPrenom('Geoffrey');
     $user2 = $manager->getRepository('StepUserBundle:User')->findOneByPrenom('Delphine');
     $pas1 = $manager->getRepository('StepAppBundle:Pas')->findOneByNom('Basique');
     $pas2 = $manager->getRepository('StepAppBundle:Pas')->findOneByNom('Step Touch');
     $commentaire = new Commentaire();
     $commentaire->setMessage('Un petit pas très facil pour commencer :D');
     $commentaire->setUser($user2);
     $commentaire->setPas($pas1);
     $manager->persist($commentaire);
     $commentaire = new Commentaire();
     $commentaire->setMessage('Oh Yeah, j\'aime !');
     $commentaire->setUser($user1);
     $commentaire->setPas($pas1);
     $manager->persist($commentaire);
     $commentaire = new Commentaire();
     $commentaire->setMessage('Un petit pas très facil pour commencer :D');
     $commentaire->setUser($user1);
     $commentaire->setPas($pas2);
     $manager->persist($commentaire);
     $commentaire = new Commentaire();
     $commentaire->setMessage('Oh Yeah, j\'aime !');
     $commentaire->setUser($user2);
     $commentaire->setPas($pas2);
     $manager->persist($commentaire);
     $manager->flush();
 }
 /**
  * @param BuildAfter $event
  */
 public function onBuildAfter(BuildAfter $event)
 {
     /** @var OrmDatasource $dataSource */
     $datagrid = $event->getDatagrid();
     $config = $datagrid->getConfig();
     $configParameters = $config->toArray();
     if (!array_key_exists('extended_entity_name', $configParameters) || !$configParameters['extended_entity_name']) {
         return;
     }
     $targetClass = $configParameters['extended_entity_name'];
     $parameters = $datagrid->getParameters();
     $dataSource = $datagrid->getDatasource();
     $queryBuilder = $dataSource->getQueryBuilder();
     $alias = current($queryBuilder->getDQLPart('from'))->getAlias();
     if ($dataSource instanceof OrmDatasource && $parameters->has('activityId')) {
         $activityId = $parameters->get('activityId');
         $email = $this->entityManager->getRepository('OroEmailBundle:Email')->find($activityId);
         if ($email) {
             $targetsArray = $email->getActivityTargets($targetClass);
             $targetIds = [];
             foreach ($targetsArray as $target) {
                 $targetIds[] = $target->getId();
             }
             if ($targetIds) {
                 $queryBuilder->andWhere($queryBuilder->expr()->notIn("{$alias}.id", $targetIds));
             }
         }
     }
 }
 /**
  *
  * @param string $inPostal1
  * @param string|array $inPostal2
  * @return array
  */
 public function getDistanceBetweenPostalCodes($inPostal1, $inPostal2)
 {
     $codes = $this->adjustCodes($inPostal1, $inPostal2);
     // When we are comparing two identical postal codes inPostal2 is a string
     if (is_string($inPostal2) && $codes[0] == $codes[1]) {
         return array($inPostal1 => array($inPostal1 => new Distance(0)));
     }
     /** @var PostalCode[] $data */
     $data = $this->entityMgr->getRepository('NSDistanceBundle:PostalCode')->getByCodes($codes);
     if (count($data) < 2) {
         return array();
     }
     if (!isset($data[$codes[0]])) {
         throw new UnknownPostalCodeException(sprintf("Source postalcode '%s/%s' not found", $inPostal1, $codes[0]));
     }
     $postal1 = $data[$codes[0]];
     if (is_array($inPostal2)) {
         $ret = array();
         $source = array_shift($codes);
         if (in_array($source, $codes)) {
             $ret[$source] = new Distance(0);
         }
         foreach ($data as $pcode) {
             if ($pcode != $postal1) {
                 $ret[$pcode->getPostalCode()] = $this->getDistance($postal1, $pcode);
             }
         }
         return array($postal1->getPostalCode() => $ret);
     }
     $postal2 = $data[$codes[1]];
     return array($postal1->getPostalCode() => array($postal2->getPostalCode() => $this->getDistance($postal1, $postal2)));
 }
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     /** @var UserManager $userManager */
     $userManager = $this->container->get('oro_user.manager');
     $admin = $userManager->findUserByEmail(LoadAdminUserData::DEFAULT_ADMIN_EMAIL);
     $organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();
     /** @var Store $store */
     $store = $this->getReference('store');
     /** @var Channel $channel */
     $channel = $this->getReference('default_channel');
     /** @var Integration $integration */
     $integration = $this->getReference('integration');
     $className = ExtendHelper::buildEnumValueClassName('mage_subscr_status');
     $enumRepo = $manager->getRepository($className);
     foreach ($this->subscriberData as $data) {
         $subscriber = new NewsletterSubscriber();
         $date = new \DateTime();
         $date->modify('-1 day');
         /** @var AbstractEnumValue $status */
         $status = $enumRepo->find($data['status']);
         $subscriber->setEmail($data['email'])->setStatus($status)->setConfirmCode(uniqid())->setStore($store)->setOwner($admin)->setOrganization($organization)->setOriginId($data['originId'])->setChangeStatusAt($date)->setCreatedAt($date)->setUpdatedAt($date)->setChannel($integration)->setDataChannel($channel);
         if (!empty($data['customer'])) {
             /** @var Customer $customer */
             $customer = $this->getReference($data['customer']);
             $subscriber->setCustomer($customer);
         }
         $this->setReference($data['reference'], $subscriber);
         $manager->persist($subscriber);
     }
     $manager->flush();
 }
Beispiel #25
0
 public function load(ObjectManager $manager)
 {
     // Obtener todas las ofertas y usuarios de la base de datos
     $ofertas = $manager->getRepository('OfertaBundle:Oferta')->findAll();
     $usuarios = $manager->getRepository('UsuarioBundle:Usuario')->findAll();
     foreach ($usuarios as $usuario) {
         $compras = rand(0, 3);
         $comprado = array();
         for ($i = 0; $i < $compras; $i++) {
             $venta = new Venta();
             $venta->setFecha(new \DateTime('now - ' . rand(0, 250) . ' hours'));
             // Sólo se añade una venta:
             //   - si este mismo usuario no ha comprado antes la misma oferta
             //   - si la oferta seleccionada ha sido revisada
             //   - si la fecha de publicación de la oferta es posterior a ahora mismo
             $oferta = $ofertas[array_rand($ofertas)];
             while (in_array($oferta->getId(), $comprado) || $oferta->getRevisada() == false || $oferta->getFechaPublicacion() > new \DateTime('now')) {
                 $oferta = $ofertas[array_rand($ofertas)];
             }
             $comprado[] = $oferta->getId();
             $venta->setOferta($oferta);
             $venta->setUsuario($usuario);
             $manager->persist($venta);
             $oferta->setCompras($oferta->getCompras() + 1);
             $manager->persist($oferta);
         }
         unset($comprado);
     }
     $manager->flush();
 }
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     // record all school years
     $entity = new SchoolYear();
     $entity->setDateStart(new \DateTime('2015-09-01'));
     $entity->setDateEnd(new \DateTime('2016-07-05'));
     $entity->setFilenameIcalendar('Calendrier_Scolaire_Zone_B.ics');
     $manager->persist($entity);
     $this->setReference('2015-2016', $entity);
     $entity = new SchoolYear();
     $entity->setDateStart(new \DateTime('2016-09-01'));
     $entity->setDateEnd(new \DateTime('2017-07-07'));
     $entity->setFilenameIcalendar('Calendrier_Scolaire_Zone_B.ics');
     $manager->persist($entity);
     $this->setReference('2016-2017', $entity);
     $entity = new SchoolYear();
     $entity->setDateStart(new \DateTime('2017-09-04'));
     $entity->setDateEnd(new \DateTime('2018-07-06'));
     $entity->setFilenameIcalendar('Calendrier_Scolaire_Zone_B.ics');
     $manager->persist($entity);
     $this->setReference('2017-2018', $entity);
     $manager->flush();
     $path = __DIR__ . '/../Files/';
     // record all holidays
     $this->getReference('2015-2016')->setUploadAbsolutePath($path);
     $manager->getRepository('WCSCantineBundle:SchoolHoliday')->updateAllFrom($this->getReference('2015-2016'));
     $this->getReference('2016-2017')->setUploadAbsolutePath($path);
     $manager->getRepository('WCSCantineBundle:SchoolHoliday')->updateAllFrom($this->getReference('2016-2017'));
     $this->getReference('2017-2018')->setUploadAbsolutePath($path);
     $manager->getRepository('WCSCantineBundle:SchoolHoliday')->updateAllFrom($this->getReference('2017-2018'));
 }
 public function load($resource, $type = null)
 {
     if (true === $this->loaded) {
         throw new \RuntimeException('Do not add the "extra" loader twice');
     }
     $entities = $this->_em->getRepository("BigfishCoreBundle:CacheRouting")->findAll();
     $collection = new RouteCollection();
     var_dump($collection);
     exit;
     for ($i = 0; $i < 100000; $i++) {
         $route = $this->addCollection("item-" . $i, array("_controller" => "ExampleExampleBundle:Default:test", "number" => $i));
         $collection->add("resource_" . $i, $route);
     }
     //        foreach ($entities as $entity) {
     //            $route = new Route($entity->getPath());
     //
     //            $pageClass = ($entity->getResource()->getPageClass()) ? $entity->getResource()->getPageClass() : $entity->getResource()->getPageClass();
     //
     //            $route->setDefaults(array(
     //                "_controller" => $pageClass,
     //                "resourceId" => $entity->getResource()->getId(),
     //                "templatePath" => $entity->getResource()->getTemplate()->getPath(),
     //                "moduleId" => $entity->getResource()->getTemplate()->getModule()->getId()
     //            ));
     //
     //            $collection->add("resource_".$entity->getResource()->getId(), $route);
     //        }
     //        var_dump($entities);
     //        exit;
     //        exit;
     $this->loaded = true;
     return $collection;
 }
 /**
  * Display path player
  * @param  \Innova\PathBundle\Entity\Path\Path $path
  * @return array
  *
  * @Route(
  *      "/{id}",
  *      name     = "innova_path_player_wizard",
  *      defaults = { "stepId" = null },
  *      options  = { "expose" = true }
  * )
  * @Template("InnovaPathBundle:Wizard:player.html.twig")
  */
 public function displayAction(Path $path)
 {
     // Check User credentials
     $this->pathManager->checkAccess('OPEN', $path);
     $resourceIcons = $this->om->getRepository('ClarolineCoreBundle:Resource\\ResourceIcon')->findByIsShortcut(false);
     return array('_resource' => $path, 'userProgression' => $this->pathManager->getUserProgression($path), 'resourceIcons' => $resourceIcons, 'editEnabled' => $this->pathManager->isAllow('EDIT', $path));
 }
 /**
  * @param User $user
  * @return ReportCard
  */
 public function getForUser(User $user)
 {
     $uid = (string) $user->getId();
     if ($this->cache->contains($uid)) {
         return $this->cache->fetch($uid);
     }
     /** @var EGPlayerStatsRepository $statsRepo */
     $statsRepo = $this->em->getRepository('GotChosenSiteBundle:EGPlayerStats');
     /** @var EGGameResultRepository $resultsRepo */
     $resultsRepo = $this->em->getRepository('GotChosenSiteBundle:EGGameResult');
     /** @var Scholarship $egScholarship */
     $egScholarship = $this->em->getRepository('GotChosenSiteBundle:Scholarship')->getCurrentEvoGames();
     $playerStats = $statsRepo->getOrCreate($user, $egScholarship, date('Y-m'));
     $card = new ReportCard();
     $card->rank = $playerStats->getRank();
     $card->maxRank = $statsRepo->getTotalPlayers(date('Y-m'));
     $card->qualifierPlays = $statsRepo->getTotalPlaySessions($user, $egScholarship, EGPlaySession::PHASE_QUALIFIER);
     $card->contestPlays = $statsRepo->getTotalPlaySessions($user, $egScholarship, EGPlaySession::PHASE_CONTEST);
     $card->wins = $resultsRepo->getTotalWins($user, date('Y-m'));
     $card->feedbacksRated = min(20, $playerStats->getFeedbacksRated());
     $card->pointsWinning = $playerStats->getGameplayPoints();
     $card->pointsBonus = $playerStats->getBonusPoints();
     $card->pointsFeedback = $playerStats->getFeedbackPoints();
     $card->pointsTotal = $playerStats->getTotalPoints();
     $this->cache->save($uid, $card);
     return $card;
 }
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     /** @var AccountUser[] $accountUsers */
     $accountUsers = $manager->getRepository('OroB2BCustomerBundle:AccountUser')->findAll();
     $internalRatings = $manager->getRepository(ExtendHelper::buildEnumValueClassName(Customer::INTERNAL_RATING_CODE))->findAll();
     $rootCustomer = null;
     $firstLevelCustomer = null;
     // create customer groups
     $rootGroup = $this->createCustomerGroup('Root');
     $firstLevelGroup = $this->createCustomerGroup('First');
     $secondLevelGroup = $this->createCustomerGroup('Second');
     $manager->persist($rootGroup);
     $manager->persist($firstLevelGroup);
     $manager->persist($secondLevelGroup);
     // create customers
     foreach ($accountUsers as $index => $accountUser) {
         $customer = $accountUser->getCustomer();
         switch ($index % 3) {
             case 0:
                 $customer->setGroup($rootGroup);
                 $rootCustomer = $customer;
                 break;
             case 1:
                 $customer->setGroup($firstLevelGroup)->setParent($rootCustomer);
                 $firstLevelCustomer = $customer;
                 break;
             case 2:
                 $customer->setGroup($secondLevelGroup)->setParent($firstLevelCustomer);
                 break;
         }
         $customer->setInternalRating($internalRatings[array_rand($internalRatings)]);
     }
     $manager->flush();
 }