/**
  * Registers services on the given container.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Application $app
  * @return Wunderlist
  */
 public function register(Application $app)
 {
     $app['wunderlist.lusitanian_authenticator'] = $app->share(function ($app) {
         $requestStack = $app['request_stack'];
         $currentRequest = $requestStack->getCurrentRequest();
         $wunderlist = $app['oauth']->getService('wunderlist');
         return new OAuthLibAuthentication($wunderlist, $currentRequest);
     });
     $app['wunderlist.default_authenticator'] = $app->share(function ($app) {
         if (!$app->offsetExists('wunderlist.authenticator')) {
             $app['wunderlist.authenticator'] = 'lusitanian';
         }
         return $app['wunderlist.' . $app['wunderlist.authenticator'] . '_authenticator'];
     });
     $app['wunderlist.builder'] = $app->share(function ($app) {
         $builder = new ClientBuilder();
         $builder->setAuthenticator($app['wunderlist.default_authenticator']);
         if ($app->offsetExists('serializer')) {
             $builder->setSerializer($app['serializer']);
         }
         if ($app->offsetExists('wunderlist.http_client')) {
             $builder->setHttpClient($app['wunderlist.http_client']);
         }
         return $builder;
     });
     $app['wunderlist'] = $app->share(function ($app) {
         return $app["wunderlist.builder"]->build();
     });
 }
 protected function getClient($annotationOptions = array())
 {
     if (!$this->app->offsetExists('annot')) {
         $this->registerAnnotations($annotationOptions);
     }
     $this->client = new Client($this->app, $this->clientOptions);
 }
 /**
  * Implements ControllerProviderInterface::connect() connecting this
  * controller.
  *
  * @param Application $app
  * the Application instance of the Silex application
  *
  * @return SilexController\Collection
  * this method is expected to return the used ControllerCollection instance
  */
 public function connect(Application $app)
 {
     if ($app->offsetExists('twig.loader.filesystem')) {
         $app['twig.loader.filesystem']->addPath(__DIR__ . '/../views/', 'crud');
     }
     if (!$app->offsetExists('crud.layout')) {
         $app['crud.layout'] = '@crud/layout.twig';
     }
     $class = get_class($this);
     $factory = $app['controllers_factory'];
     $factory->get('/resource/static', $class . '::staticFile')->bind('static');
     $factory->match('/{entity}/create', $class . '::create')->bind('crudCreate');
     $factory->match('/{entity}', $class . '::showList')->bind('crudList');
     $factory->match('/{entity}/{id}', $class . '::show')->bind('crudShow');
     $factory->match('/{entity}/{id}/edit', $class . '::edit')->bind('crudEdit');
     $factory->post('/{entity}/{id}/delete', $class . '::delete')->bind('crudDelete');
     $factory->match('/{entity}/{id}/{field}/file', $class . '::renderFile')->bind('crudRenderFile');
     $factory->post('/{entity}/{id}/{field}/delete', $class . '::deleteFile')->bind('crudDeleteFile');
     $factory->get('/setting/locale/{locale}', $class . '::setLocale')->bind('crudSetLocale');
     $app->before(function (Request $request, Application $app) {
         if ($app['crud']->getManageI18n()) {
             $locale = $app['session']->get('locale', 'en');
             $app['translator']->setLocale($locale);
         }
         $locale = $app['translator']->getLocale();
         $app['crud']->setLocale($locale);
     });
     return $factory;
 }
 public function testMongoDBServiceProviderManager()
 {
     $this->application->register(new ElasticSearchServiceProvider(), array('elasticsearch' => array('connections' => array('default' => array('host' => 'localhost', 'port' => 12345), 'cluster' => array('server' => array(array('host' => 'localhost', 'port' => 3), array('host' => 'localhost', 'port' => 2)))))));
     if (!$this->application->offsetExists('es.manager')) {
         $this->markTestSkipped('elasticsearch not found into PIMPLE');
     }
     $this->arrayHasKey('es.default_manager', $this->application);
     $this->assertSame($this->application['es.manager']('default'), $this->application['es.default_manager']);
 }
 public function testMongoDBServiceProviderManager()
 {
     $this->application->register(new DoctrineMongoDBServiceProvider(), array('doctrine_mongodb' => array('connections' => array('default' => array('host' => 'localhost', 'database' => 'database', 'port' => 27017)), 'document_managers' => array('default' => array('mapping' => array('yml' => array('type' => 'yml', 'alias' => 'Alias', 'path' => '/path/to/yml/files', 'namespace' => 'Unit\\MongoDB\\Tests\\Yml'), 'xml' => array('type' => 'yml', 'path' => '/path/to/yml/files', 'namespace' => 'Unit\\MongoDB\\Tests\\Yml'), 'annotation' => array('type' => 'annotation', 'path' => '/path/to/annotation/classes', 'namespace' => 'Unit\\MongoDB\\Tests\\Annotation')))))));
     if (!$this->application->offsetExists('doctrine_mongodb')) {
         $this->markTestSkipped('doctrine_mongodb not found into PIMPLE');
     }
     $this->arrayHasKey('doctrine_mongodb.default_manager', $this->application);
     $this->assertSame($this->application['doctrine_mongodb.document_manager']('default'), $this->application['doctrine_mongodb.default_document_manager']);
 }
Example #6
0
 public function __invoke(array $record)
 {
     $record['extra']['clientIp'] = $this->getClientIp($this->app['request_stack']);
     if ($this->app->offsetExists('security')) {
         $record['extra']['user'] = $this->getUsername($this->app['security']);
     }
     $record['extra']['token'] = $this->token;
     $record = $this->addRemoteRequestToken($record, $this->app['request_stack']);
     return $record;
 }
 public function testServiceFactoryServiceProviderOptions()
 {
     $this->application->register(new ServiceFactoryServiceProvider(), array('service_factory' => array('my_class' => array('class' => '\\VPG\\Unit\\Silex\\Provider\\Tests\\MyClass', 'constructor' => array('@dispatcher', array(1, 2), 'a value', 99), 'tags' => array('setLogger' => '@url_matcher')))));
     if (!$this->application->offsetExists('service.factory')) {
         $this->markTestSkipped('service factory not found into PIMPLE');
     }
     $service = $this->application['service.factory']('my_class');
     $this->assertEquals($this->application['dispatcher'], $service->eventDispatcher);
     $this->assertEquals($this->application['url_matcher'], $service->matcher);
     $this->assertEquals(array(1, 2), $service->values);
     $this->assertEquals('a value', $service->string);
     $this->assertEquals(99, $service->number);
 }
 public function testRegister()
 {
     $app = new Application();
     $app->register(new CRUDServiceProvider(), array('crud.file' => $this->crudFile, 'crud.datafactory' => $this->dataFactory));
     $this->assertTrue($app->offsetExists('crud'));
     $app['crud']->getEntities();
 }
Example #9
0
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registered
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  */
 public function boot(Application $app)
 {
     $src = $app->offsetExists('commands.path') ? $app['commands.path'] : $app['path.src'];
     $dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($src));
     $commands = new \ArrayObject();
     /** @var RecursiveDirectoryIterator $dir */
     for ($dir->rewind(); $dir->valid(); $dir->next()) {
         if ($dir->isDot()) {
             continue;
         }
         if ('php' !== $dir->getExtension()) {
             continue;
         }
         $name = $dir->getSubPathname();
         $name = substr($name, 0, -4);
         $className = str_replace(DIRECTORY_SEPARATOR, '\\', $name);
         $r = new ReflectionClass($className);
         if ($r->isAbstract() || false === $r->isSubclassOf("Symfony\\Component\\Console\\Command\\Command")) {
             continue;
         }
         $commands->append(new $className());
     }
     /** @noinspection PhpParamsInspection */
     $app['console'] = $app->share($app->extend('console', function (Console $console) use($commands) {
         foreach ($commands as $command) {
             $console->add($command);
         }
         return $console;
     }));
 }
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registers
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  */
 public function boot(Application $app)
 {
     // Add twig template path.
     if ($app->offsetExists('twig.loader.filesystem')) {
         $app['twig.loader.filesystem']->addPath(__DIR__ . '/views/', 'user');
     }
 }
 /**
  * @covers ::register
  * @covers ::boot
  */
 public function testDefaults()
 {
     $app = new Silex();
     $app['db'] = $this->getMockBuilder('Doctrine\\DBAL\\Connection')->disableOriginalConstructor()->getMock();
     $console = new Console();
     $app->register(new DoctrineMigrationsProvider($console));
     $this->assertTrue($app->offsetExists('migrations.output_writer'));
     $this->assertInstanceOf('Doctrine\\DBAL\\Migrations\\OutputWriter', $app['migrations.output_writer']);
     $this->assertNull($app['migrations.namespace']);
     $this->assertNull($app['migrations.directory']);
     $this->assertEquals('Migrations', $app['migrations.name']);
     $this->assertEquals('migration_versions', $app['migrations.table_name']);
     $this->assertFalse($console->has('migrations:execute'));
     $this->assertFalse($console->has('migrations:generate'));
     $this->assertFalse($console->has('migrations:migrate'));
     $this->assertFalse($console->has('migrations:status'));
     $this->assertFalse($console->has('migrations:version'));
     $this->assertFalse($console->has('migrations:diff'));
     $app->boot();
     $this->assertTrue($console->has('migrations:execute'));
     $this->assertTrue($console->has('migrations:generate'));
     $this->assertTrue($console->has('migrations:migrate'));
     $this->assertTrue($console->has('migrations:status'));
     $this->assertTrue($console->has('migrations:version'));
     $this->assertFalse($console->has('migrations:diff'));
 }
Example #12
0
 /**
  * Bootstraps the application.
  *
  * This method is called after all services are registered
  * and should be used for "dynamic" configuration (whenever
  * a service must be requested).
  */
 public function boot(Application $app)
 {
     if ($app->offsetExists('facade.aliases')) {
         $aliases = $app->offsetGet('facade.aliases');
         ClassAliaser::register($aliases);
     }
 }
 public function register(Application $app)
 {
     $app['cache.memcached'] = $app->share(function () use($app) {
         if (!class_exists('\\Doctrine\\Common\\Cache\\MemcachedCache')) {
             throw new \Exception('You need to include doctrine/common in order to use the cache service');
         }
         $cache = new MemcachedCache();
         $cache->setMemcached($app['memcached']);
         return $cache;
     });
     $app['cache.predis'] = $app->share(function () use($app) {
         if (!class_exists('\\Doctrine\\Common\\Cache\\PredisCache')) {
             throw new \Exception('You need to include doctrine/common in order to use the cache service');
         }
         return new PredisCache($app['predis.client']);
     });
     $app['cache.predis_serializer'] = $app->share(function () use($app) {
         if (!class_exists('\\Doctrine\\Common\\Cache\\PredisCache')) {
             throw new \Exception('You need to include doctrine/common in order to use the cache service');
         }
         return new SerializingPredisCache($app['predis.client']);
     });
     $app['cache'] = $app->share(function () use($app) {
         if ($app->offsetExists('cache.default')) {
             return $app[$app['cache.default']];
         }
         return $app['memcached'];
     });
 }
 public function register(Application $app)
 {
     $app['lexik_form_filter.query_builder_updater'] = $app->share(function ($app) {
         $frmDataExt = $app['lexik_form_filter.form_data_extractor'];
         $dispatcher = $app['dispatcher'];
         return new FilterBuilderUpdater($frmDataExt, $dispatcher);
     });
     $app['lexik_form_filter.form_data_extractor'] = $app->share(function ($app) {
         $formDataExtractor = new FormDataExtractor();
         $formDataExtractor->addMethod(new DefaultExtractionMethod());
         $formDataExtractor->addMethod(new TextExtractionMethod());
         $formDataExtractor->addMethod(new ValueKeysExtractionMethod());
         if ($app->offsetExists('form-filter.data_extraction_methods')) {
             foreach ($app['form-filter.data_extraction_methods'] as $extMethod) {
                 $formDataExtractor->addMethod($extMethod);
             }
         }
         return $formDataExtractor;
     });
     $app['form.extensions'] = $app->share($app->extend('form.extensions', function ($extensions) use($app) {
         $extensions[] = new FilterExtension();
         return $extensions;
     }));
     $app['dispatcher']->addListener(FilterEvents::PREPARE, array(new PrepareListener(), 'onFilterBuilderPrepare'));
     $app['dispatcher']->addSubscriber(new DoctrineSubscriber());
 }
 public function register(Application $app)
 {
     $app['monolog.formatter'] = $app->share(function () {
         return new LineFormatter(null, 'Y-m-d H:i:s.u');
     });
     $app['monolog.handler'] = function () use($app) {
         if (!$app['monolog.logfile']) {
             return new NullHandler();
         }
         if (method_exists('Silex\\Provider\\MonologServiceProvider', 'translateLevel')) {
             $level = MonologServiceProvider::translateLevel($app['monolog.level']);
         } else {
             $level = $app['monolog.level'];
         }
         $streamHandler = new StreamHandler($app['monolog.logfile'], $level);
         $streamHandler->setFormatter($app['monolog.formatter']);
         return $streamHandler;
     };
     $app['logger'] = $app->share($app->extend('logger', function (Logger $logger, \Pimple $app) {
         $logger->pushProcessor($app['logger.request_processor']);
         $logger->pushProcessor(new PsrLogMessageProcessor());
         if (!($app->offsetExists('monolog.logstashfile') && $app['monolog.logstashfile'])) {
             return $logger;
         }
         $logstashHandler = new StreamHandler($app['monolog.logstashfile'], $app['monolog.level']);
         $logstashHandler->setFormatter(new LogstashFormatter($app['monolog.name']));
         $extras = array();
         if ($app->offsetExists('meta.service')) {
             $extras['service'] = $app['meta.service'];
         }
         if ($app->offsetExists('meta.customer')) {
             $extras['customer'] = $app['meta.customer'];
         }
         if ($app->offsetExists('meta.environment')) {
             $extras['environment'] = $app['meta.environment'];
         }
         $logstashHandler->pushProcessor(new ExtraContextProcessor($extras));
         $logger->pushHandler($logstashHandler);
         return $logger;
     }));
     $app['logger.request_processor'] = $app->share(function () use($app) {
         return new RequestProcessor($app);
     });
 }
 /**
  * @param \Silex\Application $app
  */
 public function boot(Application $app)
 {
     /** @var AnnotationService $annotationService */
     $annotationService = $app['annot'];
     // Process annotations for all controllers in given directory
     if ($app->offsetExists('annot.controllerDir') && strlen($app['annot.controllerDir']) > 0) {
         if (!is_dir($app['annot.controllerDir'])) {
             throw new RuntimeException("Controller directory: {$app['annot.controllerDir']} does not exist.");
         }
         $controllers = $annotationService->discoverControllers($app['annot.controllerDir']);
         $annotationService->registerControllers($controllers);
     }
     // Process annotations for any given controllers
     if ($app->offsetExists('annot.controllers') && is_array($app['annot.controllers'])) {
         foreach ($app['annot.controllers'] as $controllerName) {
             $annotationService->registerController($controllerName);
         }
     }
 }
 /**
  * Register this service
  * (non-PHPdoc)
  * @see \Silex\ServiceProviderInterface::register()
  */
 public function register(Application $app)
 {
     $app['ten24.livereload.default_options'] = array('host' => 'localhost', 'port' => 35729, 'enabled' => true, 'check_server_presence' => true);
     $app['ten24.livereloader'] = $app->share(function ($app) {
         if ($app->offsetExists('ten24.livereload.options')) {
             $app['ten24.livereload.options'] = array_merge($app['ten24.livereload.default_options'], $app['ten24.livereload.options']);
         } else {
             $app['ten24.livereload.options'] = $app['ten24.livereload.default_options'];
         }
         $params = $app['ten24.livereload.options'];
         return new LiveReloadListener($params);
     });
 }
Example #18
0
 /**
  * (non-PHPdoc)
  * @see \Silex\ServiceProviderInterface::register()
  * @param Application $app
  */
 public function register(Application $app)
 {
     $app[self::HMAC_VALIDATE_REQUEST] = $app->protect(function (Request $request, $token = null) use($app) {
         $method = $request->getMethod();
         $content = $request->getContent();
         /* @var $user UserModel */
         $user = $app->offsetExists('user') ? $app['user'] : null;
         /**
          * Getting variables
          */
         $time = filter_var($request->headers->get('x-time'), FILTER_SANITIZE_NUMBER_INT);
         $url = filter_var($request->headers->get('x-url'), FILTER_SANITIZE_URL);
         $hmac = filter_var($request->headers->get('x-hmac-hash'), FILTER_SANITIZE_STRING);
         /**
          * For GET requests, this takes the form:
          * {{REQUEST_METHOD}}{{HTTP_HOST}}{{REQUEST_URI}}
          *
          * For POST requests, this would be:
          * {{REQUEST_METHOD}}{{HTTP_HOST}}{{REQUEST_URI}}{{RAW_POST_DATA}}
          *
          * And for PUT requests, this would be:
          * {{REQUEST_METHOD}}{{HTTP_HOST}}{{REQUEST_URI}}{{RAW_PUT_DATA}}
          */
         $data = "{$method}:{$url}" . (!empty($content) ? ":{$content}" : '');
         /**
          * If $user is null, this request is for login probably
          */
         if ($user === null) {
             $key = hash('sha512', "{$data}:{$time}");
         } else {
             // Getting user email
             $email = $user->getEmail();
             $key = hash('sha512', "{$email}:{$token}");
         }
         $manager = new Manager(new HashHmac());
         $manager->config(['algorithm' => 'sha512', 'num-first-iterations' => 10, 'num-second-iterations' => 10, 'num-final-iterations' => 100]);
         //time to live, when checking if the hmac isValid this will ensure
         //that the time with have to be with this number of seconds
         $manager->ttl(2);
         //the current timestamp, this will be compared in the other API to ensure
         $manager->time($time);
         //the secure private key that will be stored locally and not sent in the http headers
         $manager->key($key);
         //the data to be encoded with the hmac, you could use the URI for this
         $manager->data($data);
         //to check if the hmac is valid you need to run the isValid() method
         //this needs to be executed after the encode method has been ran
         return $manager->isValid($hmac);
     });
 }
 public function __invoke(Request $request, Response $response, Application $app)
 {
     if ($app->offsetExists("json-schema.describedBy") && !$response->isEmpty()) {
         if ($app["json-schema.correlationMechanism"] === "profile") {
             $contentType = $response->headers->get("Content-Type");
             $response->headers->set("Content-Type", "{$contentType}; profile=\"{$app["json-schema.describedBy"]}\"");
         } elseif ($app["json-schema.correlationMechanism"] === "link") {
             $response->headers->set("Link", "<{$app["json-schema.describedBy"]}>; rel=\"describedBy\"", false);
         } else {
             $errorMessage = "json-schema.correlationMechanism must be either \"profile\" or \"link\"";
             throw new ServiceUnavailableHttpException(null, $errorMessage);
         }
     }
 }
 /**
  * Register this service
  * (non-PHPdoc)
  *
  * @see \Silex\ServiceProviderInterface::register()
  */
 public function register(Application $app)
 {
     $console = $app['console'];
     $app['ten24.consolecommand.default_options'] = array('doctrine' => array('autoRegister' => true, 'registerSchemaShow' => true, 'registerSchemaLoad' => true, 'registerDatabaseDrop' => true, 'registerDatabaseCreate' => true, 'schemaFile' => $app['root.dir'] . '/app/config/database/schema.php'), 'cache' => array('autoRegister' => true, 'registerClear' => true, 'cachePath' => $app['cache.path']), 'assetic' => array('autoRegister' => true, 'registerDump' => true));
     if (!$app->offsetExists('ten24.consolecommand.options')) {
         $app['ten24.consolecommand.options'] = $app['ten24.consolecommand.default_options'];
     } else {
         $app['ten24.consolecommand.options'] = array_merge($app['ten24.consolecommand.options'], $app['ten24.consolecommand.default_options']);
     }
     // Register doctrine:* console commands
     $doctrine = new Command\CommandDoctrine($console, $app, $app['ten24.consolecommand.options']['doctrine']);
     // Register assetic:* console commands
     $assetic = new Command\CommandAssetic($console, $app, $app['ten24.consolecommand.options']['assetic']);
     // Register cache:* commands
     $cache = new Command\CommandCache($console, $app, $app['ten24.consolecommand.options']['cache']);
 }
Example #21
0
 public function register(Application $app)
 {
     $app['config.dir'] = function () {
         throw new \RuntimeException('Set config.dir first');
     };
     $app['config'] = function () use($app) {
         $config = new Config($app['config.dir']);
         if (true === $app->offsetExists('env')) {
             $filter = new \Fatso\Config\FileFilter\EnvFilter($app['env']);
             $config->setFilter($filter);
         }
         return $config;
     };
     $app['env'] = $app->share(function () {
         return new Env();
     });
 }
 /**
  * @see \Silex\ServiceProviderInterface::register()
  */
 public function register(Application $app)
 {
     foreach ($this->services as $serviceName => $serviceDetails) {
         /* @var $classService string */
         $service = array_shift($serviceDetails);
         /* @var $args array */
         $args = array_map(function ($row) use($app) {
             if (!is_numeric($row) && !is_string($row)) {
                 return $row;
             }
             if ($app->offsetExists($row)) {
                 return $app[$row];
             }
             return $row;
         }, $serviceDetails);
         $app[$serviceName] = $app->share(function () use($service, $args) {
             return new $service(...$args);
         });
     }
 }
 /**
  * (register hook)
  *
  * @param \Silex\Application $application
  */
 public function register(Application $application)
 {
     /*
      * ElasticSearch Connection Manager Closure.
      *
      * @param string $managerKey
      *
      * @return \Doctrine\MongoDB\Connection
      */
     $application['es.manager'] = $application->protect(function ($managerKey = 'default') use($application) {
         if (!class_exists('\\Elastica\\Client')) {
             throw new \RuntimeException('The PHP Elastica library is missing.');
         }
         $key = strtolower($managerKey);
         if (isset($application['elasticsearch']['connections'][$key])) {
             $serviceKey = sprintf('es.%s_manager', $key);
             if (!$application->offsetExists($serviceKey)) {
                 $application[$serviceKey] = new Client($application['elasticsearch']['connections'][$key]);
             }
             return $application[$serviceKey];
         }
     });
 }
 public function register(Application $app)
 {
     $app['console.output'] = $app->share(function () {
         return new ConsoleOutput();
     });
     $app['console.input'] = $app->share(function () {
         return new ArgvInput();
     });
     $app['logger.console_format'] = "%start_tag%%level_name%:%end_tag% %message%\n";
     $app['monolog.handler'] = function () use($app) {
         $logfile = $app->offsetExists('monolog.console_logfile') ? $app['monolog.console_logfile'] : $app['monolog.logfile'];
         return new StreamHandler($logfile, $app['monolog.level']);
     };
     $app['logger'] = $app->share($app->extend('logger', function (Logger $logger, \Pimple $app) {
         $consoleHandler = new ConsoleHandler($app['console.output']);
         if (!class_exists('Symfony\\Bridge\\Monolog\\Handler\\ConsoleHandler')) {
             throw new \Exception('ConsoleLoggerServiceProvider requires symfony/monolog-bridge ~2.4.');
         }
         $consoleHandler->setFormatter(new ConsoleFormatter($app['logger.console_format']));
         $logger->pushHandler($consoleHandler);
         return $logger;
     }));
 }
 /**
  * Registet the serializer and serializer.builder services
  *
  * @throws  ServiceUnavailableHttpException
  *
  * @param   Application $app
  */
 public function register(Application $app)
 {
     $app['serializer.namingStrategy.separator'] = null;
     $app['serializer.namingStrategy.lowerCase'] = null;
     $app['serializer.builder'] = $app->share(function () use($app) {
         $serializerBuilder = SerializerBuilder::create()->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']);
         }
         if ($app->offsetExists('serializer.namingStrategy')) {
             $this->namingStrategy($app, $serializerBuilder);
         }
         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;
     });
     $app['serializer'] = $app->share(function () use($app) {
         return $app['serializer.builder']->build();
     });
 }
Example #26
0
 /**
  * Setups the templates.
  *
  * @param Application $app
  * the Application instance of the Silex application
  */
 protected function setupTemplates(Application $app)
 {
     if ($app->offsetExists('twig.loader.filesystem')) {
         $app['twig.loader.filesystem']->addPath(__DIR__ . '/../views/', 'crud');
     }
     if (!$app->offsetExists('crud.layout')) {
         $app['crud.layout'] = '@crud/layout.twig';
     }
 }
 /**
  * Register the jms/serializer annotations
  *
  * @param Application $app
  */
 public function boot(Application $app)
 {
     if ($app->offsetExists("serializer.srcDir")) {
         AnnotationRegistry::registerAutoloadNamespace("JMS\\Serializer\\Annotation", $app["serializer.srcDir"]);
     }
 }
 /**
  * (register hook)
  *
  * @param \Silex\Application $application
  */
 public function register(Application $application)
 {
     /*
      * Factory Service Manager Closure.
      *
      * @param string $serviceId
      *
      * @return mixed
      */
     $application['service.factory'] = $application->protect(function ($serviceId) use($application) {
         $internalId = strtolower(str_replace(T_NS_SEPARATOR, '', $serviceId));
         if (false === $application->offsetExists($internalId)) {
             if (!isset($application['service_factory'][$serviceId])) {
                 throw new \InvalidArgumentException(sprintf('The service identified by "%s" is not registered', $serviceId));
             }
             $configuration = $application['service_factory'][$serviceId];
             if (!isset($configuration['class'])) {
                 throw new \RuntimeException('Unknown service class option.');
             }
             if (!class_exists($configuration['class'])) {
                 throw new \InvalidArgumentException(sprintf('The service class "%s" is not a part of the current project', $configuration['class']));
             }
             $reflectionClass = new \ReflectionClass($configuration['class']);
             if (isset($configuration['constructor'])) {
                 $params = array();
                 foreach ($configuration['constructor'] as $param) {
                     switch (gettype($param)) {
                         case 'string':
                             $dependency = $this->_guessString($param, $application);
                             break;
                         default:
                             $dependency = $param;
                             break;
                     }
                     $params[] = $dependency;
                 }
                 $service = $reflectionClass->newInstanceArgs($params);
             } else {
                 $service = $reflectionClass->newInstance();
             }
             if (isset($configuration['tags'])) {
                 foreach ($configuration['tags'] as $name => $value) {
                     if (!$reflectionClass->hasMethod($name)) {
                         throw new \UnexpectedValueException(sprintf('"%s" Method is not a part of the class "%s"', $name, $reflectionClass->getShortName()));
                     }
                     switch (gettype($value)) {
                         case 'string':
                             $dependency = $this->_guessString($value, $application);
                             break;
                         case 'array':
                         case 'object':
                             $dependency = $value;
                             break;
                     }
                     $service->{$name}($dependency);
                 }
             }
             $application->offsetSet($internalId, $service);
         }
         return $application[$internalId];
     });
 }
 /**
  * Registers services on the given app.
  *
  * @param Application $app
  */
 public function register(Application $app)
 {
     $app["debesha.doctrine_extra_profiler.logger"] = $app->share(function () use($app) {
         return new HydrationLogger($app->offsetGet("orm.em"));
     });
     $app['debesha.class.hydrationDataCollector'] = 'SilexDoctrineHydrationProfile\\Fix\\DataCollector';
     $app["debesha.doctrine_extra_profiler.data_collector"] = $app->share(function () use($app) {
         $class = $app['debesha.class.hydrationDataCollector'];
         return new $class($app->offsetGet("debesha.doctrine_extra_profiler.logger"));
     });
     if ($app->offsetExists(self::ORM_EM_OPTIONS)) {
         $options = $app->offsetGet(self::ORM_EM_OPTIONS);
     } else {
         $options = array();
     }
     $overwrite = array('class.configuration' => 'SilexDoctrineHydrationProfile\\Fix\\LoggingConfiguration', 'class.entityManager' => 'Debesha\\DoctrineProfileExtraBundle\\ORM\\LoggingEntityManager', 'class.driver.yml' => 'Doctrine\\ORM\\Mapping\\Driver\\YamlDriver', 'class.driver.simple_yml' => 'Doctrine\\ORM\\Mapping\\Driver\\SimplifiedYamlDriver', 'class.driver.xml' => 'Doctrine\\ORM\\Mapping\\Driver\\XmlDriver', 'class.driver.simple_xml' => 'Doctrine\\ORM\\Mapping\\Driver\\SimplifiedXmlDriver', 'class.driver.php' => 'Doctrine\\Common\\Persistence\\Mapping\\Driver\\StaticPHPDriver');
     foreach ($overwrite as $key => $className) {
         if (!isset($options[$key])) {
             $options[$key] = $className;
         }
     }
     $app[self::ORM_EM_OPTIONS] = $options;
     $app['orm.ems'] = $app->share(function ($app) {
         /**
          * @var \Pimple $app
          */
         $app['orm.ems.options.initializer']();
         $ems = new \Pimple();
         foreach ($app['orm.ems.options'] as $name => $options) {
             if ($app['orm.ems.default'] === $name) {
                 // we use shortcuts here in case the default has been overridden
                 $config = $app['orm.em.config'];
             } else {
                 $config = $app['orm.ems.config'][$name];
             }
             $ems[$name] = $app->share(function () use($app, $options, $config) {
                 /**
                  * @var $entityManagerClassName \Doctrine\ORM\EntityManager
                  */
                 $entityManagerClassName = $options['class.entityManager'];
                 return $entityManagerClassName::create($app['dbs'][$options['connection']], $config, $app['dbs.event_manager'][$options['connection']]);
             });
         }
         return $ems;
     });
     $app['orm.ems.config'] = $app->share(function (\Pimple $app) {
         $app['orm.ems.options.initializer']();
         $configs = new \Pimple();
         foreach ($app['orm.ems.options'] as $name => $options) {
             /**
              * @var $config \Doctrine\ORM\Configuration
              */
             $configurationClassName = $options['class.configuration'];
             $config = new $configurationClassName();
             $app['orm.cache.configurer']($name, $config, $options);
             $config->setProxyDir($app['orm.proxies_dir']);
             $config->setProxyNamespace($app['orm.proxies_namespace']);
             $config->setAutoGenerateProxyClasses($app['orm.auto_generate_proxies']);
             $config->setCustomStringFunctions($app['orm.custom.functions.string']);
             $config->setCustomNumericFunctions($app['orm.custom.functions.numeric']);
             $config->setCustomDatetimeFunctions($app['orm.custom.functions.datetime']);
             $config->setCustomHydrationModes($app['orm.custom.hydration_modes']);
             $config->setClassMetadataFactoryName($app['orm.class_metadata_factory_name']);
             $config->setDefaultRepositoryClassName($app['orm.default_repository_class']);
             $config->setEntityListenerResolver($app['orm.entity_listener_resolver']);
             $config->setRepositoryFactory($app['orm.repository_factory']);
             $config->setNamingStrategy($app['orm.strategy.naming']);
             $config->setQuoteStrategy($app['orm.strategy.quote']);
             /**
              * @var \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain $chain
              */
             $chain = $app['orm.mapping_driver_chain.locator']($name);
             foreach ((array) $options['mappings'] as $entity) {
                 if (!is_array($entity)) {
                     throw new \InvalidArgumentException("The 'orm.em.options' option 'mappings' should be an array of arrays.");
                 }
                 if (!empty($entity['resources_namespace'])) {
                     if ($app->offsetExists('psr0_resource_locator')) {
                         $entity['path'] = $app['psr0_resource_locator']->findFirstDirectory($entity['resources_namespace']);
                     } else {
                         throw new \InvalidArgumentException('Not exist psr0_resource_locator');
                     }
                 }
                 if (isset($entity['alias'])) {
                     $config->addEntityNamespace($entity['alias'], $entity['namespace']);
                 }
                 if ('annotation' === $entity['type']) {
                     $useSimpleAnnotationReader = isset($entity['use_simple_annotation_reader']) ? $entity['use_simple_annotation_reader'] : true;
                     $driver = $config->newDefaultAnnotationDriver((array) $entity['path'], $useSimpleAnnotationReader);
                 } else {
                     $driver = $app['orm.driver.factory']($entity, $options);
                 }
                 $chain->addDriver($driver, $entity['namespace']);
             }
             $config->setMetadataDriverImpl($chain);
             foreach ((array) $options['types'] as $typeName => $typeClass) {
                 if (Type::hasType($typeName)) {
                     Type::overrideType($typeName, $typeClass);
                 } else {
                     Type::addType($typeName, $typeClass);
                 }
             }
             $configs[$name] = $config;
         }
         return $configs;
     });
     $app['orm.driver.factory'] = $app->share(function () {
         $simpleList = array('simple_yml', 'simple_xml');
         return function ($entity, $options) use($simpleList) {
             if (isset($options['class.driver.' . $entity['type']])) {
                 $className = $options['class.driver.' . $entity['type']];
                 if (in_array($entity['type'], $simpleList)) {
                     $param = array($entity['path'] => $entity['namespace']);
                 } else {
                     $param = $entity['path'];
                 }
                 return new $className($param);
             }
             throw new \InvalidArgumentException(sprintf('"%s" is not a recognized driver', $entity['type']));
         };
     });
 }
Example #30
0
 public function offsetExists($id)
 {
     return parent::offsetExists($id) || $this->phpdi->has($id);
 }