Since: 2.0
Author: Guilherme Blanco (guilhermeblanco@hotmail.com)
Author: Jonathan Wage (jonwage@gmail.com)
Author: Roman Borschel (roman@code-factory.org)
Inheritance: implements Doctrine\Common\Collections\Collection
Exemplo n.º 1
1
 /**
  * @param $locale
  * @param null $id
  * @param bool $showHome
  * @param bool $showChildren
  * @return \Doctrine\ORM\QueryBuilder|mixed
  */
 public function getParentPagesQuery($locale, $id = null, $showHome = false, $showChildren = false)
 {
     $qb = $this->createQueryBuilder('p');
     if (!$showHome) {
         $qb->where($qb->expr()->isNull('p.isHome') . ' OR p.isHome <> 1');
     }
     if ($id) {
         if (!$showChildren) {
             /** @var $page PageInterface */
             $page = $this->find($id);
             $collection = new ArrayCollection($page->getAllChildren());
             $childrenIds = $collection->map(function (PageInterface $p) {
                 return $p->getId();
             });
             if ($childrenIds->count()) {
                 $qb->andWhere($qb->expr()->notIn('p.id', $childrenIds->toArray()));
             }
         }
         $qb->andWhere($qb->expr()->neq('p.id', $id));
     }
     $qb->andWhere('p.locale = :locale');
     $qb->orderBy('p.path', 'ASC');
     $qb->setParameter(':locale', $locale);
     return $qb;
 }
 /**
  * @param LineItem $asset
  * @return HasAssetLog
  */
 public function removeAsset(LineItem $asset)
 {
     if ($this->assetExists($asset)) {
         $this->assets->removeElement($asset);
     }
     return $this;
 }
Exemplo n.º 3
0
 /**
  * @param string $str
  *
  * @return \Doctrine\Common\Collections\ArrayCollection
  */
 public function search($str)
 {
     $res = new TestResult();
     $ac = new ArrayCollection();
     $ac->add($res);
     return $ac;
 }
 /**
  * Show main page.
  *
  * @EXT\Route("/choose/{id}", name="cpasimusante_choose_item", requirements={"id" = "\d+"}, options={"expose"=true})
  * @EXT\ParamConverter("itemselector", class="CPASimUSanteItemSelectorBundle:ItemSelector", options={"id" = "id"})
  * @EXT\Template("CPASimUSanteItemSelectorBundle:ItemSelector:choose.html.twig")
  *
  * @param Request      $request
  * @param ItemSelector $itemSelector
  *
  * @return array
  */
 public function chooseAction(Request $request, ItemSelector $itemSelector)
 {
     $em = $this->getDoctrine()->getManager();
     // Create an ArrayCollection of the current Item objects in the database
     $originalItems = new ArrayCollection();
     foreach ($itemSelector->getItems() as $item) {
         $originalItems->add($item);
     }
     //retrieve ItemSelector configuration for this WS
     $config = $this->getConfig($itemSelector->getResourceNode()->getWorkspace()->getId());
     $mainResourceType = $config['mainResourceType'];
     $resourceType = $config['resourceType'];
     $namePattern = $config['namePattern'];
     $form = $this->get('form.factory')->create(new ItemSelectorType($mainResourceType, $resourceType, $namePattern), $itemSelector);
     $form->handleRequest($request);
     if ($form->isValid()) {
         // remove the relationship between the item and the ItemSelector
         foreach ($originalItems as $item) {
             if (false === $itemSelector->getItems()->contains($item)) {
                 // in a a many-to-one relationship, remove the relationship
                 $item->setItemSelector(null);
                 $em->persist($item);
                 // to delete the Item entirely, you can also do that
                 $em->remove($item);
             }
         }
         $em->persist($itemSelector);
         $em->flush();
     }
     return ['_resource' => $itemSelector, 'form' => $form->createView(), 'itemCount' => $config['itemCount']];
 }
Exemplo n.º 5
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $this->em = $manager;
     $this->countries = $this->loadStructure('OroAddressBundle:Country', 'getIso2Code');
     $this->regions = $this->loadStructure('OroAddressBundle:Region', 'getCombinedCode');
     $this->organization = $manager->getRepository('OroOrganizationBundle:Organization')->getFirst();
     $this->createTransport()->createIntegration()->createChannel()->createWebSite()->createCustomerGroup()->createStore();
     $magentoAddress = $this->createMagentoAddress($this->regions['US-AZ'], $this->countries['US']);
     $account = $this->createAccount();
     $customer = $this->createCustomer(1, $account, $magentoAddress);
     $cartAddress1 = $this->createCartAddress($this->regions['US-AZ'], $this->countries['US'], 1);
     $cartAddress2 = $this->createCartAddress($this->regions['US-AZ'], $this->countries['US'], 2);
     $cartItem = $this->createCartItem();
     $status = $this->getStatus();
     $items = new ArrayCollection();
     $items->add($cartItem);
     $cart = $this->createCart($cartAddress1, $cartAddress2, $customer, $items, $status);
     $this->updateCartItem($cartItem, $cart);
     $order = $this->createOrder($cart, $customer);
     $this->setReference('customer', $customer);
     $this->setReference('integration', $this->integration);
     $this->setReference('cart', $cart);
     $this->setReference('order', $order);
     $baseOrderItem = $this->createBaseOrderItem($order);
     $order->setItems([$baseOrderItem]);
     $this->em->persist($order);
     $this->em->flush();
 }
Exemplo n.º 6
0
 /**
  * 
  * @param string $paramName
  * @return ArrayCollection
  */
 public function saveMultipleImages($paramName = 'files')
 {
     $time = new \DateTime();
     $list = new ArrayCollection();
     foreach ($_FILES[$paramName]['name'] as $i => $v) {
         $name = $_FILES[$paramName]['name'][$i];
         $name2 = strtolower($name);
         $type = $_FILES[$paramName]['type'][$i];
         $tmp = $_FILES[$paramName]['tmp_name'][$i];
         $error = $_FILES[$paramName]['error'][$i];
         $size = $_FILES[$paramName]['size'][$i];
         $md5 = md5_file($tmp);
         $image = new Image();
         $md5Check = $this->findOneBy(array('md5' => $md5));
         if (empty($md5Check)) {
             $image->setMd5($md5);
             $image->setSizeKb(floatval($size / 1024));
             $image->setKey($this->getAvailableKey());
             move_uploaded_file($tmp, realpath(PUBLIC_PATH . '/uploaded-images') . '/' . $image->getKey());
         } else {
             $image->setReferenceImage($md5Check);
         }
         $image->setName(basename($name));
         $image->setUploadedTime($time);
         $this->save($image);
         $list->add($image);
     }
     return $list;
 }
 /**
  * @inheritdoc
  */
 public function remove(User $user)
 {
     if (!$this->collection->containsKey((string) $user->getId())) {
         throw new UserNotFoundException();
     }
     return $this->collection->removeElement($user);
 }
 public function createTagCollection()
 {
     $tags = new ArrayCollection();
     $tags->add(new Tag("foo"));
     $tags->add(new Tag("bar"));
     return $tags;
 }
Exemplo n.º 9
0
 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;
 }
 /**
  * Test method for articles.
  */
 public function testTransformArticleToDocument()
 {
     $attributes = new ArrayCollection();
     $expected = [];
     /** @var Article|MockObject $mockArticle */
     $mockArticle = $this->getMockForAbstractClass('\\ONGR\\OXIDConnectorBundle\\Entity\\Article');
     for ($i = 1; $i <= 10; $i++) {
         $artToAttr = new ArticleToAttribute();
         $artToAttr->setId($i);
         $artToAttr->setPos($i);
         $artToAttr->setArticle($mockArticle);
         $attr = new Attribute();
         $attr->setPos($i + 2);
         $attr->setTitle('Some other title ' . $i);
         $artToAttr->setAttribute($attr);
         $attributes->add($artToAttr);
         $expected[] = $artToAttr;
     }
     $result = $this->service->transform($attributes);
     foreach ($result as $idx => $actual) {
         $this->assertInstanceOf('\\ONGR\\OXIDConnectorBundle\\Document\\AttributeObject', $actual);
         $this->assertEquals('Some other title ' . ($idx + 1), $actual->getTitle());
         $this->assertEquals($idx + 3, $actual->getPos());
     }
 }
Exemplo n.º 11
0
 /**
  * Edit a ContentType.
  *
  * @param Request $request
  * @param int     $id
  *
  * @return RedirectResponse|Response
  */
 public function editAction(Request $request, $id)
 {
     $contentTypeManager = $this->get('opifer.content.content_type_manager');
     $em = $this->get('doctrine.orm.entity_manager');
     /** @var ContentTypeInterface $contentType */
     $contentType = $contentTypeManager->getRepository()->find($id);
     if (!$contentType) {
         return $this->createNotFoundException();
     }
     $originalAttributes = new ArrayCollection();
     foreach ($contentType->getSchema()->getAttributes() as $attributes) {
         $originalAttributes->add($attributes);
     }
     $form = $this->createForm(ContentTypeType::class, $contentType);
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         // Remove deleted attributes
         foreach ($originalAttributes as $attribute) {
             if (false === $contentType->getSchema()->getAttributes()->contains($attribute)) {
                 $em->remove($attribute);
             }
         }
         // Add new attributes
         foreach ($form->getData()->getSchema()->getAttributes() as $attribute) {
             $attribute->setSchema($contentType->getSchema());
             foreach ($attribute->getOptions() as $option) {
                 $option->setAttribute($attribute);
             }
         }
         $contentTypeManager->save($contentType);
         $this->addFlash('success', 'Content type has been updated successfully');
         return $this->redirectToRoute('opifer_content_contenttype_edit', ['id' => $contentType->getId()]);
     }
     return $this->render($this->getParameter('opifer_content.content_type_edit_view'), ['content_type' => $contentType, 'form' => $form->createView()]);
 }
Exemplo n.º 12
0
 /**
  * Process form
  *
  * @param  CalendarEvent $entity
  *
  * @throws \LogicException
  *
  * @return bool  True on successful processing, false otherwise
  */
 public function process(CalendarEvent $entity)
 {
     $this->form->setData($entity);
     if (in_array($this->request->getMethod(), array('POST', 'PUT'))) {
         $originalChildren = new ArrayCollection();
         foreach ($entity->getChildEvents() as $childEvent) {
             $originalChildren->add($childEvent);
         }
         $this->form->submit($this->request);
         if ($this->form->isValid()) {
             $this->ensureCalendarSet($entity);
             $targetEntityClass = $this->entityRoutingHelper->getEntityClassName($this->request);
             if ($targetEntityClass) {
                 $targetEntityId = $this->entityRoutingHelper->getEntityId($this->request);
                 $targetEntity = $this->entityRoutingHelper->getEntityReference($targetEntityClass, $targetEntityId);
                 $action = $this->entityRoutingHelper->getAction($this->request);
                 if ($action === 'activity') {
                     $this->activityManager->addActivityTarget($entity, $targetEntity);
                 }
                 if ($action === 'assign' && $targetEntity instanceof User && $targetEntityId !== $this->securityFacade->getLoggedUserId()) {
                     /** @var Calendar $defaultCalendar */
                     $defaultCalendar = $this->manager->getRepository('OroCalendarBundle:Calendar')->findDefaultCalendar($targetEntity->getId(), $targetEntity->getOrganization()->getId());
                     $entity->setCalendar($defaultCalendar);
                 }
             }
             $this->onSuccess($entity, $originalChildren, $this->form->get('notifyInvitedUsers')->getData());
             return true;
         }
     }
     return false;
 }
Exemplo n.º 13
0
 static function load(Config $config)
 {
     $scenes = new ArrayCollection();
     // Start with the entry scene
     $stack = array();
     $scene = $config['entry_scene'];
     array_push($stack, $scene);
     // Loop until our stack is empty
     while (count($stack)) {
         // Load a scene from the stack
         $scenePath = array_pop($stack);
         $data = Yaml::load($config['base_directory'] . '/' . $scenePath . '.yml');
         // Create a scene from the data
         $newScene = new Scene($scenePath, $data);
         $scenes->set($scenePath, $newScene);
         // If we have exit-scenes, add them to the stack so we can load them
         foreach ($data['scene']['exit'] as $direction => $exitScene) {
             $tmp['exit'][strtolower($direction)] = $exitScene;
             // Only add to stack when we haven't already processed that scene
             if (!$scenes->containsKey($exitScene)) {
                 array_push($stack, $exitScene);
             }
         }
     }
     return $scenes;
 }
 /**
  * Test update path
  */
 public function testUpdatePath()
 {
     $siteId = $this->currentSiteManager->getCurrentSiteId();
     $parentNodeId = 'parent';
     $parentPath = 'parentPath';
     $son1NodeId = 'son1NodeId';
     $son2NodeId = 'son2NodeId';
     $parent = Phake::mock('OpenOrchestra\\ModelInterface\\Model\\NodeInterface');
     Phake::when($parent)->getNodeId()->thenReturn($parentNodeId);
     Phake::when($parent)->getPath()->thenReturn($parentPath);
     $son1 = Phake::mock('OpenOrchestra\\ModelInterface\\Model\\NodeInterface');
     Phake::when($son1)->getNodeId()->thenReturn($son1NodeId);
     $son2 = Phake::mock('OpenOrchestra\\ModelInterface\\Model\\NodeInterface');
     Phake::when($son2)->getNodeId()->thenReturn($son2NodeId);
     $son3 = Phake::mock('OpenOrchestra\\ModelInterface\\Model\\NodeInterface');
     Phake::when($son3)->getNodeId()->thenReturn($son2NodeId);
     $sons = new ArrayCollection();
     $sons->add($son1);
     $sons->add($son2);
     $sons->add($son3);
     Phake::when($this->nodeRepository)->findByParent($parentNodeId, $siteId)->thenReturn($sons);
     $event = Phake::mock('OpenOrchestra\\ModelInterface\\Event\\NodeEvent');
     Phake::when($event)->getNode()->thenReturn($parent);
     $this->subscriber->updatePath($event);
     Phake::verify($son1)->setPath($parentPath . '/' . $son1NodeId);
     Phake::verify($son2)->setPath($parentPath . '/' . $son2NodeId);
     Phake::verify($son3)->setPath($parentPath . '/' . $son2NodeId);
     Phake::verify($this->eventDispatcher, Phake::times(2))->dispatch(Phake::anyParameters());
 }
Exemplo n.º 15
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     /** @var EntityManager em */
     $em = $this->getContainer()->get('doctrine')->getManager();
     $users = $em->getRepository('ESNUserBundle:User')->findBy(array("esner" => 1));
     $concerned_users = new ArrayCollection();
     /** @var User $user */
     foreach ($users as $user) {
         /** @var EsnerFollow $follow */
         $follow = $user->getFollow();
         if ($follow) {
             $trial = $follow->getTrialstarted();
             $end_trial = $trial;
             date_add($trial, date_interval_create_from_date_string('21 days'));
             $now = new \DateTime();
             if ($end_trial->format('d/m/Y') == $now->format('d/m/Y')) {
                 $concerned_users->add($user);
             }
         }
     }
     /** @var User $concerned_user */
     foreach ($concerned_users as $concerned_user) {
         $message = \Swift_Message::newInstance()->setSubject('[ESN Lille][ERP] Periode d\'essaie terminé pour ' . $concerned_user->getFullname())->setFrom($this->getContainer()->getParameter('mailer_from'))->setTo($user->getEmail())->setBody($this->getContainer()->get('templating')->render('ESNHRBundle:Emails:trial_ended.html.twig', array('user' => $concerned_user)), 'text/html');
         $this->getContainer()->get('mailer')->send($message);
     }
 }
Exemplo n.º 16
0
 /**
  * Test entity getters & setters
  */
 public function testGettersSetters()
 {
     $entity = new User();
     $entity->setActivationKey('activation-key');
     $entity->setDisplayName('display name');
     $entity->setEmail('*****@*****.**');
     $entity->setLogin('login');
     $collection = new ArrayCollection();
     $meta1 = new UserMeta();
     $meta1->setKey('meta-key');
     $meta1->setValue('meta-value');
     $meta1->setUser($entity);
     $collection->add($entity);
     $entity->setMetas($collection);
     $entity->setNicename('nice name');
     $entity->setPass('pass');
     $date = new \DateTime();
     $entity->setRegistered($date);
     $entity->setStatus(2);
     $entity->setUrl('http://www.url.com');
     $this->assertEquals('activation-key', $entity->getActivationKey());
     $this->assertEquals('display name', $entity->getDisplayName());
     $this->assertEquals('*****@*****.**', $entity->getEmail());
     $this->assertEquals('login', $entity->getLogin());
     $this->assertEquals($collection, $entity->getMetas());
     $this->assertEquals('nice name', $entity->getNicename());
     $this->assertEquals('pass', $entity->getPass());
     $this->assertEquals($date, $entity->getRegistered());
     $this->assertEquals(2, $entity->getStatus());
     $this->assertEquals('http://www.url.com', $entity->getUrl());
 }
Exemplo n.º 17
0
 /**
  *
  * Returns an ArrayCollection containing three keys :
  *    - self::BASKETS : an ArrayCollection of the actives baskets
  *     (Non Archived)
  *    - self::STORIES : an ArrayCollection of working stories
  *    - self::VALIDATIONS : the validation people are waiting from me
  *
  * @return \Doctrine\Common\Collections\ArrayCollection
  */
 public function getContent($sort)
 {
     /* @var $repo_baskets Alchemy\Phrasea\Model\Repositories\BasketRepository */
     $repo_baskets = $this->app['repo.baskets'];
     $sort = in_array($sort, ['date', 'name']) ? $sort : 'name';
     $ret = new ArrayCollection();
     $baskets = $repo_baskets->findActiveByUser($this->app['authentication']->getUser(), $sort);
     // force creation of a default basket
     if (0 === count($baskets)) {
         $basket = new BasketEntity();
         $basket->setName($this->app->trans('Default basket'));
         $basket->setUser($this->app['authentication']->getUser());
         $this->app['EM']->persist($basket);
         $this->app['EM']->flush();
         $baskets = [$basket];
     }
     $validations = $repo_baskets->findActiveValidationByUser($this->app['authentication']->getUser(), $sort);
     /* @var $repo_stories Alchemy\Phrasea\Model\Repositories\StoryWZRepository */
     $repo_stories = $this->app['repo.story-wz'];
     $stories = $repo_stories->findByUser($this->app, $this->app['authentication']->getUser(), $sort);
     $ret->set(self::BASKETS, $baskets);
     $ret->set(self::VALIDATIONS, $validations);
     $ret->set(self::STORIES, $stories);
     return $ret;
 }
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     if (!$this->isEnabled()) {
         return;
     }
     $shippingMethods = new ArrayCollection();
     $shippingMethods->add($this->getReference('shipping_method_fedex'));
     $shippingMethods->add($this->getReference('shipping_method_ups'));
     $cod = new PaymentMethod();
     $cod->setEnabled(1);
     $cod->setHierarchy(0);
     $cod->setProcessor('cod');
     $cod->translate('en')->setName('Cash on delivery');
     $cod->setShippingMethods($shippingMethods);
     $cod->setDefaultOrderStatus($this->getReference('default_order_status'));
     $cod->mergeNewTranslations();
     $manager->persist($cod);
     $bankTransfer = new PaymentMethod();
     $bankTransfer->setEnabled(1);
     $bankTransfer->setHierarchy(0);
     $bankTransfer->setProcessor('bank_transfer');
     $bankTransfer->translate('en')->setName('Bank transfer');
     $bankTransfer->setShippingMethods($shippingMethods);
     $bankTransfer->setDefaultOrderStatus($this->getReference('default_order_status'));
     $bankTransfer->mergeNewTranslations();
     $manager->persist($bankTransfer);
     $manager->flush();
     $this->setReference('payment_method_cod', $cod);
     $this->setReference('payment_method_bank_transfer', $bankTransfer);
 }
    /**
     * Transforms choice keys into entities
     *
     * @param  mixed $keys   An array of keys, a single key or NULL
     * @return Collection|object  A collection of entities, a single entity
     *                            or NULL
     */
    public function reverseTransform($keys)
    {
        $collection = new ArrayCollection();

        if ('' === $keys || null === $keys) {
            return $collection;
        }

        if (!is_array($keys)) {
            throw new UnexpectedTypeException($keys, 'array');
        }

        $notFound = array();

        // optimize this into a SELECT WHERE IN query
        foreach ($keys as $key) {
            if ($entity = $this->choiceList->getEntity($key)) {
                $collection->add($entity);
            } else {
                $notFound[] = $key;
            }
        }

        if (count($notFound) > 0) {
            throw new TransformationFailedException(sprintf('The entities with keys "%s" could not be found', implode('", "', $notFound)));
        }

        return $collection;
    }
Exemplo n.º 20
0
 /**
  * @param Request $request
  * @param int     $id
  *
  * @return RedirectResponse|Response
  */
 public function editAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getManager();
     $template = $em->getRepository('OpiferCmsBundle:Template')->find($id);
     $form = $this->createForm(TemplateType::class, $template);
     $form->handleRequest($request);
     $originalAttributes = new ArrayCollection();
     foreach ($template->getAttributes() as $attributes) {
         $originalAttributes->add($attributes);
     }
     if ($form->isSubmitted() && $form->isValid()) {
         // Delete removed attributes
         foreach ($originalAttributes as $attribute) {
             if (false === $form->getData()->getAttributes()->contains($attribute)) {
                 $em->remove($attribute);
             }
         }
         // Add new attributes
         foreach ($form->getData()->getAttributes() as $attribute) {
             $attribute->setTemplate($template);
             foreach ($attribute->getOptions() as $option) {
                 $option->setAttribute($attribute);
             }
         }
         $em->flush();
         return $this->redirectToRoute('opifer_cms_template_edit', ['id' => $template->getId()]);
     }
     return $this->render('OpiferCmsBundle:Backend/Template:edit.html.twig', ['form' => $form->createView(), 'template' => $template]);
 }
Exemplo n.º 21
0
 public function getMenuContext($locale)
 {
     $menuData = $this->getMenuData()[$locale];
     $menu = new Menu();
     $menu->setName($menuData['name']);
     $menu->setMachineName($menuData['machineName']);
     $menu->setLocale($menuData['locale']);
     $collectionA = new ArrayCollection();
     for ($i = 1; $i <= 5; $i++) {
         $itemA = $this->newItem($menu, $i);
         $collectionB = new ArrayCollection();
         for ($j = 1; $j <= 5; $j++) {
             $itemB = $this->newItem($menu, $j, $itemA);
             $collectionB->add($itemB);
             $collectionC = new ArrayCollection();
             for ($k = 1; $k <= 5; $k++) {
                 $itemC = $this->newItem($menu, $k);
                 $collectionC->add($itemC);
             }
             $itemB->addChildren($collectionC);
         }
         $itemA->addChildren($collectionB);
         $collectionA->add($itemA);
     }
     $menu->addItems($collectionA);
     return $menu;
 }
Exemplo n.º 22
0
 public static function getTours($tours)
 {
     // Valida que existan tours
     if (count($tours) >= Generalkeys::NUMBER_ONE) {
         // Crea un array para colocar una coleccion de objetos TourTO
         $toursColeccion = new ArrayCollection();
         // Itera los tours encontrados
         foreach ($tours as $tour) {
             // Se crea un nuevo objeto para colocal la informacion de cada uno de los tours como array
             $tourTO = new TourTO();
             //Se anexa la invformacion
             $tourTO->setId($tour['id']);
             $tourTO->setNombreTour($tour['nombre']);
             $tourTO->setCircuito($tour['circuito']);
             $tourTO->setDescripcionTour(StringUtils::cutText($tour['descripcion'], Generalkeys::NUMBER_ZERO, Generalkeys::NUMBER_TWO_HUNDRED, Generalkeys::COLILLA_TEXT, Generalkeys::CIERRE_HTML_P));
             //$tourTO->setDescripcionTour($tour['descripcion']);
             $tourTO->setTarifaadulto(number_format(ceil($tour['tarifaadulto'])));
             $tourTO->setTarifamenor(number_format(ceil($tour['tarifamenor'])));
             $tourTO->setSimboloMoneda($tour['simbolomoneda']);
             // Valida imagen tour si es null coloca imagen not found de lo contrario coloca la imagen
             if (is_null($tour['imagen'])) {
                 $tourTO->setPrincipalImage(Generalkeys::PATH_IMAGE_NOT_FOUND);
             } else {
                 $tourTO->setPrincipalImage($tour['imagen']);
             }
             //Se agrega el objeto a la coleccion
             $toursColeccion->add($tourTO);
         }
         return $toursColeccion;
     }
 }
Exemplo n.º 23
0
 public function jobsAction(Request $request)
 {
     $user = $this->getUser();
     $em = $this->getDoctrine()->getManager();
     if (null === $user) {
         return $this->redirect($this->generateUrl('mainpage'));
     }
     $originalJobs = new ArrayCollection();
     foreach ($user->getJobs() as $job) {
         $originalJobs->add($job);
     }
     $form = $this->createForm(new JobsCollectionType(), $user);
     $form->handleRequest($request);
     if ($form->isValid()) {
         $newJobs = $user->getJobs();
         foreach ($originalJobs as $oldJob) {
             if (!$newJobs->contains($oldJob)) {
                 $newJobs->removeElement($oldJob);
                 $em->remove($oldJob);
             }
         }
         foreach ($newJobs as $actualJob) {
             $actualJob->setUser($user);
         }
         $em->flush();
     }
     return $this->render('NetworkWebBundle:User:profile_jobs.html.twig', ['form' => $form->createView()]);
 }
Exemplo n.º 24
0
 /**
  * 
  * Done
  * @return ViewModel
  */
 public function createAction()
 {
     $request = $this->getRequest();
     $entityManager = $this->getEntityManager();
     $roles = $entityManager->getRepository('Authorization\\Entity\\Role')->findAll();
     $formRoles = [];
     foreach ($roles as $role) {
         $formRoles[$role->getRoleId()] = $role->getRoleName();
     }
     $roleForm = new RoleForm($formRoles);
     if ($request->isPost()) {
         $data = $request->getPost();
         $roleForm->setInputFilter(new RoleFilter());
         $roleForm->setData($data);
         if ($roleForm->isValid()) {
             $data = $roleForm->getData();
             $role = new EntityRole();
             $role->setRoleName($data['role_name']);
             $parents = new ArrayCollection();
             foreach ($data['role_parent'] as $parentRoleId) {
                 $parents->add($entityManager->getReference('Authorization\\Entity\\Role', $parentRoleId));
             }
             $role->addParents($parents);
             try {
                 $entityManager->persist($role);
                 $entityManager->flush();
                 $this->redirect()->toRoute('authorization/role', array('action' => 'index'));
             } catch (Exception $ex) {
                 return new ViewModel(array('message' => $ex->getCode() . ': ' . $ex->getMessage()));
             }
         }
     }
     return new ViewModel(array('roleForm' => $roleForm));
 }
 /**
  * @param  Event   $event
  * @return Entry[]
  *
  * @throws Exception\RuntimeException
  * @throws Zend\Di\Exception\ClassNotFoundException
  */
 public function process(Event $event)
 {
     $entries = new ArrayCollection();
     $eventRange = new DateRange($event->start, $event->end);
     if ($eventRange->isEmpty()) {
         return $entries;
     }
     $rule = $event->rule;
     if ($rule === null) {
         throw new Exception\RuntimeException(sprintf('The event %s has no associated rule.', $event->id));
     }
     $config = $this->getMatchingConfiguration($rule, $eventRange->getStart());
     if ($config->end < $eventRange->getEnd()) {
         throw new Exception\RuntimeException(sprintf('The rule configuration %s from %s to %s does not' . ' cover the desired range %s to %s.', $config->id, $config->start->format('Y-m-d'), $config->end->format('Y-m-d'), $eventRange->getStart()->format('Y-m-d'), $eventRange->getEnd()->format('Y-m-d')));
     }
     $strategy = $this->di->get($config->strategy);
     if (!$strategy instanceof StrategyInterface) {
         throw new Exception\RuntimeException(sprintf('The class %s does not implement %s.', get_class($strategy), 'Tillikum\\Billing\\Event\\Strategy\\StrategyInterface'));
     }
     $strategyEntries = $strategy->process($event, $config);
     foreach ($strategyEntries as $entry) {
         if ($event->is_credit) {
             $entry->amount *= -1;
         }
         $entries->add($entry);
     }
     return $entries;
 }
 public function getCategoryPath(CategoryInterface $category) : array
 {
     $collection = new ArrayCollection();
     $collection->add($category);
     $this->addCategoryParent($category->getParent(), $collection);
     return array_reverse($collection->toArray());
 }
 /**
  * If the event isn't already in the list, add it
  * 
  * @param CalendarEventInterface $event
  * @return CalendarEvent $this
  */
 public function addEvent(CalendarEventInterface $event)
 {
     if (!$this->events->contains($event)) {
         $this->events->add($event);
     }
     return $this;
 }
 public function testBind01()
 {
     $expectedJSON = file_get_contents(dirname(__DIR__) . '/../../Resources/json/client_aftership_couriers_response_handler_01.json');
     $this->response->expects($this->once())->method('getStatusCode')->will($this->returnValue(200));
     $this->response->expects($this->once())->method('getContent')->will($this->returnValue($expectedJSON));
     $this->responseHandler->bind($this->response, $this->collection);
     $this->assertEquals(26, $this->collection->count());
     $courier0 = $this->collection[0];
     $this->assertEquals('USPS', $courier0->getName());
     $this->assertEquals('United States Postal Service', $courier0->getOtherName());
     $this->assertEquals('+1 800-275-8777', $courier0->getPhone());
     $this->assertEquals(['USA'], $courier0->getServiceCountries());
     $this->assertEquals('usps', $courier0->getSlug());
     $this->assertEquals(['en'], $courier0->getSupportLanguages());
     $this->assertNotNull($courier0->getUpdatedAt());
     $this->assertEquals("https://www.usps.com", $courier0->getUrl());
     $courier13 = $this->collection[13];
     $this->assertEquals('Hong Kong Post', $courier13->getName());
     $this->assertEquals('香港郵政', $courier13->getOtherName());
     $this->assertEquals('+852 2921 2222', $courier13->getPhone());
     $this->assertEquals(['HKG'], $courier13->getServiceCountries());
     $this->assertEquals('hong-kong-post', $courier13->getSlug());
     $this->assertEquals(['en'], $courier13->getSupportLanguages());
     $this->assertNotNull($courier13->getUpdatedAt());
     $this->assertEquals("http://hongkongpost.com", $courier13->getUrl());
 }
Exemplo n.º 29
0
 /**
  * @param Request $request
  * @param integer $id
  *
  * @Route("/blog/{id}/update", name="cms.blog.update")
  * @Template("AceCmsBundle:Blog:create-update.html.twig")
  *
  * @return array
  */
 public function indexAction(Request $request, $id)
 {
     /** @var Blog $blog */
     $blog = $this->blogRepository->find($id);
     if (!$blog) {
         $this->session->getFlashBag()->add('error', 'Item was not found');
         return $this->redirectToRoute('cms.blog.list');
     }
     $originalEvents = new ArrayCollection();
     foreach ($blog->getEvents() as $event) {
         $originalEvents->add($event);
     }
     $user = $this->getUser();
     $form = $this->formFactory->create(new BlogType(), $blog, ['add_submit_buttons' => true]);
     $form->handleRequest($request);
     if ($form->isSubmitted()) {
         if ($form->isValid()) {
             $blog->addNotExistedEvents();
             $blog->removeNotExistedEvents($originalEvents);
             $blog->setUpdatedBy($user);
             $this->blogRepository->save([$blog], true);
             $this->session->getFlashBag()->add('success', 'Item was successfully saved');
         } else {
             $this->session->getFlashBag()->add('error', 'The form has some error(s).');
         }
     }
     return ['form' => $form->createView()];
 }
Exemplo n.º 30
0
 /**
  * @param RoleInterface $role
  *
  * @return $this
  */
 public function addRole(RoleInterface $role)
 {
     if (false === $this->hasRole($role)) {
         $this->roles->add($role);
     }
     return $this;
 }