/** * Set defaults and build the conneg service. * * @param Container $app * @throws ServiceUnavailableHttpException */ public function register(Container $app) { $app["conneg.responseFormats"] = array("html"); $app["conneg.requestFormats"] = array("form"); $app["conneg.defaultFormat"] = "html"; $app["conneg"] = function (Container $app) { if ($app->offsetExists("serializer")) { if ($app["serializer"] instanceof JMS\Serializer) { if (!$app->offsetExists("conneg.serializationContext")) { $app["conneg.serializationContext"] = null; } if (!$app->offsetExists("conneg.deserializationContext")) { $app["conneg.deserializationContext"] = null; } return new JmsSerializerContentNegotiation($app); } elseif ($app["serializer"] instanceof SymfonySerializer\Serializer) { if (!$app->offsetExists("conneg.serializationContext")) { $app["conneg.serializationContext"] = array(); } if (!$app->offsetExists("conneg.deserializationContext")) { $app["conneg.deserializationContext"] = array(); } return new SymfonySerializerContentNegotiation($app); } } throw new ServiceUnavailableHttpException(null, "No supported serializer found"); }; }
/** * @param Container $container the dependency injection container. */ public function register(Container $container) { if (!$container->offsetExists('token.length')) { $container['token.length'] = TokenCreator::DEFAULT_LENGTH; } if (!$container->offsetExists('token.case')) { $container['token.case'] = TokenCreator::UPPER; } $container['token'] = function ($container) { return new TokenCreator($container['token.length'], $container['token.case']); }; }
public function register(Container $container) { $cid = $this->cid; $container[$cid] = $container->factory(function () use($cid, $container) { $get = function ($key, $default = null) use($container, $cid) { $key = $cid . '.' . $key; return $container->offsetExists($key) ? $container->offsetGet($key) : $default; }; $adapterName = $get('adapter'); switch ($adapterName) { case 'redis': $adapter = new AdapterPureRedis(['host' => $get('host'), 'port' => $get('port'), 'timeout' => $get('timeout'), 'password' => $get('password'), 'dbIndex' => $get('dbIndex')]); break; case 'file': $adapter = new AdapterFile($get('dir')); break; default: $adapter = new AdapternotCache(); break; } foreach ($get('options', []) as $k => $v) { $adapter->setOption($k, $v); } return new Cache($adapter); }); }
/** * @param Container $pimple */ public function register(Container $pimple) { // Default extractor, inflector and middleware setup $pimple['tactician.extractor'] = new ClassNameExtractor(); $pimple['tactician.inflector'] = new HandleInflector(); $pimple['tactician.middleware'] = [new LockingMiddleware()]; // Set (default tactician) locator only when not already set before if (!$pimple->offsetExists('tactician.locator')) { $pimple['tactician.locator'] = function () { return new InMemoryLocator(); }; } // Setup command bus $pimple['tactician.command_bus'] = function () use($pimple) { if (is_string($pimple['tactician.extractor'])) { $pimple['tactician.extractor'] = new $pimple['tactician.extractor'](); } if (is_string($pimple['tactician.inflector'])) { $pimple['tactician.inflector'] = new $pimple['tactician.inflector'](); } // Add handler middleware to existing set of middleware $middleware = $pimple['tactician.middleware']; $middleware[] = new CommandHandlerMiddleware($pimple['tactician.extractor'], $pimple['tactician.locator'], $pimple['tactician.inflector']); return new CommandBus($middleware); }; }
/** * @param Container|Application $app */ public function register(Container $app) { if (!$app->offsetExists('annot.useServiceControllers')) { $app['annot.useServiceControllers'] = true; } $app["annot"] = function (Container $app) { return new AnnotationService($app); }; // A custom auto loader for Doctrine Annotations since it can't handle PSR-4 directory structure AnnotationRegistry::registerLoader(function ($class) { return class_exists($class); }); // Register ServiceControllerServiceProvider here so the user doesn't have to. if ($app['annot.useServiceControllers']) { $app->register(new ServiceControllerServiceProvider()); } // this service registers the service controller and can be overridden by the user $app['annot.registerServiceController'] = $app->protect(function ($controllerName) use($app) { if ($app['annot.useServiceControllers']) { $app["{$controllerName}"] = function (Application $app) use($controllerName) { return new $controllerName($app); }; } }); $app['annot.controllerFinder'] = $app->protect(function (Application $app, $dir) { return $app['annot']->getFiles($dir, $app['annot.controllerNamespace']); }); /** @noinspection PhpUnusedParameterInspection */ $app['annot.controller_factory'] = $app->protect(function (Application $app, $controllerName, $methodName, $separator) { return $controllerName . $separator . $methodName; }); $app['annot.controllerNamespace'] = ''; }
/** * Registers new resource creator object * * @param string $name * @param Closure $resourceFactory * * @return void * @throws DependencyException */ public function registerResourceFactory($name, Closure $resourceFactory) { $key = $this->diKeys['resource'] . $name; if ($this->container->offsetExists($key)) { throw new DependencyException("Can't register resource factory with {$name}, because it's already exists"); } $this->container[$key] = $resourceFactory; }
/** * @param Container $container the dependency injection container. */ public function register(Container $container) { if (!$container->offsetExists('quota.targets')) { $container['quota.targets'] = []; } $container['quota'] = function ($container) { return new QuotaCell($container['quota.targets']); }; }
/** * {@inheritDoc} * @throws ReferenceException */ public function resolveService($arg, Container $container, $alias = "") { if (!is_string($alias)) { $alias = ""; } if ($arg[0] == ContainerBuilder::SERVICE_CHAR) { $originalName = substr($arg, 1); $name = $this->aliasThisKey($originalName, $alias); // check if the service exists if (!$container->offsetExists($name)) { $name = $originalName; if (!$container->offsetExists($name)) { throw new ReferenceException(sprintf("Tried to inject the service '%s', but it doesn't exist", $name)); } } $arg = $container[$name]; } return $arg; }
public function register(Container $pimple) { if ($pimple->offsetExists('facade.aliases')) { $aliases = $pimple->offsetGet('facade.aliases'); } else { $aliases = null; } $facadeServiceLocator = new ArrayAccessAdapter($pimple); FacadeLoader::init($facadeServiceLocator, $aliases); }
/** * @param Container $container */ public function register(Container $container) { $container->register(new ValidatorServiceProvider()); $container["validator.mapping.class_metadata_factory"] = function () use($container) { $reader = new AnnotationReader(); $loader = new AnnotationLoader($reader); $cache = $container->offsetExists("cache.factory") && $container["cache.factory"] instanceof Cache ? new DoctrineCache($container["cache.factory"]) : null; return new LazyLoadingMetadataFactory($loader, $cache); }; }
public function register(Container $container) { $cid = $this->cid; $container[$cid] = $container->factory(function () use($cid, $container) { $get = function ($key, $default = null) use($container, $cid) { $key = $cid . '.' . $key; return $container->offsetExists($key) ? $container->offsetGet($key) : $default; }; $pdo = new Database($get('dsn'), $get('user'), $get('password'), $get('options', [])); return new Db($pdo); }); }
public function route() { if ($this->container->offsetExists('controller')) { $controller = $this->container['controller']; $controller->executeMethod(); unset($controller); //Destroy all the objects } else { $view = new View\ViewNotFoundHtml($this->container['cms'], $this->container['request']->language); $view->renderNotFound(); } }
public function get($serviceName, $resolveTags = true) { if (!$this->container instanceof Container) { throw new ConfigException("No Container has been set on the ServiceLocator"); } if (!is_string($serviceName)) { throw new \InvalidArgumentException("Service name must be a string, received " . gettype($serviceName)); } if (!$this->container->offsetExists($serviceName)) { throw new ReferenceException("The key '{$serviceName}' is not registered in this Container"); } $service = $this->container[$serviceName]; // resolve tags if required if ($service instanceof TagCollection && $resolveTags) { $services = $service->getServices(); $service = []; foreach ($services as $key => $taggedService) { $service[$key] = $this->get($taggedService, false); } } return $service; }
/** * @param string $abstract * @param array $parameters * @return mixed * @throws ContainerException */ public function make($abstract, $parameters = []) { $abstract = $this->getAlias($abstract); $normalAbstract = $this->normalize($abstract); if ($this->container->offsetExists($normalAbstract)) { return $this->container->offsetGet($normalAbstract); } if (!class_exists($abstract)) { throw new ContainerException("Class {$abstract} does not exist"); } $reflector = new \ReflectionClass($abstract); if (!$reflector->isInstantiable()) { throw new ContainerException("Can't instantiate this"); } $constructor = $reflector->getConstructor(); if (is_null($constructor)) { return new $abstract(); } $parameters = $constructor->getParameters(); $dependencies = $this->getDependencies($parameters); $builder = $reflector->newInstanceArgs($dependencies); $this->instance($normalAbstract, $builder); return $this->container->offsetGet($normalAbstract); }
public function register(Container $api) { $api->extend('blimp.extend', function ($status, $api) { if ($status) { $api['security.oauth.grant.urn:blimp:accounts:google'] = function () { return new Google(); }; if ($api->offsetExists('config.root')) { $api->extend('config.root', function ($root, $api) { $tb = new TreeBuilder(); $rootNode = $tb->root('google'); $rootNode->children()->scalarNode('client_id')->cannotBeEmpty()->end()->scalarNode('client_secret')->cannotBeEmpty()->end()->scalarNode('scope')->defaultValue('email https://www.googleapis.com/auth/plus.login')->end()->scalarNode('fields')->defaultValue('id,name,link,gender,email,picture')->end()->end(); $root->append($rootNode); return $root; }); } } return $status; }); }
/** * @param Container $app */ public function __construct(Container $app) { $this->app = $app; if ($app->offsetExists('annot.cache')) { if ($app['annot.cache'] instanceof Cache) { $this->cache = $app['annot.cache']; } else { if (is_string($app['annot.cache']) && strlen($app['annot.cache']) > 0) { $cacheClass = "Doctrine\\Common\\Cache\\" . $app['annot.cache'] . "Cache"; if (!class_exists($cacheClass)) { throw new RuntimeException("Cache type: [{$cacheClass}] does not exist. Make sure you include Doctrine cache."); } $this->cache = new $cacheClass(); } else { throw new RuntimeException("Cache object does not implement Doctrine\\Common\\Cache\\Cache"); } } $this->reader = new CachedReader(new AnnotationReader(), $this->cache, $app['debug']); } else { $this->reader = new AnnotationReader(); } $this->useCache = !$this->app['debug'] && $this->cache instanceof Cache; }
public function __invoke(Container $app) { $serializerBuilder = SerializerBuilder::create(); if ($app->offsetExists("debug")) { $serializerBuilder->setDebug($app["debug"]); } if ($app->offsetExists("serializer.annotationReader")) { $serializerBuilder->setAnnotationReader($app["serializer.annotationReader"]); } if ($app->offsetExists("serializer.cacheDir")) { $serializerBuilder->setCacheDir($app["serializer.cacheDir"]); } if ($app->offsetExists("serializer.configureHandlers")) { $serializerBuilder->configureHandlers($app["serializer.configureHandlers"]); } if ($app->offsetExists("serializer.configureListeners")) { $serializerBuilder->configureListeners($app["serializer.configureListeners"]); } if ($app->offsetExists("serializer.objectConstructor")) { $serializerBuilder->setObjectConstructor($app["serializer.objectConstructor"]); } $serializerBuilder->setPropertyNamingStrategy($app["serializer.propertyNamingStrategy"]); if ($app->offsetExists("serializer.serializationVisitors")) { $this->setSerializationVisitors($app, $serializerBuilder); } if ($app->offsetExists("serializer.deserializationVisitors")) { $this->setDeserializationVisitors($app, $serializerBuilder); } if ($app->offsetExists("serializer.includeInterfaceMetadata")) { $serializerBuilder->includeInterfaceMetadata($app["serializer.includeInterfaceMetadata"]); } if ($app->offsetExists("serializer.metadataDirs")) { $serializerBuilder->setMetadataDirs($app["serializer.metadataDirs"]); } return $serializerBuilder; }
/** * Returns true if the given service is defined. * * @param string $id The service identifier * * @return Boolean true if the service is defined, false otherwise * * @api */ public function has($id) { return $this->pimple->offsetExists($id); }
/** * @param Container $container * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface|null */ private function getEventDispatcher(Container $container) { if ($container->offsetExists(self::EVENT_DISPATCHER)) { $dispatcher = $container[self::EVENT_DISPATCHER]; if (is_string($dispatcher)) { return $container[$dispatcher]; } return $dispatcher; } return null; }
/** * @param string|Middleware $middleware * @return Middleware */ public function resolveMiddleware(Container $pimple, $middleware) { if ($middleware instanceof Middleware) { return $middleware; } if ($pimple->offsetExists($middleware)) { $middleware = $pimple[$middleware]; if ($middleware instanceof Middleware) { return $middleware; } } throw new \InvalidArgumentException(sprintf('Tactician middleware must implement %s', Middleware::class)); }
public function offsetExists($id) { return $this->pimpleContainer->offsetExists($this->ensureNamespacesLoaded($id)); }
protected function view($name, Config $config) { if (!($config = $config->get("views.{$name}"))) { throw new \LogicException("No configuration for view '{$name}'"); } $view = parent::offsetGet('view')->create($config); parent::offsetExists('profiler') && $view->setProfiler(parent::offsetGet('profiler')); return $view; }
protected function processExtensions(array $config, Container $container, $alias) { $extensions = !empty($config["extensions"]) ? $config["extensions"] : []; foreach ($extensions as $service => $extension) { if (!$container->offsetExists($service)) { $aliasedService = $this->referenceResolver->aliasThisKey($service, $alias); if (!$container->offsetExists($aliasedService)) { throw new ConfigException(sprintf("Cannot use extension for the service '%s' as it does not exist", $service)); } $service = $aliasedService; } foreach ($extension as $i => $call) { $extension[$i] = $this->processCall($call, $i, $service . " (extension)"); } if (!empty($extension)) { $container->extend($service, function ($object) use($extension, $alias) { return $this->serviceFactory->extendService($object, $extension, $alias); }); } } }
/** * Determines the Twig template to use for the given parameters depending on * the existance of certain keys in the Container $app in this order: * * crud.$section.$action.$entity * crud.$section.$action * crud.$section * * If nothing exists, this string is returned: "@crud/<action>.twig" * * @param Container $app * the Silex application * @param string $section * the section of the template, either "layout" or "template" * @param string $action * the current calling action like "create" or "show" * @param string $entity * the current calling entity * * @return string * the best fitting template */ public function getTemplate(Container $app, $section, $action, $entity) { $crudSection = 'crud.' . $section; $crudSectionAction = $crudSection . '.' . $action; $offsets = [$crudSectionAction . '.' . $entity, $crudSection . '.' . $entity, $crudSectionAction, $crudSection]; foreach ($offsets as $offset) { if ($app->offsetExists($offset)) { return $app[$offset]; } } return '@crud/' . $action . '.twig'; }