private function createContainer(array $definitions = []) { $builder = new ContainerBuilder(); $builder->addDefinitions(__DIR__ . '/../../res/config/config.php'); $builder->addDefinitions([ContainerInterface::class => get(Container::class), Twig_LoaderInterface::class => object(Twig_Loader_Array::class)->constructor([]), ResourceRepository::class => object(NullRepository::class)]); $builder->addDefinitions($definitions); return $builder->build(); }
/** * Initial setup of DI\ContainerBuilder. * * @param bool $annotation annotation usage. * * @return DI\ContainerBuilder */ protected static function initialSetupContainerBuilder($annotation) { $builder = new DI\ContainerBuilder(); $builder->useAnnotations($annotation); $builder->addDefinitions(['request' => ServerRequestFactory::fromGlobals(), 'response' => DI\object(Response::class), 'http_flow_event' => DI\object(ZendHttpFlowEvent::class)->constructor('bootstrap', DI\get('request'), DI\get('response')), 'event_manager' => DI\object(ZendEvmProxy::class), 'dispatcher' => DI\factory(function ($container) { return new Dispatcher($container->get('router'), $container); })]); return $builder; }
/** * Container compilation. * * @param mixed $config Configuration file/array. * * @link http://php-di.org/doc/php-definitions.html * * @return ContainerInterface */ public static function buildContainer($config = []) { $builder = new DI\ContainerBuilder(); $builder->useAnnotations(true); $builder->addDefinitions(['request' => \Zend\Diactoros\ServerRequestFactory::fromGlobals(), 'response' => DI\object('Zend\\Diactoros\\Response'), 'http_flow_event' => DI\object('Penny\\Event\\HttpFlowEvent')->constructor('bootstrap', DI\get('request'), DI\get('response')), 'event_manager' => DI\object('Zend\\EventManager\\EventManager'), 'dispatcher' => DI\factory(function ($container) { return new \Penny\Dispatcher($container->get('router'), $container); })]); $builder->addDefinitions($config); $container = $builder->build(); $container->set('di', $container); return $container; }
/** * Application initialization. * * @param mixed $router Routing system. * @param ContainerInterface $container Dependency Injection container. */ public function __construct($router = null, ContainerInterface $container = null) { $this->container = $container ?: $this->buildContainer(Loader::load()); $container =& $this->container; $this->response = new Response(); $this->request = ServerRequestFactory::fromGlobals(); if ($router == null && $container->has('router') == false) { throw new Exception('Define router config'); } if ($container->has('router') == false) { $container->set('router', $router); } $container->set('event_manager', DI\object('Zend\\EventManager\\EventManager')); $container->set('dispatcher', DI\object('GianArb\\Penny\\Dispatcher')->constructor($container->get('router'))); $container->set('di', $container); }
/** * @param array $list * @param string|array|DefinitionSource $definitions Can be an array of definitions, the * name of a file containing definitions * or a DefinitionSource object. * @param bool $test_mode * @throws InvalidListException * @throws \Exception */ function compose(array $list, $definitions = [], $test_mode = false) { validate($list); $to_cleanup = []; /** @var \DI\Container $container */ $container = (new ContainerBuilder())->addDefinitions($definitions)->build(); try { foreach ($list as $name => $block) { $container->set(Values::class, object()->constructor($list)); echo $name . PHP_EOL; $list[$name]['value'] = $container->call($list[$name]['action']); if (isset($list[$name]['cleanup'])) { $to_cleanup[] = $list[$name]['cleanup']; } else { $to_cleanup[] = function () { }; } } /** * Force cleanup on all actions */ if ($test_mode) { throw new TestModeException(); } } catch (\Exception $e) { /** * Call all previous action cleanups */ array_map(function ($cleanup) use($list, $container) { $container->set(Values::class, object()->constructor($list)); $container->call($cleanup); }, array_reverse($to_cleanup)); /** * We want the exception if not a TestModeException, * but want to exit if test mode */ if ($e instanceof TestModeException) { echo "--- Test Mode Ended Successfully ---\n"; return; } throw $e; } }
<?php namespace CASS\Domain\Bundles\Theme; use DI\Container; use function DI\object; use function DI\factory; use function DI\get; use CASS\Application\Bundles\Doctrine2\Factory\DoctrineRepositoryFactory; use CASS\Domain\Bundles\Theme\Entity\Theme; use CASS\Domain\Bundles\Theme\Frontline\ThemeScript; use CASS\Domain\Bundles\Theme\Repository\ThemeRepository; use CASS\Domain\Bundles\Theme\Service\ThemeService; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use League\Flysystem\Memory\MemoryAdapter; return ['php-di' => ['config.paths.theme.preview.www' => factory(function (Container $container) { return sprintf('%s/entity/themes/preview', $container->get('config.storage.www')); }), 'config.paths.theme.preview.dir' => factory(function (Container $container) { return sprintf('%s/entity/themes/preview/', $container->get('config.storage.dir')); }), ThemeScript::class => object()->constructorParameter('wwwStorage', factory(function (Container $container) { return $container->get('config.paths.theme.preview.www'); })), ThemeRepository::class => factory(new DoctrineRepositoryFactory(Theme::class)), ThemeService::class => object()->constructorParameter('fileSystem', factory(function (Container $container) { $env = $container->get('config.env'); $path = $container->get('config.paths.theme.preview.dir'); if ($env === 'test') { return new Filesystem(new MemoryAdapter($path)); } else { return new Filesystem(new Local($path)); } }))]];
foreach ($routes as $routeName => $route) { $router->add($routeName, $route['pattern'])->addValues(['controller' => $route['controller']]); } return $router; }), LoggerInterface::class => factory(function (ContainerInterface $c) { $logger = new Logger('main'); $file = $c->get('directory.logs') . '/app.log'; $logger->pushHandler(new StreamHandler($file, Logger::WARNING)); return $logger; }), Poser::class => object()->constructor(link(SvgFlatRender::class)), Twig_Environment::class => factory(function (ContainerInterface $c) { $loader = new Twig_Loader_Filesystem(__DIR__ . '/../../src/Maintained/Application/View'); $twig = new Twig_Environment($loader); $twig->addExtension($c->get(TwigExtension::class)); $twig->addExtension($c->get(PiwikTwigExtension::class)); return $twig; }), PiwikTwigExtension::class => object()->constructor(link('piwik.host'), link('piwik.site_id'), link('piwik.enabled')), Cache::class => factory(function (ContainerInterface $c) { $cache = new FilesystemCache($c->get('directory.cache') . '/app'); $cache->setNamespace('Maintained'); return $cache; }), 'storage.repositories' => factory(function (ContainerInterface $c) { $backend = new StorageWithTransformers(new FileStorage($c->get('directory.data') . '/repositories.json')); $backend->addTransformer(new JsonEncoder(true)); $storage = new MapWithTransformers(new MapAdapter($backend)); $storage->addTransformer(new ObjectArrayMapper(Repository::class)); return $storage; }), 'storage.statistics' => factory(function (ContainerInterface $c) { $storage = new MapWithTransformers(new MultipleFileStorage($c->get('directory.data') . '/statistics')); $storage->addTransformer(new PhpSerializeEncoder()); return $storage; }), Client::class => factory(function (ContainerInterface $c) { $cacheDirectory = $c->get('directory.cache') . '/github';
<?php namespace CASS\Application; use function DI\object; use function DI\factory; use function DI\get; use DI\Container; use Evenement\EventEmitter; use Intervention\Image\ImageManager; return ['php-di' => ['composer.json' => factory(function (Container $container) { return json_decode(file_get_contents(sprintf('%s/composer.json', $container->get('paths')['backend'])), true); }), 'paths' => ['backend' => sprintf('%s/../../../', __DIR__), 'frontend' => sprintf('%s/../../../../frontend', __DIR__), 'www' => sprintf('%s/../../../../www/app', __DIR__)], 'config.version.current' => factory(function (Container $container) { return $container->get('composer.json')['version']; }), 'config.storage.dir' => '/data/storage', 'config.storage.www' => '/storage', 'config.routes_group' => ['auth', 'with-profile', 'common', 'final'], ImageManager::class => factory(function (Container $container) { return new ImageManager(['driver' => 'gd']); }), EventEmitter::class => object()]];
<?php use DI\Container; use Interop\Container\ContainerInterface; use Puli\Discovery\Api\Discovery; use Puli\UrlGenerator\Api\UrlGenerator; use Stratify\Framework\Middleware\ContainerBasedInvoker; use Zend\Diactoros\Response\EmitterInterface; use Zend\Diactoros\Response\SapiEmitter; use function DI\get; use function DI\object; return [\Stratify\Http\Application::class => object()->constructor(get('http'), get('middleware_invoker'), get(EmitterInterface::class)), \Silly\Application::class => object()->method('useContainer', get(Container::class), true, true), 'http' => function () { throw new Exception('No HTTP stack was defined'); }, ContainerInterface::class => get(Container::class), EmitterInterface::class => get(SapiEmitter::class), 'middleware_invoker' => get(ContainerBasedInvoker::class), UrlGenerator::class => function (ContainerInterface $c) { $puli = $c->get('puli.factory'); return $puli->createUrlGenerator($c->get(Discovery::class)); }];
$hbs->addHelper('count', function (HbsTemplate $template, HbsContext $context, $args, $source) { return count($context->get($args)); }); $hbs->addHelper('join', function (HbsTemplate $template, HbsContext $context, $args, $source) { $matches = []; if (preg_match("#'([^']+)' (.+)#", $args, $matches)) { list(, $separator, $input) = $matches; $out = []; foreach ((array) $context->get($input) as $value) { $context->push($value); $out[] = $template->render($context); $context->pop(); } return implode($separator, $out); } return ''; }); return $hbs; }), 'Bigwhoop\\Trumpet\\Commands\\CommandExecutionContext' => DI\object(), 'Bigwhoop\\Trumpet\\Commands\\CommandHandler' => DI\factory(function (DIC $c) { $handler = new CommandHandler(); $handler->registerCommand($c->get('Bigwhoop\\Trumpet\\Commands\\CodeCommand')); $handler->registerCommand($c->get('Bigwhoop\\Trumpet\\Commands\\ExecCommand')); $handler->registerCommand($c->get('Bigwhoop\\Trumpet\\Commands\\IncludeCommand')); $handler->registerCommand($c->get('Bigwhoop\\Trumpet\\Commands\\ImageCommand')); $handler->registerCommand($c->get('Bigwhoop\\Trumpet\\Commands\\WikiCommand')); return $handler; }), 'PhpParser\\PrettyPrinterAbstract' => DI\object('\\PhpParser\\PrettyPrinter\\Standard'), 'PhpParser\\Lexer' => DI\object('PhpParser\\Lexer\\Emulative'), 'PhpParser\\ParserAbstract' => DI\object('PhpParser\\Parser')->constructor(DI\link('PhpParser\\Lexer')), 'PhpParser\\NodeTraverserInterface' => DI\object('PhpParser\\NodeTraverser')->method('addVisitor', DI\link('PhpParser\\NodeVisitor\\NameResolver'))]; $builder = new DI\ContainerBuilder(); $builder->addDefinitions(new DI\Definition\Source\ArrayDefinitionSource($definitions)); //$builder->useAnnotations(false); return $builder->build();
}))]]; $configTest = ['php-di' => [ProfileService::class => object()->constructorParameter('wwwImagesDir', factory(function (Container $container) { return $container->get('config.paths.profile.avatar.www'); }))->constructorParameter('imagesFlySystem', factory(function (Container $container) { return new Filesystem(new MemoryAdapter($container->get('config.paths.profile.avatar.dir'))); }))]]; return ['php-di' => ['config.paths.profile.backdrop.presets.json' => factory(function (Container $container) { return json_decode(file_get_contents(sprintf('%s/presets/profile/presets.json', $container->get('config.storage.dir'))), true); }), 'config.paths.profile.avatar.dir' => factory(function (Container $container) { return sprintf('%s/entity/profile/by-sid/avatar/', $container->get('config.storage.dir')); }), 'config.paths.profile.avatar.www' => factory(function (Container $container) { return sprintf('%s/entity/profile/by-sid/avatar/', $container->get('config.storage.www')); }), 'config.paths.profile.backdrop.dir' => factory(function (Container $container) { return sprintf('%s/entity/profile/by-sid/backdrop', $container->get('config.storage.dir')); }), 'config.paths.profile.backdrop.www' => factory(function (Container $container) { return sprintf('%s/entity/profile/by-sid/backdrop', $container->get('config.storage.www')); }), ProfileRepository::class => factory(new DoctrineRepositoryFactory(Profile::class)), ProfileExpertInEQRepository::class => factory(new DoctrineRepositoryFactory(ProfileExpertInEQ::class)), ProfileInterestingInEQRepository::class => factory(new DoctrineRepositoryFactory(ProfileInterestingInEQ::class)), ProfileBackdropPresetFactory::class => object()->constructorParameter('json', factory(function (Container $container) { return $container->get('config.paths.profile.backdrop.presets.json'); })), ProfileBackdropUploadStrategyFactory::class => object()->constructorParameter('wwwPath', factory(function (Container $container) { return $container->get('config.paths.profile.backdrop.www'); }))->constructorParameter('storagePath', factory(function (Container $container) { return $container->get('config.paths.profile.backdrop.dir'); }))->constructorParameter('fileSystem', factory(function (Container $container) { $env = $container->get('config.env'); $dir = $container->get('config.paths.profile.backdrop.dir'); if ($env === 'test') { return new Filesystem(new MemoryAdapter($dir)); } else { return new Filesystem(new Local($dir)); } }))], 'env' => ['development' => $configDefault, 'production' => $configDefault, 'stage' => $configDefault, 'test' => $configTest]];
use PhpSchool\LearnYouPhp\Exercise\ArrayWeGo; use PhpSchool\LearnYouPhp\Exercise\BabySteps; use PhpSchool\LearnYouPhp\Exercise\ConcernedAboutSeparation; use PhpSchool\LearnYouPhp\Exercise\DatabaseRead; use PhpSchool\LearnYouPhp\Exercise\ExceptionalCoding; use PhpSchool\LearnYouPhp\Exercise\FilteredLs; use PhpSchool\LearnYouPhp\Exercise\HelloWorld; use PhpSchool\LearnYouPhp\Exercise\HttpJsonApi; use PhpSchool\LearnYouPhp\Exercise\MyFirstIo; use PhpSchool\LearnYouPhp\Exercise\TimeServer; use PhpSchool\LearnYouPhp\Exercise\DependencyHeaven; use PhpSchool\LearnYouPhp\TcpSocketFactory; use PhpSchool\PhpWorkshop\Event\Event; use Symfony\Component\Filesystem\Filesystem; use Faker\Factory as FakerFactory; return [BabySteps::class => object(BabySteps::class), HelloWorld::class => object(HelloWorld::class), HttpJsonApi::class => object(HttpJsonApi::class), MyFirstIo::class => factory(function (ContainerInterface $c) { return new MyFirstIo($c->get(Filesystem::class), FakerFactory::create()); }), FilteredLs::class => factory(function (ContainerInterface $c) { return new FilteredLs($c->get(Filesystem::class)); }), ConcernedAboutSeparation::class => factory(function (ContainerInterface $c) { return new ConcernedAboutSeparation($c->get(Filesystem::class), FakerFactory::create(), $c->get(Parser::class)); }), ArrayWeGo::class => factory(function (ContainerInterface $c) { return new ArrayWeGo($c->get(Filesystem::class), FakerFactory::create()); }), ExceptionalCoding::class => factory(function (ContainerInterface $c) { return new ExceptionalCoding($c->get(Filesystem::class), FakerFactory::create()); }), DatabaseRead::class => factory(function (ContainerInterface $c) { return new DatabaseRead(FakerFactory::create()); }), TimeServer::class => factory(function (ContainerInterface $c) { return new TimeServer(new TcpSocketFactory()); }), DependencyHeaven::class => factory(function (ContainerInterface $c) { return new DependencyHeaven(FakerFactory::create('fr_FR'));
<?php use Slim\HttpCache\Cache; use function DI\env; use function DI\get; use function DI\object; return [Cache::class => object(Cache::class)->constructorParameter('type', env('HTTP_CACHE_TYPE', 'public'))->constructorParameter('maxAge', env('HTTP_CACHE_MAX_AGE', 315360000))];
use CASS\Domain\Bundles\Attachment\Service\AttachmentPreviewService; use function DI\object; use function DI\factory; use function DI\get; use DI\Container; use CASS\Application\Bundles\Doctrine2\Factory\DoctrineRepositoryFactory; use CASS\Domain\Bundles\Attachment\Entity\Attachment; use CASS\Domain\Bundles\Attachment\Repository\AttachmentRepository; use CASS\Domain\Bundles\Attachment\Service\AttachmentService; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; use League\Flysystem\Memory\MemoryAdapter; return ['php-di' => ['config.paths.attachment.dir' => factory(function (Container $container) { return sprintf('%s/entity/attachment', $container->get('config.storage.dir')); }), 'config.paths.attachment.www' => factory(function (Container $container) { return sprintf('%s/entity/attachment', $container->get('config.storage.www')); }), AttachmentRepository::class => factory(new DoctrineRepositoryFactory(Attachment::class)), AttachmentService::class => object()->constructorParameter('wwwDir', factory(function (Container $container) { return $container->get('config.paths.attachment.www'); }))->constructorParameter('generatePreviews', factory(function (Container $container) { return $container->get('config.env') !== 'test'; }))->constructorParameter('fileSystem', factory(function (Container $container) { $env = $container->get('config.env'); if ($env === 'test') { return new Filesystem(new MemoryAdapter()); } else { return new Filesystem(new Local($container->get('config.paths.attachment.dir'))); } })), AttachmentPreviewService::class => object()->constructorParameter('attachmentsRealPath', factory(function (Container $container) { return $container->get('config.paths.attachment.dir'); }))]];
<?php use livetyping\hermitage\app\signer\Signer; use function DI\env; use function DI\get; use function DI\object; return ['signer' => object(Signer::class)->constructor(env('SIGNER_ALGORITHM', 'sha256')), Signer::class => get('signer')];
<?php use livetyping\hermitage\app\middleware\Authenticate; use function DI\env; use function DI\get; use function DI\object; return [Authenticate::class => object(Authenticate::class)->constructorParameter('secret', env('AUTH_SECRET'))->constructorParameter('timestampExpires', env('AUTH_TIMESTAMP_EXPIRES', 120))];
<?php namespace CASS\Domain\Bundles\Colors; use function DI\object; use function DI\factory; use function DI\get; use DI\Container; use CASS\Application\Service\BundleService; use CASS\Domain\Bundles\Avatar\Service\AvatarService; use CASS\Domain\Bundles\Avatar\Service\Strategy\FileAvatarStrategy; use CASS\Domain\Bundles\Avatar\Service\Strategy\MockAvatarStrategy; use CASS\Domain\DomainBundle; $configDefault = ['php-di' => [AvatarService::class => object()->constructorParameter('strategy', get(FileAvatarStrategy::class))]]; $configMock = ['php-di' => [AvatarService::class => object()->constructorParameter('strategy', get(MockAvatarStrategy::class))]]; return ['php-di' => [FileAvatarStrategy::class => object()->constructorParameter('fontPath', factory(function (Container $container) { $domainBundle = $container->get(BundleService::class)->getBundleByName(DomainBundle::class); /** @var DomainBundle $domainBundle */ return sprintf('%s/fonts/Roboto/Roboto-Medium.ttf', $domainBundle->getResourcesDir()); }))], 'env' => ['development' => $configDefault, 'production' => $configDefault, 'stage' => $configDefault, 'test' => $configMock]];
<?php use Acme\Controller\HomeController; use function DI\object; return [HomeController::class => object()];
<?php use Bamf\Middleware\ControllerMiddleware; use DI\Container; use function DI\object; use function DI\get; return [ControllerMiddleware::class => object()->constructor(get(Container::class))];
<?php use PHPFramework\Example\UserController; use PHPFramework\Impl\EventSystem\EventManager; use function DI\object; /* * Add your event-listener here * @see http://php-di.org/doc/ */ return [EventManager::DI_EVENT_LISTENER_KEY => [object(UserController::class)]];
<?php use GuzzleHttp\Psr7\ServerRequest; use Interop\Container\ContainerInterface; use League\Plates; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; use TimTegeler\Routerunner\Routerunner; use function DI\factory; use function DI\object; return [Routerunner::class => function (ContainerInterface $container) { return new Routerunner('Creios\\Creiwork\\Controller', $container); }, Plates\Engine::class => object()->constructor(__DIR__ . '/../template'), LoggerInterface::class => function (\Monolog\Handler\StreamHandler $streamHandler) { $logger = new \Monolog\Logger('Creiwork'); $logger->pushHandler($streamHandler); return $logger; }, \Monolog\Handler\StreamHandler::class => object()->constructor(__DIR__ . '/../log/test.log', \Monolog\Logger::INFO), ServerRequestInterface::class => factory([ServerRequest::class, 'fromGlobals'])];
<?php namespace ZEA2\Platform\Bundles\Swagger; use function DI\object; use function DI\factory; use function DI\get; use DI\Container; use ZEA2\Platform\Bundles\Swagger\Service\APIDocsService; return ['php-di' => [APIDocsService::class => object()->constructorParameter('excludedBundles', factory(function (Container $container) : array { if ($container->has('config.api-docs.excluded-bundles')) { return $container->get('config.api-docs.excluded-bundles'); } else { return []; } }))]];
<?php namespace CASS\Domain\Bundles\Auth; use function DI\object; use function DI\factory; use function DI\get; use CASS\Domain\Bundles\Auth\Middleware\AuthMiddleware; use CASS\Application\Bundles\Frontline\Service\FrontlineService; $config = ['php-di' => []]; foreach (AuthMiddleware::OAUTH2_PROVIDERS as $provider => $commandClassName) { $config['php-di'][$commandClassName] = object()->constructorParameter('oauth2Config', get(sprintf('config.oauth2.%s', $provider))); } return $config;
}, CodePatcher::class => function (ContainerInterface $c) { $patch = (new Patch())->withInsertion(new Insertion(Insertion::TYPE_BEFORE, 'ini_set("display_errors", 1);'))->withInsertion(new Insertion(Insertion::TYPE_BEFORE, 'error_reporting(E_ALL);'))->withInsertion(new Insertion(Insertion::TYPE_BEFORE, 'date_default_timezone_set("Europe/London");')); return new CodePatcher($c->get(Parser::class), new Standard(), $patch); }, FakerGenerator::class => function () { return FakerFactory::create(); }, RequestRenderer::class => object(), TerminalInterface::class => factory([TerminalFactory::class, 'fromSystem']), 'menu' => factory(MenuFactory::class), MenuFactory::class => object(), ExerciseRenderer::class => function (ContainerInterface $c) { return new ExerciseRenderer($c->get('appName'), $c->get(ExerciseRepository::class), $c->get(UserState::class), $c->get(UserStateSerializer::class), $c->get(MarkdownRenderer::class), $c->get(Color::class), $c->get(OutputInterface::class)); }, MarkdownRenderer::class => function (ContainerInterface $c) { $docParser = new DocParser(Environment::createCommonMarkEnvironment()); $cliRenderer = (new MarkdownCliRendererFactory())->__invoke($c); return new MarkdownRenderer($docParser, $cliRenderer); }, UserStateSerializer::class => function (ContainerInterface $c) { return new UserStateSerializer(getenv('HOME'), $c->get('workshopTitle'), $c->get(ExerciseRepository::class)); }, UserState::class => function (ContainerInterface $c) { return $c->get(UserStateSerializer::class)->deSerialize(); }, SyntaxHighlighter::class => factory(PsxFactory::class), PsxFactory::class => object(), ResetProgress::class => function (ContainerInterface $c) { return new ResetProgress($c->get(UserStateSerializer::class)); }, ResultRendererFactory::class => function (ContainerInterface $c) { $factory = new ResultRendererFactory(); $factory->registerRenderer(FunctionRequirementsFailure::class, FunctionRequirementsFailureRenderer::class); $factory->registerRenderer(Failure::class, FailureRenderer::class); $factory->registerRenderer(CgiResult::class, CgiResultRenderer::class, function (CgiResult $result) use($c) { return new CgiResultRenderer($result, $c->get(RequestRenderer::class)); }); $factory->registerRenderer(CgiGenericFailure::class, FailureRenderer::class); $factory->registerRenderer(CgiRequestFailure::class, CgiRequestFailureRenderer::class); $factory->registerRenderer(CliResult::class, CliResultRenderer::class); $factory->registerRenderer(CliGenericFailure::class, FailureRenderer::class); $factory->registerRenderer(CliRequestFailure::class, CliRequestFailureRenderer::class); $factory->registerRenderer(ComparisonFailure::class, ComparisonFailureRenderer::class); return $factory;
use PHPFramework\Impl\ResponseWriter\CORSResponseHeaderModifierInterface; use PHPFramework\Impl\ResponseWriter\JsonContentTypeHeaderModifier; use PHPFramework\Impl\ResponseWriter\JsonResponseContentWriter; use PHPFramework\Impl\ResponseWriter\ResponseHeaderWriter; use PHPFramework\Impl\ResponseWriter\ResponseStatusCodeWriter; use PHPFramework\Impl\ResponseWriter\ResponseWriter; use PHPFramework\Impl\Routing\FastRouteRouter; use function DI\factory; use function DI\get; use function DI\object; use function FastRoute\simpleDispatcher; /* * @see http://php-di.org/doc/ */ return [StringUtilityInterface::class => object(StringUtility::class), SerializerInterface::class => function (ContainerInterface $c) { return SerializerBuilder::create()->build(); }, ExceptionSanitizerInterface::class => object(ExceptionSanitizer::class), ExceptionHandlerInterface::class => object(ExceptionHandler::class), CORSResponseHeaderModifierInterface::class => object(CORSResponseHeaderModifier::class), ContentTypeHeaderModifierInterface::class => object(JsonContentTypeHeaderModifier::class), ResponseWriter::DI_RESPONSE_HEADER_MODIFIER_KEY => [get(CORSResponseHeaderModifierInterface::class), get(ContentTypeHeaderModifierInterface::class)], ResponseContentWriterInterface::class => object(JsonResponseContentWriter::class), ResponseHeaderWriterInterface::class => object(ResponseHeaderWriter::class), ResponseStatusCodeWriterInterface::class => object(ResponseStatusCodeWriter::class), ResponseWriterInterface::class => object(ResponseWriter::class)->constructorParameter('responseHeaderModifier', get(ResponseWriter::DI_RESPONSE_HEADER_MODIFIER_KEY)), Dispatcher::class => function (ContainerInterface $c) { return simpleDispatcher(function (RouteCollector $r) use($c) { $routesConfig = $c->get(FastRouteRouter::DI_ROUTE_CONFIG_KEY); foreach ($routesConfig as $routeConfig) { /** @var string $method */ $method = $routeConfig[0]; /** @var string $regex */ $regex = $routeConfig[1]; /** @var string $eventClass */ $eventClass = $routeConfig[2]; $r->addRoute($method, $regex, $eventClass); } }); }, RouterInterface::class => object(FastRouteRouter::class), UrlInterface::class => object(Url::class)->scope(Scope::PROTOTYPE), RequestUrlReaderInterface::class => object(RequestUrlReader::class), RequestMethodReaderInterface::class => object(RequestMethodReader::class), HeaderCollectionInterface::class => object(HeaderCollection::class)->scope(Scope::PROTOTYPE), RequestHeaderReaderInterface::class => object(RequestHeaderReader::class), RequestContentDeserializerInterface::class => object(RequestContentDeserializer::class), RequestContentInterface::class => object(RequestContent::class)->scope(Scope::PROTOTYPE), RequestContentReaderInterface::class => object(RequestContentReader::class), RouteParameterCollectionInterface::class => object(RouteParameterCollection::class)->scope(Scope::PROTOTYPE), RequestInterface::class => object(Request::class)->scope(Scope::PROTOTYPE), RequestReaderInterface::class => object(RequestReader::class), AppInterface::class => object(App::class), EventManagerInterface::class => object(EventManager::class)->constructorParameter('eventListener', get(EventManager::DI_EVENT_LISTENER_KEY))];
<?php use Puli\Repository\Api\ResourceRepository; use Puli\TwigExtension\PuliExtension; use Puli\TwigExtension\PuliTemplateLoader; use Puli\UrlGenerator\Api\UrlGenerator; use Stratify\TwigModule\Extension\StratifyExtension; use function DI\add; use function DI\get; use function DI\object; return ['twig.options' => [], 'twig.globals' => [], 'twig.extensions' => add([get(Twig_Extension_Debug::class), get(PuliExtension::class), get(StratifyExtension::class)]), Twig_Environment::class => object()->constructor(get(Twig_LoaderInterface::class), get('twig.options'))->method('setExtensions', get('twig.extensions')), Twig_LoaderInterface::class => object(PuliTemplateLoader::class), PuliExtension::class => object()->constructor(get(ResourceRepository::class), get(UrlGenerator::class))];
<?php use DI\Bridge\Slim\CallableResolver; use DI\Bridge\Slim\ControllerInvoker; use DI\Container; use DI\Scope; use Interop\Container\ContainerInterface; use Invoker\Invoker; use Invoker\ParameterResolver\AssociativeArrayResolver; use Invoker\ParameterResolver\Container\TypeHintContainerResolver; use Invoker\ParameterResolver\ResolverChain; use Slim\Http\Headers; use Slim\Http\Request; use Slim\Http\Response; use function DI\factory; use function DI\get; use function DI\object; return ['settings.httpVersion' => '1.1', 'settings.responseChunkSize' => 4096, 'settings.outputBuffering' => 'append', 'settings.determineRouteBeforeAppMiddleware' => false, 'settings.displayErrorDetails' => false, 'settings' => ['httpVersion' => get('settings.httpVersion'), 'responseChunkSize' => get('settings.responseChunkSize'), 'outputBuffering' => get('settings.outputBuffering'), 'determineRouteBeforeAppMiddleware' => get('settings.determineRouteBeforeAppMiddleware'), 'displayErrorDetails' => get('settings.displayErrorDetails')], 'router' => object(Slim\Router::class), 'errorHandler' => object(Slim\Handlers\Error::class)->constructor(get('settings.displayErrorDetails')), 'notFoundHandler' => object(Slim\Handlers\NotFound::class), 'notAllowedHandler' => object(Slim\Handlers\NotAllowed::class), 'environment' => function () { return new Slim\Http\Environment($_SERVER); }, 'request' => factory(function (ContainerInterface $c) { return Request::createFromEnvironment($c->get('environment')); })->scope(Scope::SINGLETON), 'response' => factory(function (ContainerInterface $c) { $headers = new Headers(['Content-Type' => 'text/html; charset=UTF-8']); $response = new Response(200, $headers); return $response->withProtocolVersion($c->get('settings')['httpVersion']); })->scope(Scope::SINGLETON), 'foundHandler' => object(ControllerInvoker::class)->constructor(get('foundHandler.invoker')), 'foundHandler.invoker' => function (ContainerInterface $c) { $resolvers = [new AssociativeArrayResolver(), new TypeHintContainerResolver($c)]; return new Invoker(new ResolverChain($resolvers), $c); }, 'callableResolver' => object(CallableResolver::class), ContainerInterface::class => get(Container::class)];
<?php use Maintained\Application\Command\ClearCacheCommand; use Maintained\Application\Command\ShowStatisticsCommand; use Maintained\Application\Command\UpdateStatisticsCommand; use Maintained\Application\Command\WarmupCacheCommand; use Maintained\Statistics\CachedStatisticsProvider; use Maintained\Statistics\StatisticsComputer; use Maintained\Statistics\StatisticsProvider; use Maintained\Statistics\StatisticsProviderLogger; use function DI\factory; use function DI\link; use function DI\object; return ['baseUrl' => 'http://isitmaintained.com', 'maintenance' => false, 'directory.cache' => __DIR__ . '/../../app/cache', 'directory.data' => __DIR__ . '/../../app/data', 'directory.logs' => __DIR__ . '/../../app/logs', 'routes' => require __DIR__ . '/routes.php', 'piwik.enabled' => false, 'piwik.host' => null, 'piwik.site_id' => null, 'github.auth_token' => null, StatisticsProvider::class => link(CachedStatisticsProvider::class), CachedStatisticsProvider::class => object()->constructorParameter('cache', link('storage.statistics'))->constructorParameter('wrapped', link(StatisticsProviderLogger::class)), StatisticsProviderLogger::class => object()->constructorParameter('wrapped', link(StatisticsComputer::class))->constructorParameter('repositoryStorage', link('storage.repositories')), ClearCacheCommand::class => object()->constructorParameter('cacheDirectory', link('directory.cache'))->constructorParameter('dataDirectory', link('directory.data')), ShowStatisticsCommand::class => object(), WarmupCacheCommand::class => object()->constructorParameter('repositoryStorage', link('storage.repositories')), UpdateStatisticsCommand::class => object()->constructorParameter('repositoryStorage', link('storage.repositories'))->constructorParameter('statisticsCache', link('storage.statistics'))];
use SimpleBus\Message\CallableResolver\CallableMap; use SimpleBus\Message\CallableResolver\CallableResolver; use SimpleBus\Message\CallableResolver\ServiceLocatorAwareCallableResolver; use SimpleBus\Message\Handler\DelegatesToMessageHandlerMiddleware; use SimpleBus\Message\Handler\Resolver\MessageHandlerResolver; use SimpleBus\Message\Handler\Resolver\NameBasedMessageHandlerResolver; use SimpleBus\Message\Name\ClassBasedNameResolver; use SimpleBus\Message\Name\MessageNameResolver; use Zend\Diactoros\Response\EmitterInterface; use Zend\Diactoros\Response\SapiEmitter; use Zend\Diactoros\ServerRequestFactory; use function DI\get; use function DI\object; use function FastRoute\simpleDispatcher; return [DiKey::SERVICE_LOCATOR => function (ContainerInterface $c) { return function ($serviceId) use($c) { return $c->get($serviceId); }; }, CallableResolver::class => object(ServiceLocatorAwareCallableResolver::class)->constructorParameter('serviceLocator', get(DiKey::SERVICE_LOCATOR)), CallableMap::class => object(CallableMap::class)->constructorParameter('callablesByName', get(DiKey::COMMAND_TO_HANDLER_MAPPING)), MessageNameResolver::class => object(ClassBasedNameResolver::class), MessageHandlerResolver::class => object(NameBasedMessageHandlerResolver::class), FinishesHandlingMessageBeforeHandlingNext::class => object(FinishesHandlingMessageBeforeHandlingNext::class), DelegatesToMessageHandlerMiddleware::class => object(DelegatesToMessageHandlerMiddleware::class), DiKey::COMMAND_BUS_MIDDLEWARES => [get(FinishesHandlingMessageBeforeHandlingNext::class), get(DelegatesToMessageHandlerMiddleware::class)], DiKey::COMMAND_BUS => object(MessageBusSupportingMiddleware::class)->constructorParameter('middlewares', get(DiKey::COMMAND_BUS_MIDDLEWARES)), Dispatcher::class => function (ContainerInterface $c) { return simpleDispatcher(function (RouteCollector $r) use($c) { $routesConfig = $c->get(DiKey::ROUTE_TO_COMMAND_CREATOR_MAPPING); foreach ($routesConfig as $routeConfig) { $r->addRoute($routeConfig[0], $routeConfig[1], $routeConfig[2]); } }); }, RouterInterface::class => object(FastRouteRouter::class)->constructorParameter('serviceLocator', get(DiKey::SERVICE_LOCATOR)), ServerRequestInterface::class => function () { return ServerRequestFactory::fromGlobals(); }, RequestKnowledge::class => object(RequestKnowledge::class), SerializerInterface::class => function () { return SerializerBuilder::create()->build(); }, DiKey::RESPONSE_MODIFIERS => [], ResponderInterface::class => object(Responder::class)->constructorParameter('responseModifiers', get(DiKey::RESPONSE_MODIFIERS)), EmitterInterface::class => object(SapiEmitter::class), RequestBodyParserInterface::class => object(RequestBodyParser::class), HttpExceptionHandlerInterface::class => object(GenericHttpExceptionHandler::class), AppInterface::class => object(App::class)->constructorParameter('commandBus', get(DiKey::COMMAND_BUS))];
/** * bind to a class, such as an interface to an implementation of that interface * @param string $class name of the class to bind to * @return InjectorBuilder */ public function toClass($class) { return $this->bind(object($class)); }