function it_sets_up_dependencies_if_class_does_contains_dependencies_method(Container $container) { $container->get(InjectableCompilerPass::INJECTABLES_SERVICE_ID)->willReturn($this->referenceToControllerWithDependenciesMethod); $class = new Acme_Catalog2_IndexController(); $container->get('acme.product.catalog')->shouldBeCalled(); $this->setupDependencies($class); }
/** * Execute the next task on the queue * * @param string $queue * @param int $timeout * @throws \Exception * @throws \mcfedr\Queue\JobManagerBundle\Exception\UnrecoverableException * @throws \mcfedr\Queue\JobManagerBundle\Exception\ExecuteException */ public function execute($queue = null, $timeout = null) { $job = $this->manager->get($queue, $timeout); if (!$job) { return; } $task = json_decode($job->getData(), true); $this->logger->info('Got task', ['task' => $task['name'], 'options' => $task['options']]); try { /** @var Worker $worker */ $worker = $this->container->get($task['name']); foreach ($this->preListeners as $listener) { $listener->preTask($worker, $task['options']); } $worker->execute($task['options']); foreach ($this->postListeners as $listener) { $listener->postTask($worker, $task['options']); } $this->manager->delete($job); } catch (ServiceNotFoundException $e) { $this->manager->delete($job); $throw = new UnrecoverableException("Service for job not found", 0, $e); $throw->setJob($job); throw $throw; } catch (UnrecoverableException $e) { $this->manager->delete($job); $e->setJob($job); throw $e; } catch (\Exception $e) { throw new ExecuteException($job, $e); } }
public function let(Container $container, Translator $translator, Session $session, TopicRepository $topicRepository, EntityRepository $repository, EntityManager $entityManager, Request $request, FormFactory $formFactory, FormBuilder $formBuilder, Form $form, FormView $formView, Topic $topic, CsrfTokenManagerAdapter $csrfTokenManagerAdapter, AbstractQuery $query, AbstractQuery $query2, ParameterBag $parameterBag, ArticleTopicRepository $articleTopicrepository, UserService $userService, User $user, TopicService $topicService, Article $article, QueryBuilder $queryBuilder, CacheService $cacheService, EventDispatcher $dispatcher) { $container->get('em')->willReturn($entityManager); $container->get('session')->willReturn($session); $container->get('request')->willReturn($request); $container->get('translator')->willReturn($translator); $container->get('form.factory')->willReturn($formFactory); $container->get('form.csrf_provider')->willReturn($csrfTokenManagerAdapter); $container->get('newscoop.cache')->willReturn($cacheService); $container->get('user')->willReturn($userService); $container->get('dispatcher')->willReturn($dispatcher); $userService->getCurrentUser()->willReturn($user); $container->get('newscoop_newscoop.topic_service')->willReturn($topicService); $formBuilder->getForm(Argument::cetera())->willReturn($form); $formFactory->create(Argument::cetera())->willReturn($form); $form->createView()->willReturn($formView); $form->handleRequest(Argument::cetera())->willReturn(true); $form->isValid()->willReturn(true); $entityManager->persist(Argument::any())->willReturn(true); $entityManager->flush(Argument::any())->willReturn(true); $entityManager->remove(Argument::any())->willReturn(true); $entityManager->getRepository('Newscoop\\NewscoopBundle\\Entity\\Topic')->willReturn($repository); $entityManager->getRepository('Newscoop\\Entity\\ArticleTopic')->willReturn($articleTopicrepository); $this->setContainer($container); $this->token = 'uTxRiEkont4XxRpTcSADPCowge7TgNONE7Y5HWd4pmY'; $request->get('_csrf_token')->willReturn($this->token); $request->get('_code')->willReturn('en'); $request->get('_articleNumber')->willReturn('64'); $request->getLocale()->willReturn('en'); $request->get('_code', 'en')->willReturn('en'); $request->request = $parameterBag; }
private function doFilter(AssetInterface $asset) { $content = $asset->getContent(); $callback = function ($matches) { $fs = new Filesystem(); $resource = $matches['resource']; preg_match("/(\\@{1,2})([A-Z][A-Za-z0-9\\_\\-]*)/", $resource, $matches); if ($resource[1] == "@") { $resource = substr($resource, 1); } try { $bundle = $this->container->get('kernel')->getBundle($matches[2]); $path = $this->container->get('kernel')->locateResource($resource); if ($fs->exists($path)) { if (preg_match("/Resources\\/public\\/(.*)/", $path, $matches2)) { $path = 'bundles/' . preg_replace('/bundle$/', '', strtolower($bundle->getName())) . '/' . $matches2[1]; if ($matches[1] == "@@") { return $this->container->get('kernel')->getRootDir() . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'web' . DIRECTORY_SEPARATOR . $path; } try { return $this->container->get('templating.helper.assets')->getUrl($path); } catch (InactiveScopeException $e) { return "../" . $path; } } } } catch (Exception $e) { } return $resource; }; $pattern = "/(?P<resource>\\@{1,2}[A-Za-z\\_]+Bundle[A-Za-z0-9\\_\\.\\/\\-]*)/"; $asset->setContent(preg_replace_callback($pattern, $callback, $content)); }
public function warmUp($cacheDir) { // we need the directory no matter the hydrator cache generation strategy. $hydratorCacheDir = $this->container->getParameter('doctrine.odm.mongodb.hydrator_dir'); if (!file_exists($hydratorCacheDir)) { if (false === @mkdir($hydratorCacheDir, 0777, true)) { throw new \RuntimeException(sprintf('Unable to create the Doctrine Hydrator directory (%s)', dirname($hydratorCacheDir))); } } else { if (!is_writable($hydratorCacheDir)) { throw new \RuntimeException(sprintf('Doctrine Hydrator directory (%s) is not writeable for the current system user.', $hydratorCacheDir)); } } // if hydrators are autogenerated we don't need to generate them in the cache warmer. if ($this->container->getParameter('doctrine.odm.mongodb.auto_generate_hydrator_classes') === true) { return; } $documentManagers = $this->container->getParameter('doctrine.odm.mongodb.document_managers'); foreach ($documentManagers as $documentManagerName) { $dm = $this->container->get(sprintf('doctrine.odm.mongodb.%s_document_manager', $documentManagerName)); /* @var $dm Doctrine\ODM\MongoDB\DocumentManager */ $classes = $dm->getMetadataFactory()->getAllMetadata(); $dm->getHydratorFactory()->generateHydratorClasses($classes); } }
/** * Sets the signal handlers that we use during execution */ private function setSignalHandlers() { $this->container->get('logger')->debug('Setting signal handlers'); pcntl_signal(SIGTERM, [$this, 'signalHandler']); pcntl_signal(SIGINT, [$this, 'signalHandler']); pcntl_signal(SIGHUP, [$this, 'signalHandler']); }
/** * @dataProvider getDebugModes */ public function testToolbarConfig($enabled) { $extension = new WebProfilerExtension(); $extension->load(array(array('toolbar' => $enabled)), $this->container); $this->assertSame($enabled, $this->container->get('web_profiler.debug_toolbar')->isEnabled()); $this->assertSaneContainer($this->getDumpedContainer()); }
public function __construct(Container $container) { $this->container = $container; $this->request = $container->get('request'); $this->em = $container->get('doctrine')->getManager(); $this->user = $container->get('security.context')->getToken()->getUser(); }
/** * @DI\Observe("kernel.view", priority = 255) */ public function onKernelView(GetResponseEvent $event) { $responseData = $event->getControllerResult(); if ($responseData instanceof Response) { return; } $response = new JsonResponse($responseData); $securityContext = $this->container->get('security.context'); $token = $securityContext->getToken(); $userId = $token->getUsername(); if ($userId != 'anon.') { if (in_array('ROLE_ADMIN', array_map(function ($role) { return $role->getRole(); }, $token->getRoles()))) { $access = self::ACCESS_ADMIN; } else { if (array_key_exists('ownerId', $responseData) && $responseData['ownerId'] == $userId) { $response->headers->set('owner-id', $responseData['ownerId']); $access = self::ACCESS_AUTHOR; } else { $access = self::ACCESS_READER; } } } else { $access = self::ACCESS_ANONYMOUS; } $roles = ""; foreach ($token->getRoles() as $role) { $roles = $roles . ", " . $role->getRole(); } $response->headers->set('user-id', $userId); $response->headers->set('roles', $roles); $response->headers->set(self::ACCESS_HEADER_NAME, $access); $event->setResponse($response); }
public static function getSearchManager(Container $container = null, $vertical) { if ($vertical != '') { return $container->get('rmc_' . $vertical . '.search_manager'); } return $container->get('rmc_core.ad_search_manager'); }
public function let(ArticleService $articleService, AuthorService $authorService, CacheService $cacheService, Container $container, ArticleRepository $articleRepository, LanguageRepository $languageRepository, ArticleTypeRepository $articleTypeRepository, PublicationRepository $publicationRepository, IssueRepository $issueRepository, SectionRepository $sectionRepository, AuthorTypeRepository $authorTypeRepository, EntityManager $entityManager, Request $request, FormFactory $formFactory, FormBuilder $formBuilder, Form $form, FormView $formView, User $user, UserService $userService, Article $article, Publication $publication, ArticleType $articleType, Issue $issue, Section $section, Language $language, Author $author, AuthorType $authorType, AbstractQuery $query, SecurityContext $security, TokenStorage $tokenStorage, TokenInterface $token, Router $router) { $container->get('em')->willReturn($entityManager); $container->get('request')->willReturn($request); $container->get('user')->willReturn($userService); $container->get('form.factory')->willReturn($formFactory); $container->get('newscoop_newscoop.article_service')->willReturn($articleService); $container->get('author')->willReturn($authorService); $container->get('newscoop.cache')->willReturn($cacheService); $container->get('router')->willReturn($router); $formBuilder->getForm(Argument::cetera())->willReturn($form); $formFactory->create(Argument::cetera())->willReturn($form); $form->createView()->willReturn($formView); $form->handleRequest(Argument::cetera())->willReturn(true); $form->isValid()->willReturn(true); $security->getToken()->willReturn($token); $container->get('security.context')->willReturn($security); $container->has('security.context')->willReturn(true); $container->has('security.token_storage')->willReturn(true); $container->get('security.token_storage')->willReturn($tokenStorage); $this->setContainer($container); $entityManager->getRepository('Newscoop\\Entity\\Article')->willReturn($articleRepository); $entityManager->getRepository('Newscoop\\Entity\\Language')->willReturn($languageRepository); $entityManager->getRepository('Newscoop\\Entity\\ArticleType')->willReturn($articleTypeRepository); $entityManager->getRepository('Newscoop\\Entity\\Publication')->willReturn($publicationRepository); $entityManager->getRepository('Newscoop\\Entity\\Issue')->willReturn($issueRepository); $entityManager->getRepository('Newscoop\\Entity\\Section')->willReturn($sectionRepository); $entityManager->getRepository('Newscoop\\Entity\\AuthorType')->willReturn($authorTypeRepository); $articleRepository->getArticle(Argument::cetera())->willReturn($query); $entityManager->flush(Argument::any())->willReturn(true); $userService->getCurrentUser()->willReturn($user); $number = 64; $language = "en"; }
/** * Перед удаление альбома, удаляем все фотограффии, находящиеся в нем, * и уменьшаем у всех последующих альбомов sortIndex на 10 * * @param LifecycleEventArgs $args */ public function preRemove(LifecycleEventArgs $args) { $entity = $args->getEntity(); $em = $args->getEntityManager(); if ($entity instanceof \PhotoBundle\Entity\Album) { $photos = $entity->getPhotos(); foreach ($photos as $photo) { $em->remove($photo); } $sortIndex = $entity->getSortIndex(); $albums = $em->getRepository('PhotoBundle:Album')->getAlbumsWithMoreSortIndex($sortIndex); foreach ($albums as $album) { $currentSortIndex = $album->getSortIndex(); $album->setSortIndex($currentSortIndex - 10); } } elseif ($entity instanceof Photo) { $name = $entity->getName(); $pathToImageDirectory = $this->_container->get('request')->server->get('DOCUMENT_ROOT') . '/uploaded/images'; $paths = array($pathToImageDirectory . '/800x800/', $pathToImageDirectory . '/200x200/'); foreach ($paths as $path) { $fullName = $path . $name; if (file_exists($fullName)) { unlink($fullName); } } } }
public function getSite() { if ($this->site === null) { $host = $this->container->get('request')->getHost(); $cleanHost = $this->removeUrlPattern($host); $sites = $this->em->getRepository('SymbbCoreSiteBundle:Site')->findBy(array()); foreach ($sites as $site) { $domains = $site->getDomainArray(); foreach ($domains as $domain) { if ($this->removeUrlPattern($domain) == $cleanHost) { $this->site = $site; return $this->site; } } } if ($this->site === null) { if (!empty($sites)) { $this->site = reset($sites); } else { $this->site = new \Symbb\Core\SiteBundle\Entity\Site(); } } } return $this->site; }
/** * @param Event $event * @param User $user * * @return Ticket */ public function createTicket($event, $user) { // @todo це ще треба передивитись і поправити $em = $this->container->get('doctrine.orm.default_entity_manager'); // Вытягиваем скидку из конфига $paymentsConfig = $this->container->getParameter('stfalcon_event.config'); $discount = (double) $paymentsConfig['discount']; $ticket = new Ticket(); $ticket->setEvent($event); $ticket->setUser($user); $ticket->setAmountWithoutDiscount($event->getCost()); $paidPayments = $em->getRepository('StfalconEventBundle:Payment')->findPaidPaymentsForUser($user); // если пользователь имеет оплаченные события, // то он получает скидку (если для события разрешена такая скидка) if (count($paidPayments) > 0 && $event->getUseDiscounts()) { $cost = $event->getCost() - $event->getCost() * $discount; $hasDiscount = true; } else { $cost = $event->getCost(); $hasDiscount = false; } $ticket->setAmount($cost); $ticket->setHasDiscount($hasDiscount); $em->persist($ticket); $em->flush(); return $ticket; }
public function dump(AssetInterface $asset) { $writer = new \Assetic\AssetWriter(sys_get_temp_dir(), $this->container->getParameter('assetic.variables')); $ref = new \ReflectionMethod($writer, 'getCombinations'); $ref->setAccessible(true); $name = $asset->getSourcePath(); $type = substr($name, strrpos($name, '.') + 1); switch ($type) { case 'coffee': $asset->ensureFilter($this->container->get('assetic.filter.coffee')); $type = 'js'; break; case 'less': $asset->ensureFilter($this->container->get('assetic.filter.less')); $type = 'css'; break; } $combinations = $ref->invoke($writer, $asset->getVars()); $asset->setValues($combinations[0]); $asset->load(); $content = $asset->getContent(); // because the assetic cssrewrite makes bullshit here, we need to reimplement the filter if ($type === 'css') { $content = $this->cssFilter($content, '/' . dirname($asset->getSourcePath())); } return $content; }
/** * Collects data for the given Request and Response. * * @param Request $request A Request instance * @param Response $response A Response instance * @param \Exception $exception An Exception instance * * @api */ public function collect(Request $request, Response $response, \Exception $exception = null) { $messages = array(); $content = $response->getContent(); $path = ''; $fileContent = ''; $template = $request->attributes->get('_template'); if (is_null($template)) { $templateName = $request->attributes->get('template'); list($front, $format, $engine) = explode('.', $templateName); $templateParts = explode(":", $front); $template = new TemplateReference($templateParts[0], $templateParts[1], $templateParts[2], $format, $engine); } if ($template instanceof TemplateReference) { $locale = $request->attributes->get('_locale', $request->getLocale()); $catalogue = new MessageCatalogue($locale); $path = $template->getPath(); /** * Check if $path is a resource */ if (strstr($path, '@')) { $kernel = $this->container->get('kernel'); $path = $kernel->locateResource($path); $fileContent = file_get_contents($path); } $this->twigExtractor->extractTemplate($path, $catalogue); $messages = $catalogue->all(); } $this->data = array('content' => $content, 'file_content' => $fileContent, 'messages' => $messages, 'path' => $path); }
/** * @param EntityManager $entityManager */ public function __construct(EntityManager $entityManager, Container $container) { $this->em = $entityManager; $this->qb = $entityManager->createQueryBuilder(); $this->mailer = $container->get('mailer'); $this->templating = $container->get('templating'); }
protected function getRole($entityData) { $rolename = $entityData->Role; $em = $this->container->get('doctrine.orm.default_entity_manager'); $repo = $em->getRepository('UserBundle:Role'); $entityData->Role = $repo->findOneBy(array('role' => $rolename)); }
public function execute(InputInterface $input, OutputInterface $output) { $this->container = $this->getContainer(); $this->assetic = $this->container->get('assetic.asset_manager'); $files = array(); foreach ($this->assetic->getNames() as $name) { $asset = $this->assetic->get($name); $group = array(); foreach ($asset as $assetPart) { $absPath = realpath($assetPart->getSourceRoot() . '/' . $assetPart->getSourcePath()); if ($absPath === false) { continue; } $group[] = $assetPart->getTargetPath(); $files[$assetPart->getTargetPath()] = $absPath; } $files[$asset->getTargetPath()] = $group; } switch ($input->getArgument('format')) { case 'json': $output->write(json_encode($files)); break; default: $output->write(var_export($files, true)); break; } }
public function warmUp($cacheDir) { // we need the directory no matter the proxy cache generation strategy. $proxyCacheDir = $this->container->getParameter('doctrine.orm.proxy_dir'); if (!file_exists($proxyCacheDir)) { if (false === @mkdir($proxyCacheDir, 0777, true)) { throw new \RuntimeException(sprintf('Unable to create the Doctrine Proxy directory (%s)', dirname($proxyCacheDir))); } } else { if (!is_writable($proxyCacheDir)) { throw new \RuntimeException(sprintf('Doctrine Proxy directory (%s) is not writeable for the current system user.', $proxyCacheDir)); } } // if proxys are autogenerated we don't need to generate them in the cache warmer. if ($this->container->getParameter('doctrine.orm.auto_generate_proxy_classes') === true) { return; } $entityManagers = $this->container->getParameter('doctrine.orm.entity_managers'); foreach ($entityManagers as $entityManagerName) { $em = $this->container->get(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName)); /* @var $em Doctrine\ORM\EntityManager */ $classes = $em->getMetadataFactory()->getAllMetadata(); $em->getProxyFactory()->generateProxyClasses($classes); } }
/** * FormFactory constructor. * @param Container $container */ public function __construct(Container $container) { # configuring the form factory $this->formFactory = Forms::createFormFactoryBuilder()->addExtension(new DoctrineOrmExtension(new ExtendedEntityManager($container->get('models'))))->addExtension(new ValidatorExtension(Validation::createValidator()))->getFormFactory(); # registering all necessary smarty plugins new SmartyPlugins($this->getFormHelper(), $container->get('template')); }
/** * Creates the QR code URL corresponding to the given message. * * @param $text * @param int $size * @param int $padding * @param string $extension * @param string $errorCorrectionLevel * @param array $foregroundColor * @param array $backgroundColor * @param string $label * @param string $labelFontSize * @param string $labelFontPath * * @return mixed */ public function qrcodeUrlFunction($text, $size = null, $padding = null, $extension = null, $errorCorrectionLevel = null, array $foregroundColor = null, array $backgroundColor = null, $label = null, $labelFontSize = null, $labelFontPath = null) { $params = array('text' => $text); if ($size !== null) { $params['size'] = $size; } if ($padding !== null) { $params['padding'] = $padding; } if ($extension !== null) { $params['extension'] = $extension; } if ($errorCorrectionLevel !== null) { $params['error_correction_level'] = $errorCorrectionLevel; } if ($foregroundColor !== null) { $params['foreground_color'] = $foregroundColor; } if ($backgroundColor !== null) { $params['background_color'] = $backgroundColor; } if ($label !== null) { $params['label'] = $label; } if ($labelFontSize !== null) { $params['label_font_size'] = $labelFontSize; } if ($labelFontPath !== null) { $params['label_font_path'] = $labelFontPath; } return $this->container->get('router')->generate('endroid_qrcode', $params, true); }
public function __invoke() { $token = $this->container->get('security.context')->getToken(); if (null !== $token) { return $token->getUser(); } }
/** * Renders jwplayer * * @param MediaInterface $media * @param array $options * * @return string */ public function renderMedia(MediaInterface $media, array $options = array()) { $defaultOptions = $this->container->getParameter('thrace_media.jwplayer.options'); $configs = array('key' => $defaultOptions['key'], 'html5player' => $defaultOptions['html5player'], 'flashplayer' => $defaultOptions['flashplayer'], 'type' => $media->getType(), 'id' => uniqid('thrace_media', true), 'file' => $this->container->get('router')->generate('thrace_media_render', array('name' => $media->getMediaPath(), 'hash' => $media->getHash()), true)); $configs = array_replace_recursive($configs, $options); return $this->container->get('templating')->render('ThraceMediaBundle:Media:media.html.twig', array('media' => $media, 'configs' => $configs)); }
public static function createProvider(Container $container) { $annotationsEnabled = $container->getParameter('rezonant.mapper.providers.annotations.enabled'); $configEnabled = $container->getParameter('rezonant.mapper.providers.config.enabled'); $cacheEnabled = $container->getParameter('rezonant.mapper.cache.enabled'); $cacheStrategy = $container->getParameter('rezonant.mapper.cache.strategy'); //$maps = $container->getParameter('rezonant.mapper.maps'); $providers = array(); if ($annotationsEnabled) { $providers[] = $container->get('rezonant.mapper.annotation_map_provider'); } if ($configEnabled) { $configMapProvider = $container->get('rezonant.mapper.config_map_provider'); //$configMapProvider->setMaps($maps); $providers[] = $configMapProvider; } $provider = new MapProviderModerator($providers); if ($cacheEnabled) { if (!class_exists($cacheStrategy, true)) { throw new InvalidConfigurationException("No such strategy class {$cacheStrategy}"); } $provider = new CacheProvider($provider, new $cacheStrategy()); } return $provider; }
/** * postLoad Callback for Page entity, gets all defined PageHooks and calls it * @param Page $page * @param LifecycleEventArgs $args */ public function postLoad(Page $page, LifecycleEventArgs $args) { $hookManager = $this->container->get('mm_cmf_content.page_hook_manager'); foreach ($hookManager->getHooks() as $hook) { $hook->process($page, $this->container->get('request')); } }
/** * Get an EntityManager * @return EntityManager */ public function getEntityManager() { if ($this->em === null) { $this->setEntityManager($this->container->get('doctrine')->getManager($this->emName)); } return $this->em; }
/** * Get entity for storage users * * @return \Doctrine\ORM\EntityRepository|null */ public function getRepository() { if ($this->entity) { return $this->container->get('doctrine.orm.entity_manager')->getRepository($this->entity); } return null; }
/** * @param $crudServiceName * @param CrudController $controller * @throws ConfigException */ private function registerCrudInController($crudServiceName, CrudController $controller) { if (!($crud = $this->container->get($crudServiceName))) { throw new ConfigException(sprintf('Crud service with name %s not found in service container.', $crudServiceName)); } $controller->initAsCrudController($crud); }
public function testOnTournamentFinish() { $event = new TournamentContainer(); $tournament = $this->container->get("core.handler.tournament")->getRepository()->find(2163); $event->setTournament($tournament); $this->service->onTournamentFinish($event); }