public function addToInjector(Injector $injector) { foreach ($this->shares as $share) { $injector->share($share); } foreach ($this->aliases as $original => $alias) { $injector->alias($original, $alias); } foreach ($this->definitions as $name => $args) { $injector->define($name, $args); } foreach ($this->params as $param => $value) { $injector->defineParam($param, $value); } foreach ($this->delegates as $param => $callable) { $injector->delegate($param, $callable); } foreach ($this->prepares as $class => $callable) { $injector->prepare($class, $callable); } }
/** * * {@inheritDoc} * * @see \Spark\Configuration\ConfigurationInterface::apply() */ public function apply(Injector $injector) { $injector->alias(ExtractorInterface::class, HeaderExtractor::class); $injector->define(HeaderExtractor::class, [':header' => 'token']); $injector->alias(\Spark\Auth\Credentials\ExtractorInterface::class, BodyExtractor::class); $injector->alias(AdapterInterface::class, AuthAdapter::class); }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias(RequestInterface::class, ServerRequest::class); $injector->alias(ResponseInterface::class, Response::class); $injector->alias(ServerRequestInterface::class, ServerRequest::class); $injector->delegate(ServerRequest::class, [ServerRequestFactory::class, 'fromGlobals']); }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias('Psr\\Http\\Message\\RequestInterface', 'Zend\\Diactoros\\ServerRequest'); $injector->alias('Psr\\Http\\Message\\ResponseInterface', 'Zend\\Diactoros\\Response'); $injector->alias('Psr\\Http\\Message\\ServerRequestInterface', 'Zend\\Diactoros\\ServerRequest'); $injector->delegate('Zend\\Diactoros\\ServerRequest', 'Zend\\Diactoros\\ServerRequestFactory::fromGlobals'); }
/** * Applies a configuration set to a dependency injector. * * @param Injector $injector */ public function apply(Injector $injector) { //Specify token parameter from query string $injector->define(QueryExtractor::class, [':parameter' => 'al']); //Use Query Extractor to grab auth token $injector->alias(\Spark\Auth\Token\ExtractorInterface::class, QueryExtractor::class); //Use Json Extractor to grab credentials $injector->alias(\Spark\Auth\Credentials\ExtractorInterface::class, JsonExtractor::class); //Specify custom auth adapter to use $injector->alias(AdapterInterface::class, Adapter::class); }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias('Equip\\Auth\\Token\\ExtractorInterface', 'Equip\\Auth\\Token\\QueryExtractor'); $injector->define('Equip\\Auth\\Token\\QueryExtractor', [':parameter' => 'tk']); $injector->alias('Equip\\Auth\\Credentials\\ExtractorInterface', 'Equip\\Auth\\Credentials\\BodyExtractor'); $injector->alias('Equip\\Auth\\AdapterInterface', 'Equip\\Project\\Auth\\Adapter'); $dir = dirname(dirname(__DIR__)); $dotenv = new Dotenv($dir); $dotenv->load(); $dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']); }
public function __construct(JigConfig $jigConfig, Injector $injector, JigConverter $jigConverter = null, Escaper $escaper = null) { parent::__construct($jigConfig, $jigConverter); $this->injector = $injector; $this->injector->alias('Jig\\Jig', get_class($this)); $this->injector->share($this); if ($escaper === null) { $escaper = new ZendEscaperBridge(new ZendEscaper()); } $this->injector->alias('Jig\\Escaper', get_class($escaper)); $this->injector->share($escaper); $this->escaper = $escaper; }
public function setUp() { parent::setUp(); $this->compileDirectory = new JigCompilePath(dirname(__DIR__) . "/./../tmp/generatedTemplates/"); $this->templateDirectory = new JigTemplatePath(dirname(__DIR__) . "/./templates/"); $jigConfig = new JigConfig($this->templateDirectory, $this->compileDirectory, Jig::COMPILE_ALWAYS, "php.tpl"); $injector = new \Auryn\Injector(); $this->injector = $injector; $escaper = new ZendEscaperBridge(new ZendEscaper()); $this->injector->alias('Jig\\Escaper', get_class($escaper)); $this->injector->share($escaper); $this->jigDispatcher = new JigDispatcher($jigConfig, $injector); }
/** * Applies a configuration set to a dependency injector. * * @param Injector $injector */ public function apply(Injector $injector) { // JWT $injector->define('Equip\\Auth\\Jwt\\Configuration', [':publicKey' => 'uhklzsdv89ywrahu', ':ttl' => 3600, ':algorithm' => 'HS256']); $injector->alias('Equip\\Auth\\Jwt\\GeneratorInterface', 'Equip\\Auth\\Jwt\\FirebaseGenerator'); $injector->alias('Equip\\Auth\\Jwt\\ParserInterface', 'Equip\\Auth\\Jwt\\FirebaseParser'); // Tokens $injector->alias(TokenExtractorInterface::class, TokenHeaderExtractor::class); $injector->define(TokenHeaderExtractor::class, [':header' => 'Bearer']); // Credentials $injector->alias(CredentialsExtractorInterface::class, CredentialsBodyExtractor::class); // Adapter $injector->alias(AdapterInterface::class, JWTAdapter::class); }
/** * @param array $implementations * @param array $shareClasses * @return Provider */ function createProvider($implementations = array(), $shareClasses = array()) { $provider = new Injector(); $provider->define('GithubService\\GithubArtaxService\\GithubArtaxService', [':userAgent' => 'Danack_test']); $provider->prepare('Amp\\Artax\\Client', 'prepareArtaxClient'); $standardImplementations = ['GithubService\\GithubService' => 'DebugGithub', 'Amp\\Artax\\AsyncClient' => 'Amp\\Artax\\AsyncClient', 'Amp\\Reactor' => 'Amp\\NativeReactor', 'ArtaxServiceBuilder\\ResponseCache' => 'ArtaxServiceBuilder\\ResponseCache\\NullResponseCache', 'PSR\\Cache' => 'PSR\\Cache\\APCCache', 'Amp\\Addr\\Cache' => 'Amp\\Addr\\MemoryCache']; $standardShares = ['Amp\\Reactor' => 'Amp\\Reactor']; $provider->delegate('Amp\\Artax\\Client', 'createClient'); foreach ($standardImplementations as $interface => $implementation) { if (array_key_exists($interface, $implementations)) { if (is_object($implementations[$interface]) == true) { $provider->alias($interface, get_class($implementations[$interface])); $provider->share($implementations[$interface]); } else { $provider->alias($interface, $implementations[$interface]); } unset($implementations[$interface]); } else { if (is_object($implementation)) { $implementation = get_class($implementation); } $provider->alias($interface, $implementation); } } foreach ($implementations as $class => $implementation) { if (is_object($implementation) == true) { $provider->alias($class, get_class($implementation)); $provider->share($implementation); } else { $provider->alias($class, $implementation); } } foreach ($standardShares as $class => $share) { if (array_key_exists($class, $shareClasses)) { $provider->share($shareClasses[$class]); unset($shareClasses[$class]); } else { $provider->share($share); } } foreach ($shareClasses as $class => $share) { $provider->share($share); } $provider->share($provider); //YOLO return $provider; }
public function apply(Injector $injector) { //START: auth $injector->alias(AdapterInterface::class, \trejeraos\SimpleServerMonitor\Auth\FooAdapter::class); $injector->alias(AuthHandler::class, FooAuthHandler::class); $injector->share(FooAuthHandler::class); // get auth token $injector->alias(TokenExtractorInterface::class, QueryExtractor::class); $injector->define(QueryExtractor::class, [':parameter' => 'tok']); // get auth credentials $injector->alias(CredentialsExtractorInterface::class, BodyExtractor::class); $injector->define(BodyExtractor::class, [':identifier' => 'user', ':password' => 'password']); // share valid auth token class $injector->share(\trejeraos\SimpleServerMonitor\Auth\ValidTokens::class); //END: auth // share global config class $injector->share(\trejeraos\SimpleServerMonitor\Data\Configuration::class); }
public function apply(Injector $injector) { $injector->alias(Collection::class, DefaultCollection::class); $injector->prepare(Collection::class, function (Collection $collection) { $middleware = $collection->getArrayCopy(); // Do session checking before routing array_splice($middleware, array_search(RouteHandler::class, $middleware), 0, CheckSessionMiddleware::class); $collection->exchangeArray($middleware); }); }
public function testRouting405() { $request = new CLIRequest("/introduction", 'example.com', 'POST'); $this->injector->alias('Psr\\Http\\Message\\ServerRequestInterface', get_class($request)); $this->injector->share($request); $router = $this->injector->make('Tier\\Bridge\\FastRouter'); $fn404ErrorPage = function () { return new TextBody("Route not found.", 404); }; $fn405ErrorPage = function () { return new TextBody("Method not allowed for route.", 405); }; $result = $router->routeRequest($request, $fn404ErrorPage, $fn405ErrorPage); $body = TierApp::executeExecutable($result, $this->injector); $this->assertInstanceOf('Room11\\HTTP\\Body\\TextBody', $body); /** @var $body \Room11\HTTP\Body\HtmlBody */ $html = $body->getData(); $this->assertContains("Method not allowed for route.", $html); $this->assertEquals(405, $body->getStatusCode()); }
/** * Applies a configuration set to a dependency injector. * * @param Injector $injector */ public function apply(Injector $injector) { foreach (self::$commandHandlerMapping as $command => $handler) { $injector->alias($command, $handler); } $injector->delegate(CommandBus::class, function () use($injector) { $handlerMiddleware = new CommandHandlerMiddleware(new ClassNameExtractor(), new CallableLocator([$injector, 'make']), new HandleInflector()); $lockingMiddleware = new LockingMiddleware(); $transactionMiddleware = new TransactionMiddleware($injector->make(EntityManager::class)); return new CommandBus([$transactionMiddleware, $lockingMiddleware, $handlerMiddleware]); }); }
public function testRouting405() { $request = new CLIRequest("/introduction", 'example.com', 'POST'); $this->injector->alias('Psr\\Http\\Message\\ServerRequestInterface', get_class($request)); $this->injector->share($request); $renderCallable = $this->injector->execute('Tier\\Bridge\\JigFastRouter::routeRequest'); $body = TierApp::executeExecutable($renderCallable, $this->injector); $this->assertInstanceOf('Room11\\HTTP\\Body\\TextBody', $body); /** @var $body \Room11\HTTP\Body\HtmlBody */ $html = $body->getData(); $this->assertContains("Method not allowed for route.", $html); $this->assertEquals(405, $body->getStatusCode()); }
function createInjector() { $jigTemplatePath = new \Jig\JigTemplatePath(__DIR__ . "/fixtures/templates/"); $jigCompilePath = new \Jig\JigCompilePath(__DIR__ . "/var/generatedTemplates/"); // Create a JigConfig object $jigConfig = new JigConfig($jigTemplatePath, $jigCompilePath, Jig::COMPILE_CHECK_MTIME); $injector = new Injector(); $injector->alias('Jig\\Escaper', 'Jig\\Bridge\\ZendEscaperBridge'); $injector->delegate('FastRoute\\Dispatcher', 'TierTest\\JigBridge\\createDispatcher'); $injector->share('FastRoute\\Dispatcher'); $injector->share($jigConfig); return $injector; }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias('Equip\\Adr\\PayloadInterface', 'Equip\\Payload'); }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias('Relay\\ResolverInterface', 'Equip\\Resolver\\AurynResolver'); $injector->define('Equip\\Resolver\\AurynResolver', [':injector' => $injector]); }
public function __invoke(Injector $injector) { $injector->alias(\Iterator::class, \EmptyIterator::class); }
use Room11\Jeeves\WebAPI\Server as WebAPIServer; use Room11\OpenId\Credentials; use Room11\OpenId\EmailAddress as OpenIdEmailAddress; use Room11\OpenId\Password as OpenIdPassword; use Symfony\Component\Yaml\Yaml; use function Amp\onError; use function Amp\run; require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../version.php'; define(__NAMESPACE__ . '\\PROCESS_START_TIME', time()); $builtInCommands = [AdminBuiltIn::class, BanBuiltIn::class, CommandBuiltIn::class, PluginBuiltIn::class, RoomPresence::class, UptimeBuiltIn::class, VersionBuiltIn::class]; $builtInEventHandlers = [Invite::class]; $config = Yaml::parse(file_get_contents(__DIR__ . '/../config/config.yml')); $injector = new Injector(); require_once __DIR__ . '/setup-di.php'; $injector->alias(AdminStorage::class, $config['storage']['admin'] ?? FileAdminStorage::class); $injector->alias(BanStorage::class, $config['storage']['ban'] ?? FileBanStorage::class); $injector->alias(KeyValueStorage::class, $config['storage']['keyvalue'] ?? FileKeyValueStorage::class); $injector->alias(KeyValueStorageFactory::class, ($config['storage']['keyvalue'] ?? FileKeyValueStorage::class) . 'Factory'); $injector->alias(PluginStorage::class, $config['storage']['plugin'] ?? FilePluginStorage::class); $injector->alias(RoomStorage::class, $config['storage']['room'] ?? FileRoomStorage::class); $injector->define(BitlyClient::class, [':accessToken' => $config['bitly']['accessToken']]); $injector->define(TwitterApplicationCredentials::class, [':key' => $config['twitter']['consumerKey'], ':secret' => $config['twitter']['consumerSecret']]); $injector->define(TranslationAPICredentials::class, [':clientId' => $config['ms-translate']['client-id'] ?? '', ':clientSecret' => $config['ms-translate']['client-secret'] ?? '']); $injector->define(WebSocketEventDispatcher::class, [':devMode' => $config['dev-mode']['enable'] ?? false]); $injector->delegate(Logger::class, function () use($config) { $flags = array_map('trim', explode('|', $config['logging']['level'] ?? '')); if (empty($flags[0])) { $flags = LogLevel::ALL; } else { $flags = array_reduce($flags, function ($carry, $flag) {
<?php use Auryn\Injector; use function Aerys\router; $config = (require __DIR__ . "/config/config.php"); $injector = new Injector(); $injector->share(new \Amp\Mysql\Pool(sprintf("host=%s;user=%s;pass=%s;db=%s", $config["database"]["host"], $config["database"]["user"], $config["database"]["pass"], $config["database"]["name"]))); $injector->alias("Kelunik\\Chat\\Integration\\HookRepository", "Kelunik\\Chat\\Integration\\MysqlHookRepository"); $handler = $injector->make("Kelunik\\Chat\\Integration\\Dispatcher", [":config" => $config]); $router = router(); $router->post("{service}/{id:[0-9]+}", [$handler, "handle"]); $host = (new Aerys\Host())->expose("*", $config["deploy"]["port"])->name($config["deploy"]["host"])->use($router);
private function registerCoreLabradorServices(Injector $injector) { $injector->share(Emitter::class); $injector->alias(EmitterInterface::class, Emitter::class); $injector->share(PluginManager::class); }
/** * */ public function execute() { //Figure out what Command was requested. try { $parsedCommand = $this->console->parseCommandLine(); } catch (ConfiguratorException $ce) { echo "Problem running configuration: " . $ce->getMessage(); exit(-1); } catch (\Exception $e) { //@TODO change to just catch parseException when that's implemented $output = new BufferedOutput(); $this->console->renderException($e, $output); echo $output->fetch(); exit(-1); } //Run the command requested, or the help callable if no command was input try { $output = $parsedCommand->getOutput(); $formatter = $output->getFormatter(); $formatter->setStyle('question', new OutputFormatterStyle('blue')); $formatter->setStyle('info', new OutputFormatterStyle('blue')); $questionHelper = new QuestionHelper(); $questionHelper->setHelperSet($this->console->getHelperSet()); // We currently have no config, so fine to create this directly. $injector = new Injector(); $injector->alias('Configurator\\Writer', 'Configurator\\Writer\\FileWriter'); $injector->defineParam('originalArgs', $this->originalArgs); foreach ($parsedCommand->getParams() as $key => $value) { $injector->defineParam($key, $value); } $injector->execute($parsedCommand->getCallable()); } catch (ConfiguratorException $ce) { echo "Error running task: \n"; echo $ce->getMessage(); exit(-1); } catch (\Exception $e) { echo "Unexpected exception of type " . get_class($e) . " running configurator`: " . $e->getMessage() . PHP_EOL; echo $e->getTraceAsString(); exit(-2); } }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias(ResolverInterface::class, AurynResolver::class); $injector->define(AurynResolver::class, [':injector' => $injector]); }
$auryn = new Auryn(); $injector = new Injector($auryn); /** * Setup shared instances and aliases */ $auryn->share($request); $auryn->share($session); $auryn->share($user); $auryn->share($minifier); $auryn->share($translator); $auryn->share($decryptor); $auryn->define('CodeCollab\\Encryption\\Defuse\\Encryptor', [':key' => file_get_contents(__DIR__ . '/encryption.key')]); $auryn->define('CodeCollab\\Http\\Cookie\\Factory', [':domain' => $request->server('SERVER_NAME'), ':secure' => $request->isEncrypted()]); $auryn->define('CodeCollab\\Theme\\Theme', [':themePath' => __DIR__ . '/themes', ':theme' => 'Default']); $auryn->define('Demo\\Presentation\\Template\\Html', [':basePage' => '/page.phtml']); $auryn->alias('CodeCollab\\CsrfToken\\Token', 'CodeCollab\\CsrfToken\\Handler'); $auryn->alias('CodeCollab\\Authentication\\Authentication', 'CodeCollab\\Authentication\\User'); $auryn->alias('CodeCollab\\CsrfToken\\Storage\\Storage', 'Demo\\Storage\\TokenSession'); $auryn->alias('CodeCollab\\Http\\Session\\Session', 'CodeCollab\\Http\\Session\\Native'); $auryn->alias('CodeCollab\\CsrfToken\\Generator\\Generator', 'CodeCollab\\CsrfToken\\Generator\\RandomBytes32'); $auryn->alias('CodeCollab\\I18n\\Translator', 'CodeCollab\\I18n\\FileTranslator'); $auryn->alias('CodeCollab\\Theme\\Loader', 'CodeCollab\\Theme\\Theme'); $auryn->alias('CodeCollab\\Template\\Html', 'Demo\\Presentation\\Template\\Html'); $auryn->alias('CodeCollab\\Encryption\\Encryptor', 'CodeCollab\\Encryption\\Defuse\\Encryptor'); $auryn->alias('CodeCollab\\Encryption\\Decryptor', 'CodeCollab\\Encryption\\Defuse\\Decryptor'); /** * Setup the front controller */ $frontController = new FrontController($router, $auryn->make('CodeCollab\\Http\\Response\\Response', ['server' => $request]), $session, $injector); /** * Run the application
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias(PayloadInterface::class, Payload::class); }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->alias('Negotiation\\NegotiatorInterface', 'Negotiation\\Negotiator'); }
/** * Applies a configuration set to a dependency injector. * * @param Injector $injector */ public function apply(Injector $injector) { $injector->alias(ShiftInterface::class, Shift::class); $injector->alias(UserInterface::class, User::class); }
<?php use Auryn\Injector; use Jig\JigConfig; use Jig\Jig; // Register some directories in the autoloader - we don't do this in composer.json // to avoid any confusion with users of the library. $autoloader = (require_once realpath(__DIR__) . '/../vendor/autoload.php'); $autoloader->add('JigDemo', [realpath(__DIR__) . '/']); $autoloader->add('Jig', [realpath(__DIR__) . '/compile/']); $injector = new Injector(); // Setting the Jig config $jigConfig = new JigConfig(__DIR__ . "/templates/", __DIR__ . "/compile/", Jig::COMPILE_ALWAYS, "php.tpl"); // Tell the DIC that every class that needs an instance of JigConfig // should use this one. $injector->share($jigConfig); // Alias an interface to a concrete class so that it can be found in // the template. $injector->alias('JigDemo\\Model\\ColorScheme', '\\JigDemo\\Model\\PrimaryColorscheme'); // This is the template we will be compiling. $templateName = 'onePageExample'; // Create the Jig renderer $jig = new Jig($jigConfig); // Tell Jig to make sure the template is compiled. $jig->compile($templateName); // Get the classname that the template will be called $className = $jig->getFQCNFromTemplateName($templateName); // Call the template $contents = $injector->execute([$className, 'render']); echo $contents;
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->share(SessionInterface::class); $injector->alias(SessionInterface::class, NativeSession::class); $injector->prepare(NativeSession::class, [$this, 'prepareSession']); }