/**
  * {@inheritdoc}
  */
 public function register(Container $c)
 {
     $c['migrations.apps'] = function ($c) {
         $apps = new Container();
         foreach ($c['migrations.options'] as $key => $options) {
             $apps[$key] = function () use($c, $key, $options) {
                 $db = $c['dbs'][$key];
                 return $c['migrations.create_app']($c['migrations.create_helpers']($db), $c['migrations.create_commands']($db, $options));
             };
         }
         return $apps;
     };
     $c['migrations.create_app'] = $c->protect(function ($helpers, $commands) {
         return ConsoleRunner::createApplication($helpers, $commands);
     });
     $c['migrations.create_helpers'] = $c->protect(function ($db) {
         return new HelperSet(['db' => new ConnectionHelper($db), 'dialog' => new QuestionHelper()]);
     });
     $c['migrations.create_commands'] = $c->protect(function ($db, $options) {
         $config = new Configuration($db);
         if (isset($options['namespace'])) {
             $config->setMigrationsNamespace($options['namespace']);
         }
         $config->setMigrationsDirectory($options['path']);
         $config->registerMigrationsFromDirectory($options['path']);
         if (isset($options['table'])) {
             $config->setMigrationsTableName($options['table']);
         }
         $commands = [new DiffCommand(), new ExecuteCommand(), new GenerateCommand(), new MigrateCommand(), new StatusCommand(), new VersionCommand()];
         foreach ($commands as $command) {
             $command->setMigrationConfiguration($config);
         }
         return $commands;
     });
 }
 /**
  * {@inheritdoc}
  */
 public function register(Container $app)
 {
     // Load defaults
     foreach ($this->settings as $key => $value) {
         $key = 'captcha.' . $key;
         if (!isset($app[$key])) {
             $app[$key] = $value;
         }
     }
     // Instance of builder
     $app['captcha.builder'] = function (Application $app) {
         return new CaptchaBuilder($app['captcha.phrase'], $app['captcha.phrase_builder']);
     };
     // Checks captcha
     $app['captcha.test'] = $app->protect(function ($phrase) use($app) {
         /** @var $builder CaptchaBuilder */
         $builder = $app['captcha.builder'];
         /** @var $session Session */
         $session = $app['session'];
         $builder->setPhrase($session->get($app['captcha.session_key']));
         return $builder->testPhrase($phrase);
     });
     // Returns absolute URL to the image
     $app['captcha.image_url'] = $app->protect(function () use($app) {
         /** @var $urlGenerator UrlGenerator */
         $urlGenerator = $app['url_generator'];
         return $urlGenerator->generate($app['captcha.route_name'], array(), UrlGenerator::ABSOLUTE_URL);
     });
 }
 /**
  * Registers services on the given app.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  */
 public function register(Container $app)
 {
     $app['security.jwt_retrieval.authorization_bearer.strategy'] = function () {
         return new AuthorizationBearerStrategy();
     };
     $app['security.jwt_retrieval.query_parameter.strategy'] = function () {
         return new QueryParameterStrategy();
     };
     $app['security.jwt_retrieval.chain.strategy'] = function () use($app) {
         return new ChainStrategy([$app['security.jwt_retrieval.authorization_bearer.strategy'], $app['security.jwt_retrieval.query_parameter.strategy']]);
     };
     $app['security.entry_point.jwt._proto'] = $app->protect(function () use($app) {
         return function () {
             return new JWTAuthenticationEntryPoint();
         };
     });
     $app['security.authentication_listener.factory.jwt'] = $app->protect(function ($name, $options) use($app) {
         $app['security.authentication_provider.' . $name . '.jwt'] = function () use($app, $options) {
             $encoder = new JWTEncoder($options['secret_key'], reset($options['allowed_algorithms']));
             $decoder = new JWTDecoder($options['secret_key'], $options['allowed_algorithms']);
             $converter = new SecurityUserConverter();
             $userBuilder = new JWTUserBuilder($decoder, $encoder, $converter);
             return new JWTAuthenticationProvider($userBuilder);
         };
         $app['security.authentication_listener.' . $name . '.jwt'] = function () use($app, $name, $options) {
             $strategyName = isset($options['retrieval_strategy']) ? $options['retrieval_strategy'] : 'authorization_bearer';
             return new JWTListener($app['security.token_storage'], $app['security.authentication_manager'], $app['security.jwt_retrieval.' . $strategyName . '.strategy']);
         };
         $app['security.entry_point.' . $name . '.jwt'] = $app['security.entry_point.jwt._proto']($name, $options);
         return array('security.authentication_provider.' . $name . '.jwt', 'security.authentication_listener.' . $name . '.jwt', 'security.entry_point.' . $name . '.jwt', 'pre_auth');
     });
 }
Exemplo n.º 4
0
 /**
  * Bind an abstract definition to a concrete implementation.
  *
  * @param string $abstract
  * @param string|\Closure $concrete
  * @param bool $protect
  */
 public function bind($abstract, $concrete, $protect = false)
 {
     if ($protect) {
         $concrete = $this->container->protect($concrete);
     }
     $this->container[$abstract] = $concrete;
 }
 /**
  * @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 services on the given app.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  */
 public function register(Container $app)
 {
     $app['renderer'] = function ($app) {
         return new Renderer($app);
     };
     $app['render'] = $app->protect(function ($view_path, $params = array()) use($app) {
         return $app['renderer']->render($view_path, $params);
     });
     $app['view'] = $app->protect(function ($viewName, $params = array()) use($app) {
         return $app['render'](@$app['config']['views_path'] . '/' . $viewName, $params);
     });
 }
Exemplo n.º 7
0
 /**
  * @param string $key
  * @param mixed $val
  * @param string $type (optional)
  */
 static function set($key, $val, $type = null)
 {
     if (!static::$pimple) {
         throw new \LogicException('\\Pimple\\Container not set, call init() or setPimple() before using set().');
     }
     if ('factory' == $type) {
         static::$pimple[$key] = static::$pimple->factory($val);
     } elseif ('protect' == $type) {
         static::$pimple[$key] = static::$pimple->protect($val);
     } else {
         static::$pimple[$key] = $val;
     }
 }
 public function register(Container $pimple)
 {
     $pimple['normalizer.link'] = function () use($pimple) {
         return $pimple['normalizer'];
     };
     $pimple['normalizer.image'] = function () use($pimple) {
         return $pimple['normalizer'];
     };
     $pimple['normalizer.redirect'] = function () use($pimple) {
         return $pimple['normalizer'];
     };
     $pimple['normalizer.script'] = function () use($pimple) {
         return $pimple['normalizer'];
     };
     $pimple['normalizer.stylesheet'] = function () use($pimple) {
         return $pimple['normalizer'];
     };
     $pimple['discoverer.link'] = function () use($pimple) {
         return new LinkDiscoverer($pimple['normalizer.link']);
     };
     $pimple['discoverer.image'] = function () use($pimple) {
         return new ImageDiscoverer($pimple['normalizer.image']);
     };
     $pimple['discoverer.script'] = function () use($pimple) {
         return new ScriptDiscoverer($pimple['normalizer.script']);
     };
     $pimple['discoverer.stylesheet'] = function () use($pimple) {
         return new StylesheetDiscoverer($pimple['normalizer.stylesheet']);
     };
     $pimple['discoverer.redirect'] = function () use($pimple) {
         return new RedirectDiscoverer($pimple['normalizer.redirect']);
     };
     $pimple['request_factory.internal_html'] = $pimple->protect(function (UriInterface $uri) use($pimple) {
         return new Request('GET', $uri);
     });
     $pimple['request_factory.internal_asset'] = $pimple->protect(function (UriInterface $uri) use($pimple) {
         return new Request('HEAD', $uri);
     });
     $pimple['matcher.internal_html'] = function () use($pimple) {
         return Matcher::all()->add($pimple['matcher.internal'])->add($pimple['matcher.html']);
     };
     $pimple['matcher.internal_asset'] = function () use($pimple) {
         return Matcher::all()->add($pimple['matcher.internal'])->add($pimple['matcher.asset']);
     };
     $pimple['recursor.internal_html'] = function () use($pimple) {
         return new UriRecursor($pimple['matcher.internal_html'], $pimple['request_factory.internal_html']);
     };
     $pimple['recursor.internal_asset'] = function () use($pimple) {
         return new UriRecursor($pimple['matcher.internal_asset'], $pimple['request_factory.internal_asset']);
     };
 }
 /**
  * @param Container $app
  */
 public function register(Container $app)
 {
     $app['config.initializer'] = $app->protect(function () use($app) {
         static $initialized = false;
         if ($initialized) {
             return;
         }
         $initialized = true;
         $filenames = (array) $app['config.filenames'];
         foreach ($filenames as $path) {
             $path = $app['config.replacements.resolver']($path);
             $app['config.loader']->load($path);
         }
     });
     $app['config.replacements.resolver'] = $app->protect(function ($value) use($app) {
         $replacements = $app['config.replacements'];
         if ([] === $replacements) {
             return $value;
         }
         if (is_array($value)) {
             return array_map(function ($value) use($app) {
                 return $app['config.replacements.resolver']($value);
             }, $value);
         }
         if (!is_string($value)) {
             return $value;
         }
         return $this->resolveString($value, $replacements);
     });
     $app['config.locator'] = function () {
         return new FileLocator();
     };
     $app['config.loader.yml'] = $app->factory(function (Container $app) {
         return new YamlFileLoader($app, $app['config.locator']);
     });
     $app['config.loader.php'] = $app->factory(function (Container $app) {
         return new PhpFileLoader($app, $app['config.locator']);
     });
     $app['config.loader.directory'] = $app->factory(function (Container $app) {
         return new DirectoryLoader($app, $app['config.locator']);
     });
     $app['config.loader.resolver'] = function (Container $app) {
         return new LoaderResolver([$app['config.loader.yml'], $app['config.loader.directory'], $app['config.loader.php']]);
     };
     $app['config.loader'] = function (Container $app) {
         return new DelegatingLoader($app['config.loader.resolver']);
     };
     $app['config.filenames'] = [];
     $app['config.replacements'] = [];
 }
Exemplo n.º 10
0
 /**
  * @param Container|Application $app
  */
 public function register(Container $app)
 {
     ini_set('log_errors', 1);
     strtoupper(env('APP_ENV')) === 'PRODUCTION' ? ini_set('display_errors', 0) : ini_set('display_errors', 1);
     $app['debug'] = env('DEBUG');
     !$app['debug'] ?: ($app['dump'] = $app->protect(function ($var) {
         return (new VarDumper())::dump($var);
     }));
     /** Register the app error factory */
     $app->error(function (\Exception $e) use($app) {
         // handle HTTP exceptions
         if (get_class($e) === NotFoundHttpException::class) {
             /** @var NotFoundHttpException $e */
             /** @noinspection DegradedSwitchInspection */
             switch ($e->getStatusCode()) {
                 case 404:
                     return response(view('404.html', ['error' => '404 - Page Not Found.']), 404);
                     break;
                 default:
                     $message = 'We are sorry, but something went terribly wrong.';
             }
             return new Response($message);
         }
         // not an HTTP exception
         throw $e;
     });
     if ($app['debug']) {
         error_reporting(E_ALL);
         ini_set('display_errors', 1);
         # core debug utilities
         # note that debug requires that the environment has been loaded
         include_once BOOT . 'assets/debug.php';
     }
 }
Exemplo n.º 11
0
 public function register(Container $container)
 {
     $container['cms.get_post_url_attributes'] = $container->protect(function (Post $post) {
         return ['date' => $post->getCreated()->format('Y/m/d'), 'slug' => $post->getSlug()];
     });
     $container['cms'] = function () use($container) {
         $cms = new CMS($container['em']);
         $postCmsEntity = new CMSEntity(Post::class, PostType::class);
         $postCmsEntity->addColumn('title', function (Post $post) use($container) {
             $href = $container->path('post', $container['cms.get_post_url_attributes']($post));
             return '<a href="' . $href . '">' . $post->getTitle() . '</a>';
         });
         $postCmsEntity->addColumn('slug', 'slug');
         $cms->addCMSEntity($postCmsEntity);
         $pageCmsEntity = new CMSEntity(Page::class, PageType::class);
         $pageCmsEntity->addColumn('title', 'title');
         $pageCmsEntity->addColumn('slug', 'slug');
         $cms->addCMSEntity($pageCmsEntity);
         $menuCMSEntity = new CMSEntity(Menu::class, MenuType::class);
         $menuCMSEntity->addColumn('name', 'name');
         $cms->addCMSEntity($menuCMSEntity);
         $categoryCmsEntity = new CMSEntity(Category::class, CategoryType::class);
         $categoryCmsEntity->addColumn('Name', 'name');
         $cms->addCMSEntity($categoryCmsEntity);
         return $cms;
     };
 }
Exemplo n.º 12
0
 public function register(Container $app)
 {
     $app['mailer'] = function () {
         $mailer = new \PHPMailer();
         $mailer->CharSet = 'UTF-8';
         return $mailer;
     };
     $app['email'] = $app->factory(function ($c) {
         $mailConfig = $c['config']['mail'];
         $email = $c['mailer'];
         $email->From = $mailConfig['from'];
         if (is_array($mailConfig['to'])) {
             foreach ($mailConfig['to'] as $addr) {
                 $email->addAddress($addr);
             }
         } else {
             $email->addAddress($mailConfig['to']);
         }
         $email->isHTML(true);
         return $email;
     });
     $app['email:send'] = $app->protect(function ($subject, $body) use($app) {
         $email = $app['email'];
         if ($subject and $body) {
             $email->Subject = $subject;
             $email->Body = $body;
         }
         return $email->send();
     });
 }
Exemplo n.º 13
0
 /**
  * @param Container $container
  */
 public function register(Container $container)
 {
     $container->register(new AnnotationServiceProvider());
     $container['annot.registerServiceController'] = $container->protect(function ($controllerName) use($container) {
         if ($container['annot.useServiceControllers']) {
             $container["{$controllerName}"] = function (Application $app) use($controllerName) {
                 /**
                  * resolve dependency via container
                  */
                 $reflection_class = new \ReflectionClass($controllerName);
                 $params = $reflection_class->getConstructor()->getParameters();
                 $ctor_param = [];
                 foreach ($params as $param) {
                     $class = $param->getClass();
                     if ($class === null) {
                         throw new \InvalidArgumentException("`{$param->getName()}` in {$controllerName}\n                                 constructor must have class type hinting");
                     }
                     $param_class_name = $class->getName();
                     if (!isset($app[$param_class_name])) {
                         throw new \InvalidArgumentException("{$param_class_name} in {$controllerName}\n                                 not found in container");
                     }
                     array_push($ctor_param, $app[$param_class_name]);
                 }
                 return $reflection_class->newInstanceArgs($ctor_param);
             };
         }
     });
 }
Exemplo n.º 14
0
 public function register(Container $app)
 {
     $app['twig.loader']->addLoader(new Twig_Loader_Filesystem(__DIR__ . '/../View'));
     $app->extend('twig', function ($twig, $app) {
         $twig->addFilter(new Twig_SimpleFilter('cast_to_array', function ($stdClassObject) {
             return (array) $stdClassObject;
         }));
         return $twig;
     });
     //        $app['twig'] = $app->extend('twig', function ($twig,$app) {
     //            $twig->addGlobal('paginator.range', $app['paginator.range']);
     //            $twig->addExtension(new Twig\TwigPaginatorExtension($app['request_stack']));
     //
     //            return $twig;
     //        });
     $app['paginator'] = $app->protect(function ($currentPageNumber, $totalItemsCount, $itemCountPerPage = null) use($app) {
         if (!$itemCountPerPage && isset($app['paginator.per_page'])) {
             $itemCountPerPage = $app['paginator.per_page'];
         }
         $paginator = new \Paginator\Paginator($currentPageNumber, $totalItemsCount, $itemCountPerPage);
         if (isset($app['paginator.range'])) {
             $paginator->setPageRange($app['paginator.range']);
         }
         if (isset($app['paginator.style'])) {
             $paginator->setDefaultScrollingStyle();
         }
         return $paginator->getPages();
     });
 }
Exemplo n.º 15
0
 /**
  * @param \Pimple\Container $pimple
  */
 public function register(Container $pimple)
 {
     $pimple['twig.options'] = array();
     $pimple['twig.path'] = array();
     $pimple['twig.templates'] = array();
     $pimple['twig'] = function ($c) {
         $c['twig.options'] = array_replace(array('charset' => isset($c['charset']) ? $c['charset'] : 'UTF-8', 'debug' => isset($c['debug']) ? $c['debug'] : false, 'strict_variables' => isset($c['debug']) ? $c['debug'] : false), $c['twig.options']);
         /** @var \Twig_Environment $twig */
         $twig = $c['twig.environment_factory']($c);
         if (isset($c['debug']) && $c['debug']) {
             $twig->addExtension(new \Twig_Extension_Debug());
         }
         $twig->addExtension(new \Drufony\Bridge\Twig\ThemeExtension());
         $twig->addExtension(new \Drufony\Bridge\Twig\RenderExtension());
         return $twig;
     };
     $pimple['twig.loader.drupal'] = function ($c) {
         return new DrupalLoader($GLOBALS['theme'], $GLOBALS['base_theme_info']);
     };
     $pimple['twig.loader.filesystem'] = function ($c) {
         return new \Twig_Loader_Filesystem($c['twig.path']);
     };
     $pimple['twig.loader.array'] = function ($c) {
         return new \Twig_Loader_Array($c['twig.templates']);
     };
     $pimple['twig.loader.string'] = function ($c) {
         return new \Twig_Loader_String();
     };
     $pimple['twig.loader'] = function ($c) {
         return new \Twig_Loader_Chain(array($c['twig.loader.array'], $c['twig.loader.drupal'], $c['twig.loader.filesystem'], $c['twig.loader.string']));
     };
     $pimple['twig.environment_factory'] = $pimple->protect(function ($c) {
         return new \Twig_Environment($c['twig.loader'], $c['twig.options']);
     });
 }
 public function register(Container $app)
 {
     $app['translator'] = function ($app) {
         if (!isset($app['locale'])) {
             throw new \LogicException('You must define \'locale\' parameter or register the LocaleServiceProvider to use the TranslationServiceProvider');
         }
         $translator = new Translator($app['locale'], $app['translator.message_selector'], $app['translator.cache_dir'], $app['debug']);
         $translator->setFallbackLocales($app['locale_fallbacks']);
         $translator->addLoader('array', new ArrayLoader());
         $translator->addLoader('xliff', new XliffFileLoader());
         // Register default resources
         foreach ($app['translator.resources'] as $resource) {
             $translator->addResource($resource[0], $resource[1], $resource[2], $resource[3]);
         }
         foreach ($app['translator.domains'] as $domain => $data) {
             foreach ($data as $locale => $messages) {
                 $translator->addResource('array', $messages, $locale, $domain);
             }
         }
         return $translator;
     };
     $app['translator.listener'] = function ($app) {
         return new TranslatorListener($app['translator'], $app['request_stack']);
     };
     $app['translator.message_selector'] = function () {
         return new MessageSelector();
     };
     $app['translator.resources'] = $app->protect(function ($app) {
         return array();
     });
     $app['translator.domains'] = array();
     $app['locale_fallbacks'] = array('en');
     $app['translator.cache_dir'] = null;
 }
 public function register(Container $app)
 {
     $app['ramlToSilex.initializer'] = $app->protect(function () use($app) {
         if (!is_readable($ramlFile = $app['ramlToSilex.raml_file'])) {
             throw new \RuntimeException("API config file is not readable");
         }
         $configFile = json_decode(file_get_contents($app['ramlToSilex.config_file']));
         $app['ramlToSilex.apiDefinition'] = (new Parser())->parse($ramlFile, false);
         $app['ramlToSilex.routes'] = $app['ramlToSilex.apiDefinition']->getResourcesAsUri()->getRoutes();
         if (property_exists($configFile, 'routeAccess')) {
             $app['ramlToSilex.routeAccess'] = $configFile->routeAccess;
         }
         if (property_exists($configFile, 'controllers')) {
             $app['ramlToSilex.customControllerMapping'] = $configFile->controllers;
         }
         $app['ramlToSilex.restController'] = $app->factory(function () use($app) {
             return new RestController($app);
         });
         $app['ramlToSilex.routeBuilder'] = $app->factory(function () {
             return new RouteBuilder();
         });
     });
     $app['ramlToSilex.builder'] = function () use($app) {
         $app['ramlToSilex.initializer']();
         $controllers = $app['ramlToSilex.routeBuilder']->build($app, 'ramlToSilex.restController');
         $app['controllers']->mount('', $controllers);
     };
 }
 public function it_registers_oauth2_security_services(Container $container)
 {
     $callable = Argument::type('callable');
     $container->protect($callable)->willReturnArgument();
     $factoryIdentifier = 'security.authentication_listener.factory.oauth2';
     $viewPath = realpath(__DIR__ . '/../../src/Pimple') . '/../../views/authorize.php';
     $container->offsetSet($factoryIdentifier, $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.default', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.types', ['client', 'access_token'])->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.access_token', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.authorization_code', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.client_credentials', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.client', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.refresh_token', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.user_credentials', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.user_claims', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.public_key', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.jwt_bearer', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.storage.scope', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.config', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.grant_types', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.response_types', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.token_type', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.scope_util', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.client_assertion_type', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.parameters', [])->shouldBeCalled();
     $container->offsetSet('oauth2_server', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.authorize_renderer', $callable)->shouldBeCalled();
     $container->offsetSet('oauth2_server.authorize_renderer.view', $viewPath)->shouldBeCalled();
     $this->register($container);
 }
Exemplo n.º 19
0
 public function register(Container $app)
 {
     $app['restapi.storage'] = function () use($app) {
         return new HashedStorage($app['restapi']['storage_path']);
     };
     $app['restapi.service'] = function () use($app) {
         $api = new RestApi($app['db'], $app['restapi']['schema_cache']);
         $api->setStorage($app['restapi.storage']);
         $api->setDebug($app['debug']);
         return $api;
     };
     if (isset($app['restapi']['auth'])) {
         $app['restapi.auth'] = function () use($app) {
             $auth = new AuthService($app['restapi']['auth']['users']);
             $auth->setTokenOptions($app['restapi']['auth']['token']);
             $auth->setCookieOptions($app['restapi']['auth']['cookie']);
             return $auth;
         };
         $app['restapi.listener.auth_checker'] = $app->protect(function (Request $request) use($app) {
             if (!($user = $app['restapi.auth']->getAuthenticatedUserFromRequest($request))) {
                 return new Response(null, 401, ['Content-Type' => 'application/json']);
             }
             $app['restapi.service']->setUser($user);
         });
     }
     if (isset($app['restapi']['cors'])) {
         $app['restapi.middleware.cors'] = function () use($app) {
             return new CorsMiddleware($app['restapi']['cors']);
         };
     }
 }
 public function register(Container $app)
 {
     $app["resources_factory"] = $app->protect(new ResourcesFactory($app));
     // CreateResourceController
     $app["uniqid"] = function () {
         return uniqid();
     };
 }
Exemplo n.º 21
0
 /**
  * {@inheritdoc}
  */
 public function register(Container $app)
 {
     $app['menu.factory'] = function ($app) {
         $factory = new MenuFactory();
         $factory->addExtension(new RoutingExtension($app['url_generator']));
         return $factory;
     };
     $app['menu.matcher'] = function ($app) {
         $matcher = new Matcher();
         if (isset($app['menu.matcher.configure'])) {
             $app['menu.matcher.configure']($matcher);
         }
         return $matcher;
     };
     $app['menu.matcher.configure'] = $app->protect(function (Matcher $matcher) use($app) {
         foreach ($app['menu.voters'] as $voter) {
             $matcher->addVoter($voter);
         }
     });
     $app['menu.voters'] = function ($app) {
         $request = $app['request_stack']->getMasterRequest();
         $voters = [];
         if (null !== $request) {
             $voters[] = new RouteVoter($request);
             $voters[] = new UriVoter($request->getRequestUri());
         }
         return $voters;
     };
     $app['menu.renderer.list'] = function ($app) {
         return new ListRenderer($app['menu.matcher'], [], $app['charset']);
     };
     $app['menu.provider'] = function ($app) {
         return new MenuProvider($app, $app['menus']);
     };
     if (!isset($app['menus'])) {
         $app['menus'] = [];
     }
     $app['menu.renderer'] = function ($app) {
         return new TwigRenderer($app['twig'], 'knp_menu.html.twig', $app['menu.matcher']);
     };
     $app['menu.renderer_provider'] = function ($app) {
         $app['menu.renderers'] = array_merge(['list' => 'menu.renderer.list'], ['twig' => 'menu.renderer'], isset($app['menu.renderers']) ? $app['menu.renderers'] : []);
         return new RendererProvider($app, 'twig', $app['menu.renderers']);
     };
     $app['menu.manipulator'] = function () {
         return new MenuManipulator();
     };
     $app['menu.helper'] = function ($app) {
         return new Helper($app['menu.renderer_provider'], $app['menu.provider'], $app['menu.manipulator']);
     };
     $app['menu.twig_extension'] = function ($app) {
         return new MenuExtension($app['menu.helper'], $app['menu.matcher'], $app['menu.manipulator']);
     };
     $app->extend('twig', function (\Twig_Environment $twig, $app) {
         $twig->addExtension($app['menu.twig_extension']);
         return $twig;
     });
 }
 /**
  * @inherit
  */
 public function register(Container $container)
 {
     $container['security.authentication_listener.factory.oauth2'] = $container->protect($this->factory($container));
     $container['oauth2_server'] = $this->OAuth2Server($container);
     $container['oauth2_server.authorize_renderer.view'] = __DIR__ . '/../../views/authorize.php';
     $container['oauth2_server.authorize_renderer'] = function (Container $container) {
         return new HTMLAuthorizeRenderer($container['oauth2_server.authorize_renderer.view']);
     };
 }
Exemplo n.º 23
0
 public function register(Container $c)
 {
     // FIXME entender pq dá erro essa linha (Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Identifier "default" is not defined.' in ...\Pimple\Container.php on line 95)
     //$c['dbal.options'] = array();
     $c['dbal.initialize'] = $c->protect(function () use($c) {
         static $initialized = false;
         if ($initialized) {
             return;
         }
         $initialized = true;
         if (!isset($c['dbal.options'])) {
             $c['dbal.options'] = array('default' => array());
         } elseif (!is_array(reset($c['dbal.options']))) {
             // Se o primeiro elemento do array de opções não for um array,
             // muito provavelmente o usuário está colocando as options de
             // uma única conexão, então usar como default
             $c['dbal.options'] = array('default' => $c['dbal.options']);
         }
         $c['dbal.defaultName'] = key($c['dbal.options']);
     });
     $c['dbal.conns'] = function ($c) {
         $c['dbal.initialize']();
         $dbs = new Container();
         foreach ($c['dbal.options'] as $name => $options) {
             $config = $c['dbal.configs'][$name];
             $evm = $c['dbal.evms'][$name];
             $dbs[$name] = function ($dbs) use($options, $config, $evm) {
                 return DriverManager::getConnection($options, $config, $evm);
             };
         }
         return $dbs;
     };
     $c['dbal.configs'] = function ($c) {
         $c['dbal.initialize']();
         $configs = new Container();
         foreach ($c['dbal.options'] as $name => $options) {
             $configs[$name] = new Configuration();
             if (isset($c['logger']) && class_exists('Symfony\\Bridge\\Doctrine\\Logger\\DbalLogger')) {
                 $configs[$name]->setSQLLogger(new DbalLogger($c['logger'], isset($c['stopwatch']) ? $c['stopwatch'] : null));
             }
         }
         return $configs;
     };
     $c['dbal.evms'] = function ($c) {
         $c['dbal.initialize']();
         $emvs = new Container();
         foreach ($c['dbal.options'] as $name => $options) {
             $emvs[$name] = new EventManager();
         }
         return $emvs;
     };
     $c['doctrine.registry'] = function ($c) {
         $c['dbal.initialize']();
         return new DbalRegistry($c['dbal.conns'], array_keys($c['dbal.options']), $c['dbal.defaultName']);
     };
 }
Exemplo n.º 24
0
 public function setDecoratorTemplate($template)
 {
     $this->getLog()->deprecated();
     if ($this->dc['View']->getTargetFormat() === 'xhtml') {
         $this->dc['decorator.xhtml.template'] = is_callable($template) ? $this->dc->protect($template) : $template;
     } else {
         $this->dc['View']->setTemplate($template);
     }
     return $this;
 }
    /**
     * {@inheritdoc}
     */
    public function register(Container $app)
    {
        $app["{$this->prefix}.clients"] = array();

        $app["{$this->prefix}.clients_container"] = $app->protect(function ($prefix) use ($app) {
            return new ClientsContainer($app, $prefix);
        });

        parent::register($app);
    }
Exemplo n.º 26
0
 /**
  * @param Container $container
  */
 public function register(Container $container)
 {
     $container['console.cache'] = null;
     $container['console.command.paths'] = function () {
         $paths = array();
         return $paths;
     };
     $container['console.commands'] = function () use($container) {
         $commands = array();
         return $commands;
     };
     $container['console'] = function () use($container) {
         $console = new ConsoleApplication($container);
         // automatically detect dispatcher (e.g. in Silex applications)
         if (isset($container['dispatcher']) && !is_null($container['dispatcher'])) {
             $console->setDispatcher($container['dispatcher']);
         }
         foreach ($container['console.commands'] as $command) {
             $console->add($command);
         }
         if (!is_null($container['console.cache'])) {
             if (!is_null($container['console.cache']) && !is_dir($container['console.cache'])) {
                 mkdir($container['console.cache'], 0777, true);
             }
             $cacheFile = $container['console.cache'] . '/saxulum-console.php';
             if ($container['debug'] || !file_exists($cacheFile)) {
                 file_put_contents($cacheFile, '<?php return ' . var_export($container['console.command.search'](), true) . ';');
             }
             $commandsMap = (require $cacheFile);
         } else {
             $commandsMap = $container['console.command.search']();
         }
         foreach ($commandsMap as $commandClass) {
             $command = new $commandClass();
             $console->add($command);
         }
         return $console;
     };
     $container['console.command.search'] = $container->protect(function () use($container) {
         $commandsMap = array();
         foreach ($container['console.command.paths'] as $path) {
             foreach (Finder::create()->files()->name('*.php')->in($path) as $file) {
                 /** @var SplFileInfo $file */
                 $classes = ClassFinder::findClasses($file->getContents());
                 foreach ($classes as $class) {
                     $reflectionClass = new \ReflectionClass($class);
                     if ($reflectionClass->isSubclassOf('Saxulum\\Console\\Command\\AbstractPimpleCommand') && $reflectionClass->isInstantiable()) {
                         $commandsMap[] = $class;
                     }
                 }
             }
         }
         return $commandsMap;
     });
 }
 public function testEventDispatcher_uses_pimple_function_service()
 {
     $container = new Container();
     $container['testService'] = $container->protect(function (Event $event) {
         $event->called = true;
     });
     $dispatcher = new PimpleAwareEventDispatcher($container);
     $dispatcher->addListener("test", "testService");
     $event = $dispatcher->dispatch("test");
     $this->assertTrue($event->called);
 }
 private function registerExceptionHandler(Container $container)
 {
     $container['whoops.exception_handler'] = $container->protect(function ($e) use($container) {
         $method = Run::EXCEPTION_HANDLER;
         ob_start();
         $container['whoops']->{$method}($e);
         $response = ob_get_clean();
         $code = $e instanceof HttpException ? $e->getStatusCode() : 500;
         return new Response($response, $code);
     });
 }
 /**
  * Register the cors function and set defaults
  *
  * @param Application $app
  */
 public function register(Container $app)
 {
     $app["cors.allowOrigin"] = "*";
     // Defaults to all
     $app["cors.allowMethods"] = null;
     // Defaults to all
     $app["cors.maxAge"] = null;
     $app["cors.allowCredentials"] = null;
     $app["cors.exposeHeaders"] = null;
     $app["cors"] = $app->protect(new Cors($app));
 }
 public function register(Container $app)
 {
     $app['security.remember_me.response_listener'] = function ($app) {
         if (!isset($app['security'])) {
             throw new \LogicException('You must register the SecurityServiceProvider to use the RememberMeServiceProvider');
         }
         return new ResponseListener();
     };
     $app['security.authentication_listener.factory.remember_me'] = $app->protect(function ($name, $options) use($app) {
         if (empty($options['key'])) {
             $options['key'] = $name;
         }
         if (!isset($app['security.remember_me.service.' . $name])) {
             $app['security.remember_me.service.' . $name] = $app['security.remember_me.service._proto']($name, $options);
         }
         if (!isset($app['security.authentication_listener.' . $name . '.remember_me'])) {
             $app['security.authentication_listener.' . $name . '.remember_me'] = $app['security.authentication_listener.remember_me._proto']($name, $options);
         }
         if (!isset($app['security.authentication_provider.' . $name . '.remember_me'])) {
             $app['security.authentication_provider.' . $name . '.remember_me'] = $app['security.authentication_provider.remember_me._proto']($name, $options);
         }
         return array('security.authentication_provider.' . $name . '.remember_me', 'security.authentication_listener.' . $name . '.remember_me', null, 'remember_me');
     });
     $app['security.remember_me.service._proto'] = $app->protect(function ($providerKey, $options) use($app) {
         return function () use($providerKey, $options, $app) {
             $options = array_replace(array('name' => 'REMEMBERME', 'lifetime' => 31536000, 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => true, 'always_remember_me' => false, 'remember_me_parameter' => '_remember_me'), $options);
             return new TokenBasedRememberMeServices(array($app['security.user_provider.' . $providerKey]), $options['key'], $providerKey, $options, $app['logger']);
         };
     });
     $app['security.authentication_listener.remember_me._proto'] = $app->protect(function ($providerKey) use($app) {
         return function () use($app, $providerKey) {
             $listener = new RememberMeListener($app['security'], $app['security.remember_me.service.' . $providerKey], $app['security.authentication_manager'], $app['logger'], $app['dispatcher']);
             return $listener;
         };
     });
     $app['security.authentication_provider.remember_me._proto'] = $app->protect(function ($name, $options) use($app) {
         return function () use($app, $name, $options) {
             return new RememberMeAuthenticationProvider($app['security.user_checker'], $options['key'], $name);
         };
     });
 }