/** * {@inheritDoc} */ public function process(ContainerBuilder $container) { if ('test' === $this->kernel->getEnvironment()) { $definition = $container->getDefinition('translator.default'); $definition->setClass('Braincrafted\\Bundle\\TestingBundle\\Translator\\NoTranslator'); } }
/** * Constructor * * @access public * @param \Symfony\Component\HttpKernel\KernelInterface $kernel */ public function __construct(KernelInterface $kernel = null) { $this->bundles = new \SplObjectStorage(); if ($kernel instanceof KernelInterface) { $this->setBundles($kernel->getBundles()); } }
public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; parent::__construct("Thelia", Thelia::THELIA_VERSION); $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment())); $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.')); }
/** * Get a manipulable image instance. * * @param string $file the image path * * @return ImageHandler a manipulable image instance */ public function open($file) { if (strlen($file) >= 1 && $file[0] == '@') { $file = $this->fileLocator instanceof FileLocatorInterface ? $this->fileLocator->locate($file) : $this->fileLocator->locateResource($file); } return $this->createInstance($file); }
/** * @param PreMigrationEvent $event */ public function onPreUp(PreMigrationEvent $event) { if ($event->isTableExist(CreateMigrationTableMigration::MIGRATION_TABLE)) { $data = $event->getData(sprintf('select * from %s where id in (select max(id) from %s group by bundle)', CreateMigrationTableMigration::MIGRATION_TABLE, CreateMigrationTableMigration::MIGRATION_TABLE)); foreach ($data as $val) { $event->setLoadedVersion($val['bundle'], $val['version']); } } else { $event->addMigration(new CreateMigrationTableMigration()); // load MigrationTable initial data for BAP and OroCRM bundles installed before migrations is introduced // @todo: this transient solution can be removed in a future // when we ensure RC1 and RC2 are updated for all clients if ($event->isTableExist('oro_installer_bundle_version')) { $oroTableDataConfig = $this->kernel->locateResource('@OroMigrationBundle/EventListener/MigrationTableData/Oro.yml'); $bundleVersions = Yaml::parse(realpath($oroTableDataConfig)); $oroCrmTableDataConfig = $this->kernel->locateResource('@OroMigrationBundle/EventListener/MigrationTableData/OroCRM.yml'); if ($event->isTableExist('orocrm_account')) { $bundleVersions = array_merge($bundleVersions, Yaml::parse(realpath($oroCrmTableDataConfig))); } foreach ($bundleVersions as $bundleName => $version) { $event->setLoadedVersion($bundleName, $version); } $event->addMigration(new UpdateBundleVersionMigration($bundleVersions)); $event->addMigration(new UpdateEntityConfigMigration()); } } }
/** * @Given the system should have the following uniquenesses: */ public function theSystemShouldHaveTheFollowingUniquenesses(PyStringNode $body) { /** @var CollectUniquenessTestWorker $collectUniquenessTestWorker */ $collectUniquenessTestWorker = $this->kernel->getContainer()->get('cubalider.unique.collect_uniqueness_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectUniquenessTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Cubalider\\Uniqueness'); }
public function convert($cacheDir) { $fs = new Filesystem(); $targetDir = $cacheDir . '/js_entities'; $webDir = $this->kernel->getRootDir() . '/../web/js'; $fs->mkdir($targetDir); $fs->mkdir($webDir); $namespaces = []; $metas = $this->entityManager->getMetadataFactory()->getAllMetadata(); foreach ($metas as $metadata) { $meta = $this->convertMetadata($metadata); $directory = $targetDir . '/' . $meta->namespace; $fs->mkdir($directory); $meta->filename = $directory . '/' . $meta->functionName . '.js'; $this->generator->generateEntity($meta); if (!isset($namespaces[$meta->namespace])) { $namespaces[$meta->namespace] = array(); } $namespaces[$meta->namespace][] = $meta; } foreach ($namespaces as $namespace => $metas) { $targetFile = $targetDir . '/' . $namespace . '.js'; $webFile = $webDir . '/' . $namespace . '.js'; $this->generator->generateNamespace($namespace, $metas, $targetFile); $fs->copy($targetFile, $webFile); } }
/** * Constructor. * * @param KernelInterface $kernel A KernelInterface instance */ public function __construct(KernelInterface $kernel) { $this->kernel = $kernel; parent::__construct('Symfony', Kernel::VERSION . ' - ' . $kernel->getName() . '/' . $kernel->getEnvironment() . ($kernel->isDebug() ? '/debug' : '')); $this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment())); $this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.')); }
/** * Constructor * * @param KernelInterface $kernel */ public function __construct(KernelInterface $kernel) { // register email address proxy class loader $loader = new UniversalClassLoader(); $loader->registerNamespaces([self::ENTITY_PROXY_NAMESPACE => $kernel->getCacheDir() . DIRECTORY_SEPARATOR . self::CACHED_ENTITIES_DIR_NAME]); $loader->register(); }
public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); $routes = $this->router->getRouteCollection(); $route = $routes->get($request->attributes->get('_route')); if (!$route->getOption('requires_license')) { return; } if ('active' != $request->get('lic') && $this->kernel->getEnvironment() == 'prod') { // Checking for whitelisted users try { $user = $this->tokenStorage->getToken()->getUser(); $today = date('Y-m-d'); if ($user instanceof UserInterface) { $whitelist = $this->kernel->getContainer()->getParameter('license_whitelist'); foreach ($whitelist as $allowed) { if ($allowed['client_key'] == $user->getClientKey() && $today <= $allowed['valid_till']) { return; } } } } catch (\Exception $e) { // Do nothing } $url = $this->router->generate('atlassian_connect_unlicensed'); $response = new RedirectResponse($url); $event->setResponse($response); } }
/** * Imports units. * * @return array An array with the keys "skipped" and "imported" which contain the number of units skipped and imported * @throws \Exception If an error occured */ public function importUnits() { $path = $this->kernel->locateResource(self::UNIT_PATH . self::UNIT_DATA); $yaml = new Parser(); $data = $yaml->parse(file_get_contents($path)); $count = 0; $skipped = 0; foreach ($data as $unitName => $unitData) { $unit = $this->getUnit($unitName); if ($unit === null) { $unit = new Unit(); $unit->setName($unitName); $unit->setSymbol($unitData["symbol"]); if (array_key_exists("prefixes", $unitData)) { if (!is_array($unitData["prefixes"])) { throw new \Exception($unitName . " doesn't contain a prefix list, or the prefix list is not an array."); } foreach ($unitData["prefixes"] as $name) { $prefix = $this->getSiPrefix($name); if ($prefix === null) { throw new \Exception("Unable to find SI Prefix " . $name); } $unit->getPrefixes()->add($prefix); } } $this->entityManager->persist($unit); $this->entityManager->flush(); $count++; } else { $skipped++; } } return array("imported" => $count, "skipped" => $skipped); }
/** * {@inheritDoc} * Add the new bundle to the BundleBundle loader infrastructure instead of main kernel * * @param QuestionHelper $questionHelper dialog * @param InputInterface $input input * @param OutputInterface $output output * @param KernelInterface $kernel kernel * @param string $namespace namespace * @param string $bundle bundle * * @return string[] */ protected function updateKernel(QuestionHelper $questionHelper, InputInterface $input, OutputInterface $output, KernelInterface $kernel, $namespace, $bundle) { // skip if kernel manipulation disabled by options (defaults to true) $doUpdate = $input->getOption('doUpdateKernel'); if ($doUpdate == 'false') { return; } $auto = true; if ($input->isInteractive()) { $auto = $questionHelper->doAsk($output, $questionHelper->getQuestion('Confirm automatic update of your core bundle', 'yes', '?')); } $output->write('Enabling the bundle inside the core bundle: '); $coreBundle = $kernel->getBundle($input->getOption('loaderBundleName')); if (!is_a($coreBundle, '\\Graviton\\BundleBundle\\GravitonBundleInterface')) { throw new \LogicException('GravitonCoreBundle does not implement GravitonBundleInterface'); } $manip = new BundleBundleManipulator($coreBundle); try { $ret = $auto ? $manip->addBundle($namespace . '\\' . $bundle) : false; if (!$ret) { $reflected = new \ReflectionObject($kernel); return array(sprintf('- Edit <comment>%s</comment>', $reflected->getFilename()), ' and add the following bundle in the <comment>GravitonCoreBundle::getBundles()</comment> method:', '', sprintf(' <comment>new %s(),</comment>', $namespace . '\\' . $bundle), ''); } } catch (\RuntimeException $e) { return array(sprintf('Bundle <comment>%s</comment> is already defined in <comment>%s)</comment>.', $namespace . '\\' . $bundle, 'sGravitonCoreBundle::getBundles()'), ''); } }
/** * @return Bundle[] */ private function getBundlesFromKernel(KernelInterface $kernel) { if ($bundles = $kernel->getBundles()) { return $bundles; } return $kernel->registerBundles(); }
public function setUp() { static::$kernel = static::createKernel(); static::$kernel->boot(); $this->dm = static::$kernel->getContainer()->get('doctrine.odm.mongodb.document_manager'); parent::setUp(); }
/** * @Given the system should have the following recharge card profiles debt operations */ public function theSystemShouldHaveTheFollowingDebtOperations(PyStringNode $body) { /** @var CollectOperationsTestWorker $collectOperationsTestWorker */ $collectOperationsTestWorker = $this->kernel->getContainer()->get('muchacuba.recharge_card.profile.debt.collect_operations_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectOperationsTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Muchacuba\\RechargeCard\\Profile\\Debt\\Operation'); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $noInitialize = $input->getOption('no-initialize'); $append = $input->getOption('append'); if ($input->isInteractive() && !$append) { $dialog = $this->getHelperSet()->get('dialog'); $confirmed = $dialog->askConfirmation($output, '<question>Careful, database will be purged. Do you want to continue Y/N ?</question>', false); if (!$confirmed) { return 0; } } $paths = $input->getOption('fixtures'); $candidatePaths = []; if (!$paths) { $paths = []; foreach ($this->kernel->getBundles() as $bundle) { $candidatePath = $bundle->getPath() . '/DataFixtures/Document'; $candidatePaths[] = $candidatePath; if (file_exists($candidatePath)) { $paths[] = $candidatePath; } } } if (empty($paths)) { $output->writeln('<info>Could not find any candidate fixture paths.</info>'); if ($input->getOption('verbose')) { $output->writeln(sprintf('Looked for: </comment>%s<comment>"</comment>', implode('"<comment>", "</comment>', $candidatePaths))); } return 0; } $fixtures = $this->loader->load($paths); $this->executor->execute($fixtures, false === $append, false === $noInitialize, $output); $output->writeln(''); $output->writeln(sprintf('<info>Done. Executed </info>%s</info><info> fixtures.</info>', count($fixtures))); }
/** * Dumps all translation files. * * @param string $targetDir Target directory. * @param boolean $symlink True if generate symlink * * @return null */ public function dump($targetDir = 'web', $symlink = false, $directory = null) { $route = $this->router->getRouteCollection()->get('bazinga_exposetranslation_js'); $directory = null === $directory ? $this->kernel->getRootDir() . '/../' : $directory; $requirements = $route->getRequirements(); $formats = explode('|', $requirements['_format']); $routeDefaults = $route->getDefaults(); $defaultFormat = $routeDefaults['_format']; $parts = array_filter(explode('/', $route->getPattern())); $this->filesystem->remove($directory . $targetDir . "/" . current($parts)); foreach ($this->getTranslationMessages() as $locale => $domains) { foreach ($domains as $domain => $messageList) { foreach ($formats as $format) { $content = $this->engine->render('BazingaExposeTranslationBundle::exposeTranslation.' . $format . '.twig', array('messages' => array($domain => $messageList), 'locale' => $locale, 'defaultDomains' => $domain)); $path[$format] = $directory . $targetDir . strtr($route->getPattern(), array('{domain_name}' => $domain, '{_locale}' => $locale, '{_format}' => $format)); $this->filesystem->mkdir(dirname($path[$format]), 0777); if (file_exists($path[$format])) { $this->filesystem->remove($path[$format]); } file_put_contents($path[$format], $content); } $targetFile = $directory . $targetDir; $targetFile .= strtr($route->getPattern(), array('{domain_name}' => $domain, '{_locale}' => $locale, '.{_format}' => '')); if (true === $symlink) { $this->filesystem->symlink($path[$defaultFormat], $targetFile); } else { $this->filesystem->copy($path[$defaultFormat], $targetFile); } } } }
/** * @Then the system should have the following info sms subscription low balance reminder logs: * * @param PyStringNode $body */ public function theSystemShouldHaveTheFollowingOperations(PyStringNode $body) { /** @var CollectLogsTestWorker $collectLogsTestWorker */ $collectLogsTestWorker = $this->kernel->getContainer()->get('muchacuba.info_sms.subscription.low_balance_reminder.collect_logs_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectLogsTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Muchacuba\\InfoSms\\Subscription\\LowBalanceReminder\\Log'); }
/** * {@inheritdoc} */ public function resolveFixtures(KernelInterface $kernel, array $fixtures) { $resolvedFixtures = []; // Get real fixtures path foreach ($fixtures as $index => $fixture) { if ($fixture instanceof \SplFileInfo) { $filePath = $fixture->getRealPath(); if (false === $filePath) { throw new \RuntimeException(sprintf('The file %s pointed by a %s instance was not found.', (string) $fixture, get_class($fixture))); } $fixture = $filePath; } if (false === is_string($fixture)) { throw new \InvalidArgumentException('Expected fixtures passed to be either strings or a SplFileInfo instances.'); } if ('@' === $fixture[0]) { // If $kernel fails to resolve the resource, will throw a \InvalidArgumentException exception $realPath = $kernel->locateResource($fixture, null, true); } else { $realPath = realpath($fixture); } if (false === $realPath || false === file_exists($realPath)) { throw new \InvalidArgumentException(sprintf('The file "%s" was not found', $fixture)); } if (false === is_file($realPath)) { throw new \InvalidArgumentException(sprintf('Expected "%s to be a fixture file, got a directory instead.', $fixture)); } $resolvedFixtures[$realPath] = true; } return array_keys($resolvedFixtures); }
/** * Constructor * * @param KernelInterface $kernel */ public function __construct(KernelInterface $kernel) { // register logging hydrators class loader $loader = new ClassLoader(); $loader->addPrefix('OroLoggingHydrator\\', $kernel->getCacheDir() . DIRECTORY_SEPARATOR . 'oro_entities'); $loader->register(); }
/** * @Then /^у меня должна быть подписка на все активные ивенты$/ */ public function iMustHaveTicketForAllEvents() { $activeEvents = $this->kernel->getContainer()->get('doctrine')->getManager()->getRepository('StfalconEventBundle:Event')->findBy(array('active' => true)); $user = $this->kernel->getContainer()->get('fos_user.user_manager')->findUserByEmail('*****@*****.**'); $tickets = $this->kernel->getContainer()->get('doctrine')->getManager()->getRepository('StfalconEventBundle:Ticket')->findBy(array('user' => $user->getId())); assertEquals(count($tickets), count($activeEvents)); }
/** * Checks if the app can get the service from the container */ public function testServiceIsGettable() { $serviceCallableName = 'open_exchange_rates_service'; $this->assertTrue(static::$kernel->getContainer()->has($serviceCallableName)); static::$kernel->getContainer()->get($serviceCallableName); $this->assertTrue(true); }
/** * Gets translation files location. * * @return array */ private function getLocations() { $locations = array(); if (class_exists('Symfony\\Component\\Validator\\Validator')) { $r = new \ReflectionClass('Symfony\\Component\\Validator\\Validator'); $locations[] = dirname($r->getFilename()) . '/Resources/translations'; } if (class_exists('Symfony\\Component\\Form\\Form')) { $r = new \ReflectionClass('Symfony\\Component\\Form\\Form'); $locations[] = dirname($r->getFilename()) . '/Resources/translations'; } if (class_exists('Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException')) { $r = new \ReflectionClass('Symfony\\Component\\Security\\Core\\Exception\\AuthenticationException'); if (file_exists($dir = dirname($r->getFilename()) . '/../../Resources/translations')) { $locations[] = $dir; } else { // Symfony 2.4 and above $locations[] = dirname($r->getFilename()) . '/../Resources/translations'; } } $overridePath = $this->kernel->getRootDir() . '/Resources/%s/translations'; foreach ($this->kernel->getBundles() as $bundle => $class) { $reflection = new \ReflectionClass($class); if (is_dir($dir = dirname($reflection->getFilename()) . '/Resources/translations')) { $locations[] = $dir; } if (is_dir($dir = sprintf($overridePath, $bundle))) { $locations[] = $dir; } } if (is_dir($dir = $this->kernel->getRootDir() . '/Resources/translations')) { $locations[] = $dir; } return $locations; }
/** * @param \Symfony\Component\DependencyInjection\ContainerInterface $container_stub * @param \Symfony\Component\HttpKernel\KernelInterface $kernel_stub */ function let($container_stub, $kernel_stub) { $template_path = realpath(__DIR__ . '/../../../../Action/Template/'); $kernel_stub->locateResource(Argument::any())->willReturn($template_path); $container_stub->get(Argument::any())->willReturn($kernel_stub); $this->setContainer($container_stub); }
/** * @param string $cacheDir */ public function warmUp($cacheDir) { $mapFile = $cacheDir . '/classes.map'; if (is_file($mapFile)) { ClassCollectionLoader::load(include $mapFile, $cacheDir, 'classes', $this->kernel->isDebug(), false, '.php'); } }
/** * @Given the system should have the following internet profiles: * * @param PyStringNode $body * */ public function theSystemShouldHaveTheFollowingInternetProfiles(PyStringNode $body) { /** @var CollectProfilesTestWorker $collectProfilesTestWorker */ $collectProfilesTestWorker = $this->kernel->getContainer()->get('muchacuba.internet.collect_profiles_test_worker'); Assert::assertTrue((new SimpleFactory())->createMatcher()->match(iterator_to_array($collectProfilesTestWorker->collect()), (array) json_decode($body->getRaw(), true))); $this->rootContext->ignoreState('Muchacuba\\Internet\\Profile'); }
protected function writeCache(array $menu) { $file = $this->kernel->getCacheDir() . '/' . self::CACHE_FILENAME; $content = sprintf('<?php return %s;', var_export($menu, true)); $fs = new Filesystem(); $fs->dumpFile($file, $content); }
/** * Generates a url from a given patch * * @param $path * @param $method * @return string */ protected function getUrlFromPath($path, $method = 'GET') { try { $baseUrl = $this->kernel->getContainer()->getParameter('router.request_context.base_url'); } catch (InvalidArgumentException $e) { $baseUrl = ''; } try { $host = $this->kernel->getContainer()->getParameter('router.request_context.host'); } catch (InvalidArgumentException $e) { $host = 'localhost'; } $requestContext = new RequestContext($baseUrl, $method, $host); $router = $this->getRouter(); $router->setContext($requestContext); $urlStack = parse_url($path); $info = $router->match($urlStack['path']); $route = $info['_route']; unset($info['_route']); $url = $this->getUrl($route, $info); if (isset($urlStack['query'])) { $url .= '?' . $urlStack['query']; } return $url; }
/** * @return array */ public function getConfigurations() { if ($this->configuration !== null) { return $this->configuration; } $bundles = $this->kernel->getBundles(); $configuration = []; foreach ($bundles as $bundle) { try { $class = get_class($bundle); $classParts = explode('\\', $class); $bundleName = array_pop($classParts); $file = $this->kernel->locateResource(sprintf('@%s/Resources/config/search.yml', $bundleName)); } catch (\Exception $e) { continue; } $data = $this->parseFile($file); if (is_array($data)) { foreach ($data as $class => $config) { $configuration[$class] = $config; } } } $this->configuration = $configuration; return $configuration; }
/** * @param string $source * @param string $locale * * @return MessageCatalogueInterface | null */ public function extract($source, $locale) { if (!$this->isSourceAvailable($source)) { return; } $fs = new Filesystem(); /* @var Bundle $foundBundle */ $foundBundle = $this->kernel->getBundle($this->bundle); // load any messages from templates $extractedCatalogue = new MessageCatalogue($locale); $resourcesDir = $this->resolveResourcesDirectory($foundBundle); if ($fs->exists($resourcesDir)) { $this->extractor->extract($resourcesDir, $extractedCatalogue); } // load any existing messages from the translation files $translationsDir = $foundBundle->getPath() . '/Resources/translations'; if ($fs->exists($translationsDir)) { $currentCatalogue = new MessageCatalogue($locale); $this->loader->loadMessages($translationsDir, $currentCatalogue); foreach ($extractedCatalogue->getDomains() as $domain) { $messages = $currentCatalogue->all($domain); if (count($messages)) { $extractedCatalogue->add($messages, $domain); } } } return $extractedCatalogue; }