/** * {@inheritdoc} */ public function get($name) { try { return parent::get($name); } catch (ParameterNotFoundException $e) { // In drupal, non existing parameters are allowed. return null; } }
/** * Tests the method for checking access to routes. * * @dataProvider providerTestAccess */ public function testAccess($entity_bundle, $requirement, $access, $expected, $expect_permission_context = TRUE) { // Set up the access result objects for allowing or denying access. $access_result = $access ? AccessResult::allowed()->cachePerPermissions() : AccessResult::neutral()->cachePerPermissions(); $expected_access_result = $expected ? AccessResult::allowed() : AccessResult::neutral(); if ($expect_permission_context) { $expected_access_result->cachePerPermissions(); } $entity_manager = $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'); // Don't expect a call to the access control handler when we have a bundle // argument requirement but no bundle is provided. if ($entity_bundle || strpos($requirement, '{') === FALSE) { $access_control_handler = $this->getMock('Drupal\\Core\\Entity\\EntityAccessControlHandlerInterface'); $access_control_handler->expects($this->once())->method('createAccess')->with($entity_bundle)->will($this->returnValue($access_result)); $entity_manager->expects($this->any())->method('getAccessControlHandler')->will($this->returnValue($access_control_handler)); } $applies_check = new EntityCreateAccessCheck($entity_manager); $route = $this->getMockBuilder('Symfony\\Component\\Routing\\Route')->disableOriginalConstructor()->getMock(); $route->expects($this->any())->method('getRequirement')->with('_entity_create_access')->will($this->returnValue($requirement)); $raw_variables = new ParameterBag(); if ($entity_bundle) { $raw_variables->set('bundle_argument', $entity_bundle); } $route_match = $this->getMock('Drupal\\Core\\Routing\\RouteMatchInterface'); $route_match->expects($this->any())->method('getRawParameters')->will($this->returnValue($raw_variables)); $account = $this->getMock('Drupal\\Core\\Session\\AccountInterface'); $this->assertEquals($expected_access_result, $applies_check->access($route, $route_match, $account)); }
/** * {@inheritdoc} */ public function filterDump(AssetInterface $asset) { if (preg_match('/\\.yfp\\.js$/', $asset->getSourcePath())) { $content = $asset->getContent(); preg_match('/(\\w+)\\.yfp\\.js$/', $asset->getSourcePath(), $matches); if (isset($matches[1])) { $name = $matches[1]; $pluginName = str_replace(' ', '', ucwords(strtr($matches[1], '_-', ' '))); $config = []; if ($this->parameterBag->has("ynlo.js_plugin.{$name}")) { $config = $this->parameterBag->get("ynlo.js_plugin.{$name}"); } $jsonConfig = json_encode($config, JSON_FORCE_OBJECT); $autoRegister = null; if (strpos($content, "YnloFramework.register('{$pluginName}')") === false && strpos($content, "YnloFramework.register(\"{$pluginName}\\')") === false) { $autoRegister = "\nYnloFramework.register('{$pluginName}');"; } $settings = <<<JAVASCRIPT {$autoRegister} YnloFramework.{$pluginName}.config = \$.extend({}, YnloFramework.{$pluginName}.config, {$jsonConfig}); JAVASCRIPT; $asset->setContent($content . $settings); } } }
/** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolveValue */ public function testResolveValue() { $bag = new ParameterBag(array()); $this->assertEquals('foo', $bag->resolveValue('foo'), '->resolveValue() returns its argument unmodified if no placeholders are found'); $bag = new ParameterBag(array('foo' => 'bar')); $this->assertEquals('I\'m a bar', $bag->resolveValue('I\'m a %foo%'), '->resolveValue() replaces placeholders by their values'); $this->assertEquals(array('bar' => 'bar'), $bag->resolveValue(array('%foo%' => '%foo%')), '->resolveValue() replaces placeholders in keys and values of arrays'); $this->assertEquals(array('bar' => array('bar' => array('bar' => 'bar'))), $bag->resolveValue(array('%foo%' => array('%foo%' => array('%foo%' => '%foo%')))), '->resolveValue() replaces placeholders in nested arrays'); $this->assertEquals('I\'m a %foo%', $bag->resolveValue('I\'m a %%foo%%'), '->resolveValue() supports % escaping by doubling it'); $this->assertEquals('I\'m a bar %foo bar', $bag->resolveValue('I\'m a %foo% %%foo %foo%'), '->resolveValue() supports % escaping by doubling it'); $bag = new ParameterBag(array('foo' => true)); $this->assertTrue($bag->resolveValue('%foo%') === true, '->resolveValue() replaces arguments that are just a placeholder by their value without casting them to strings'); $bag = new ParameterBag(array()); try { $bag->resolveValue('%foobar%', array()); $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter'); } catch (\Exception $e) { $this->assertInstanceOf('\\InvalidArgumentException', $e, '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter'); $this->assertEquals('The parameter "foobar" must be defined.', $e->getMessage(), '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter'); } try { $bag->resolveValue('foo %foobar% bar', array()); $this->fail('->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter'); } catch (\Exception $e) { $this->assertInstanceOf('\\InvalidArgumentException', $e, '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter'); $this->assertEquals('The parameter "foobar" must be defined.', $e->getMessage(), '->resolveValue() throws an InvalidArgumentException if a placeholder references a non-existant parameter'); } }
/** * @param UserEvent $event * @throws \Exception * @throws \Twig_Error */ public function onResettingRequestSuccess(UserEvent $event) { $user = $event->getUser(); $params = $event->getParams(); $url = $this->router->generate($params[$event::PARAM_RESETTING_EMAIL_ROUTE], array('token' => $user->getConfirmationToken()), true); $message = \Swift_Message::newInstance()->setSubject($this->translator->trans('security.resetting.request.email.subject'))->setFrom($this->parameter->get($params[$event::PARAM_RESETTING_EMAIL_FROM]))->setTo($user->getEmail())->setBody($this->twigEngine->render($params[$event::PARAM_RESETTING_EMAIL_TEMPLATE], array('complete_name' => $event->getSecureArea()->getCompleteName(), 'url' => $url))); $this->mailer->send($message); $this->flashBag->add(FlashBagEvents::MESSAGE_TYPE_SUCCESS, $this->translator->trans('security.resetting.request.check_email', array('user_email' => $user->getObfuscatedEmail()))); }
/** * @test * @dataProvider provideConfigs */ public function setLegacyPath(array $config, $path, $prepend = null, $append = null) { $bag = new ParameterBag(); $extension = new BassterLegacyBridgeExtension(); $extension->load($config, new ContainerBuilder($bag)); self::assertEquals($path, $bag->get('basster_legacy_bridge.legacy_path')); self::assertEquals($prepend, $bag->get('basster_legacy_bridge.prepend_script')); self::assertEquals($append, $bag->get('basster_legacy_bridge.append_script')); }
/** * @param \Symfony\Component\HttpFoundation\Request $request * @param \Symfony\Component\HttpFoundation\Session\Session $session * @param \Symfony\Component\DependencyInjection\ParameterBag\ParameterBag $requestQuery */ function it_redirects_to_passed_redirect_uri($request, $session, $requestQuery) { $request->getSession()->willReturn($session); $request->query = $requestQuery; $requestQuery->has('redirect_uri')->willReturn(true); $requestQuery->get('redirect_uri')->willReturn('uri_to_redirect_to'); $response = $this->localeAction('qw', $request); $response->getTargetUrl()->shouldReturn('uri_to_redirect_to'); }
function it_casts_variable_string_in_string($request, ParameterBag $attributes) { $request->attributes = $attributes; $attributes->get('_route_params')->willReturn(['foo' => 18098, 'bar' => true, 'xyz' => 'value']); $this->cast('$foo')->shouldReturn(18098); $this->cast('$bar')->shouldReturn(true); $this->cast('$xyz')->shouldReturn('value'); $this->cast('$test')->shouldReturn('$test'); }
/** * @param ParameterBag $bag * * @return Order */ public function create($bag) { $entity = new Order(); $entity->setApplication($bag->get(self::PARAM_APP)); $entity->setClient($this->getClient($bag)); $this->enManager->persist($entity); $this->enManager->flush(); $this->eventDispatcher->dispatch(SingUpEvents::CREATE_ORDER, new OrderCreateEvent($entity)); return $entity; }
/** * @param ParameterBag $bag * * @return Client * @throws \Exception */ public function create($bag) { $client = new Client(); $client->setMsisdn($bag->get(self::PARAM_MSISDN)); $client->setCountry($bag->get(self::PARAM_COUNTRY)); $client->setClientDirection($bag->get(self::PARAM_DIRECTION)); $this->enManager->persist($client); $this->enManager->flush(); return $client; }
/** * Executes this command. * * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $parameters = new ParameterBag(); $parameters->set('configuration.file', $input->getOption('project-dir') . DIRECTORY_SEPARATOR . 'accompli.json'); $parameters->set('console.output_interface', $output); $accompli = new Accompli($parameters); $accompli->initialize(); $successfulInstall = $accompli->deploy($input->getArgument('version'), $input->getArgument('stage')); if ($successfulInstall) { return 0; } return 1; }
/** * Tests field name * * @param string $name Name * @param string $resultName Result name * * @dataProvider dataName */ public function testName($name, $resultName) { $this->annotation->expects($this->any())->method('getClass')->will($this->returnValue('Mmoreram\\ControllerExtraBundle\\Tests\\FakeBundle\\Entity\\Fake')); $this->annotation->expects($this->any())->method('getName')->will($this->returnValue($name)); $this->attributes->expects($this->once())->method('set')->with($this->equalTo($resultName), $this->isInstanceOf('Mmoreram\\ControllerExtraBundle\\Tests\\FakeBundle\\Entity\\Fake')); $this->entityAnnotationResolver->evaluateAnnotation($this->request, $this->annotation, $this->reflectionMethod); }
/** * {@inheritdoc} */ public function get($name) { if (0 === strpos($name, 'env(') && ')' === substr($name, -1) && 'env()' !== $name) { $env = substr($name, 4, -1); if (isset($this->envPlaceholders[$env])) { foreach ($this->envPlaceholders[$env] as $placeholder) { return $placeholder; // return first result } } if (preg_match('/\\W/', $env)) { throw new InvalidArgumentException(sprintf('Invalid %s name: only "word" characters are allowed.', $name)); } if ($this->has($name)) { $defaultValue = parent::get($name); if (!is_scalar($defaultValue)) { throw new RuntimeException(sprintf('The default value of an env() parameter must be scalar, but "%s" given to "%s".', gettype($defaultValue), $name)); } } $uniqueName = md5($name . uniqid(mt_rand(), true)); $placeholder = sprintf('env_%s_%s', $env, $uniqueName); $this->envPlaceholders[$env][$placeholder] = $placeholder; return $placeholder; } return parent::get($name); }
public function testProcess() { $servers = [['host' => '127.0.0.1', 'port' => 6379], ['host' => 'localhost', 'port' => 6380, 'master' => true]]; $this->containerMock->expects($this->at(0))->method('hasParameter')->with('cache.redis.servers')->will($this->returnValue(true)); $this->containerMock->expects($this->at(1))->method('getDefinition')->with('igniter.elasticache.rediscache')->will($this->returnValue($this->definitionMock)); $this->containerMock->expects($this->at(2))->method('getParameterBag')->will($this->returnValue($this->paramterBagMock)); $this->containerMock->expects($this->at(3))->method('getParameter')->with('igniter.elasticache.redis_class')->will($this->returnValue('Redis')); $this->containerMock->expects($this->at(4))->method('getParameter')->with('cache.redis.servers')->will($this->returnValue($servers)); // look up redis class param $this->paramterBagMock->expects($this->at(0))->method('resolveValue')->will($this->returnValue('Redis')); // look up servers param $this->paramterBagMock->expects($this->at(1))->method('resolveValue')->will($this->returnValue($servers)); // setMaster and addSlave calls $this->definitionMock->expects($this->at(0))->method('addMethodCall')->with('addSlave', $this->callback(function ($subject) { // verify the subject is an array of 1 Defintion class if (count($subject) != 1 && !is_a($subject[0], 'Symfony\\Component\\DependencyInjection\\Definition')) { return false; } /** @var $definition \Symfony\Component\DependencyInjection\Definition */ $definition = $subject[0]; // verify the connect call if ($definition->getMethodCalls() !== [['connect', ['127.0.0.1', 6379]]]) { return false; } return true; })); $this->definitionMock->expects($this->at(1))->method('addMethodCall')->with('setMaster', $this->callback(function ($subject) { // verify the subject is an array of 1 Defintion class if (count($subject) != 1 && !is_a($subject[0], 'Symfony\\Component\\DependencyInjection\\Definition')) { return false; } /** @var $definition \Symfony\Component\DependencyInjection\Definition */ $definition = $subject[0]; // verify the connect call if ($definition->getMethodCalls() !== [['connect', ['localhost', 6380]]]) { return false; } return true; })); $compiler = new RedisCompiler(); $compiler->process($this->containerMock); }
/** * Creates a user-presentable string describing the given exception. * * @param $exception \Exception The exception to describe */ protected function exceptionToString(\Exception $exception) { if ($exception instanceof \PHPUnit_Framework_Exception) { // PHPUnit assertion exceptions do not include expected / observed info in their // messages, but expect the test listeners to format that info like the following // (see e.g. PHPUnit_TextUI_ResultPrinter::printDefectTrace) return trim(\PHPUnit_Framework_TestFailure::exceptionToString($exception)); } if ($this->parameters->get('verbose')) { return trim($exception); } return trim($exception->getMessage()); }
/** * Tests the method for checking access to routes. * * @dataProvider providerTestAccess */ public function testAccess($entity_bundle, $requirement, $access, $expected) { $entity_manager = $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'); // Don't expect a call to the access controller when we have a bundle // argument requirement but no bundle is provided. if ($entity_bundle || strpos($requirement, '{') === FALSE) { $access_controller = $this->getMock('Drupal\\Core\\Entity\\EntityAccessControllerInterface'); $access_controller->expects($this->once())->method('createAccess')->with($entity_bundle)->will($this->returnValue($access)); $entity_manager->expects($this->any())->method('getAccessController')->will($this->returnValue($access_controller)); } $applies_check = new EntityCreateAccessCheck($entity_manager); $route = $this->getMockBuilder('Symfony\\Component\\Routing\\Route')->disableOriginalConstructor()->getMock(); $route->expects($this->any())->method('getRequirement')->with('_entity_create_access')->will($this->returnValue($requirement)); $request = new Request(); $raw_variables = new ParameterBag(); if ($entity_bundle) { // Add the bundle as a raw variable and an upcasted attribute. $request->attributes->set('bundle_argument', new \stdClass()); $raw_variables->set('bundle_argument', $entity_bundle); } $request->attributes->set('_raw_variables', $raw_variables); $account = $this->getMock('Drupal\\Core\\Session\\AccountInterface'); $this->assertEquals($expected, $applies_check->access($route, $request, $account)); }
/** * Attempt to get an attribute from the assertion. * * @param string $name * @param null $default * @return mixed|null */ public function getAttribute($name, $default = null) { $attributeDefinition = $this->attributeDictionary->getAttributeDefinition($name); // try first by urn:mace, then by urn:oid if ($this->assertionAttributes->has($attributeDefinition->getUrnMace())) { $attribute = $this->assertionAttributes->get($attributeDefinition->getUrnMace()); } elseif ($this->assertionAttributes->has($attributeDefinition->getUrnOid())) { $attribute = $this->assertionAttributes->get($attributeDefinition->getUrnOid()); } else { return $default; } // if it is singular, it should return the single value if it has a value if ($attributeDefinition->getMultiplicity() === AttributeDefinition::MULTIPLICITY_SINGLE) { $count = count($attribute); if ($count > 1) { throw new UnexpectedValueException(sprintf('AttributeDefinition "%s" has a single-value multiplicity, yet returned' . ' "%d" values', $attributeDefinition->getName(), count($attribute))); } elseif ($count === 0) { $attribute = null; } else { $attribute = reset($attribute); } } return $attribute; }
/** * {@inheritdoc} */ public function resolve() { if ($this->resolved) { return; } parent::resolve(); foreach ($this->envPlaceholders as $env => $placeholders) { if (!isset($this->parameters[$name = strtolower("env({$env})")])) { continue; } if (is_numeric($default = $this->parameters[$name])) { $this->parameters[$name] = (string) $default; } elseif (null !== $default && !is_scalar($default)) { throw new RuntimeException(sprintf('The default value of env parameter "%s" must be scalar or null, %s given.', $env, gettype($default))); } } }
/** * @param string $parameterId * @return mixed */ protected function getParameter(string $parameterId) { return $this->parameterBag->get($parameterId); }
/** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve */ public function testResolveIndicatesWhyAParameterIsNeeded() { $bag = new ParameterBag(array('foo' => '%bar%')); try { $bag->resolve(); } catch (NonExistentParameterException $e) { $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage()); } $bag = new ParameterBag(array('foo' => '%bar%')); try { $bag->resolve(); } catch (NonExistentParameterException $e) { $this->assertEquals('The parameter "foo" has a dependency on a non-existent parameter "bar".', $e->getMessage()); } }
/** * Collect the parameter bag. * * @param ComposerInformation $information The composer information. * * @param string[] $baseParameters The base parameters. * * @return ParameterBag */ private function collectParameters(ComposerInformation $information, $baseParameters) { $parameterBag = new ParameterBag($baseParameters); foreach ($information->getPackageNames() as $packageName) { $parameterBag->set(sprintf('package:%s', $packageName), $information->getPackageDirectory($packageName)); $parameterBag->set(sprintf('version:%s', $packageName), $information->getPackageVersion($packageName)); $parameterBag->set(sprintf('date:%s', $packageName), $information->getPackageReleaseDate($packageName)); } return $parameterBag; }
/** * Return all parameters. * * @return array */ public function getParameters() { return $this->parameters->all(); }
/** * Override of set() that returns $this * * @param string $name * @param mixed $value * * @return $this */ public function set($name, $value) { parent::set($name, $value); return $this; }
public function get($key) { return $this->config->get($key); }
/** * @param array $parameters * * @return $this */ public function setParameters($parameters) { $this->parameters->clear(); $this->parameters->add($parameters); return $this; }
/** * @covers Symfony\Component\DependencyInjection\ParameterBag\ParameterBag::resolve * @dataProvider stringsWithSpacesProvider */ public function testResolveStringWithSpacesReturnsString($expected, $test, $description) { $bag = new ParameterBag(array('foo' => 'bar')); try { $this->assertEquals($expected, $bag->resolveString($test), $description); } catch (ParameterNotFoundException $e) { $this->fail(sprintf('%s - "%s"', $description, $expected)); } }
/** * Given an entity parameter definition, returns associated object Manager * * This method is only useful when your entities namespaces are defined as * a parameter, very useful when you want to provide a way of overriding * entities easily * * @param string $entityParameter Entity Parameter * * @return ObjectManager|null Object manager */ public function getManagerByEntityParameter($entityParameter) { $entityNamespace = $this->parameterBag->get($entityParameter); return $this->getManagerByEntityNamespace($entityNamespace); }
/** * {@inheritDoc} */ public function has($name) { return isset($GLOBALS['conf']) && array_key_exists($name, $GLOBALS['conf']) || parent::has($name); }
/** * Translates numbered message to output language. * * @param string $message message specification to translate * @param string $number choice number * @param array $parameters message parameters * * @return string */ protected final function translateChoice($message, $number, array $parameters = array()) { return $this->translator->transChoice($message, $number, $parameters, 'behat', $this->parameters->get('language')); }
/** * Clear all parameter. */ public function clear() { $this->parameters->clear(); }