/** * Resolve a class spec into an object, if it is not already instantiated. * * @param string|object $specOrObject * * @return object */ public function __invoke($specOrObject) { if (is_object($specOrObject)) { return $specOrObject; } return $this->injector->make($specOrObject); }
/** * Start the console application * * @return int 0 if everything went fine, or an error code */ public function run() { $this->configuration->apply($this->injector); $application = $this->injector->make(ConsoleApplication::class); array_map(function ($command) use($application) { $application->add($this->injector->make($command)); }, $this->commands->toArray()); return $application->run(); }
/** * {@inheritdoc} */ public function make($class) { try { return $this->auryn->make($class); } catch (InjectionException $e) { throw new DependencyInjectionException('Dependency injection failed while trying to make ' . $class . ', ' . $e->getMessage(), $e->getCode(), $e); //@codeCoverageIgnoreStart } catch (ReflectionException $e) { throw new DependencyInjectionException('Dependency injection failed while trying to make ' . $class . ', ' . $e->getMessage(), $e->getCode(), $e); //@codeCoverageIgnoreEnd } }
/** * Adds a new instance to the container. * * @param string $id * @param mixed $concrete */ public function add($id, $concrete = null) { if ($concrete && !is_array($concrete)) { $this->instances[$id] = $concrete; return $this; } $arguments = []; if (is_array($concrete)) { $arguments = $concrete; } $this->instances[$id] = $this->injector->make($id, $arguments); return $this; }
/** * */ function execute() { $gauges = []; $counters = []; $asyncStats = $this->injector->make('Stats\\AsyncStats'); $gauges = array_merge($gauges, $this->getQueueGauges()); $counters = array_merge($counters, $asyncStats->getCounters()); $requiredTimers = [\ImagickDemo\Queue\ImagickTaskRunner::event_imageGenerated, \ImagickDemo\Queue\ImagickTaskRunner::event_pageGenerated]; $gauges = array_merge($gauges, $asyncStats->summariseTimers($requiredTimers)); if (count($counters) || count($gauges)) { $librato = $this->injector->make('Stats\\Librato'); $librato->send($gauges, $counters); } }
protected function setUp() { define('MODEL_DIR', '\\Test\\Model'); //define('DEBUG_MODE', true); $this->injector = new Injector(); $this->injector->share(Database::class); $this->database = $this->injector->make('Minute\\Database\\Database', [true]); try { $this->pdo = $this->database->getPdo(); } catch (\PDOException $e) { $this->markTestSkipped('Database connection error: ' . $e->getMessage()); } parent::setUp(); }
/** * @inheritDoc */ public function apply(Injector $injector) { foreach ($this as $class) { $configuration = $injector->make($class); $configuration->apply($injector); } }
/** * Creates all service hook handlers. */ private function initialize() { $injector = new Injector(); $namespace = __NAMESPACE__ . "\\Service\\"; $basePath = __DIR__ . "/../vendor/kelunik/chat-services/res/schema/"; $transform = function ($match) { return strtoupper($match[1]); }; try { foreach ($this->config["services"] as $name => $enabled) { if (!$enabled) { continue; } $service = $injector->make($namespace . preg_replace_callback("~-([a-z])~", $transform, ucfirst($name))); $found = false; foreach (scandir($basePath . $name) as $file) { if ($file === "." || $file === "..") { continue; } $found = true; $uri = realpath($basePath . $name . "/" . $file); $schema = $this->retriever->retrieve("file://" . $uri); $this->schemas[$name][strtok($file, ".")] = $schema; } if (!$found) { throw new RuntimeException("every service must have at least one event schema"); } $this->services[$name] = $service; } } catch (InjectorException $e) { throw new RuntimeException("couldn't create all services", 0, $e); } }
/** * Run the application * * @param string $runner * * @return \Psr\Http\Message\ResponseInterface */ public function run($runner = 'Relay\\Relay') { foreach ($this->configuration as $entry) { $this->injector->make($entry)->apply($this->injector); } return $this->injector->share($this->middleware)->prepare('Spark\\Directory', $this->routing)->execute($runner); }
function setMedoo() { $injector = new Injector(); $injector->share('medoo'); $injector->define('medoo', [':options' => $this->databaseconfig]); $this->medoodb = $injector->make('medoo'); }
/** * @param string $class * @dataProvider dataMapping */ public function testApply($class) { $injector = new Injector(); $configuration = $injector->make(AuraCliConfiguration::class); $configuration->apply($injector); $instance = $injector->make($class); $this->assertInstanceOf($class, $instance); }
/** * resolve router target to class object * @param string $target route target, format: Class#method or Class/method * @return array [object, method] */ public function createController($target) { $matches = null; if (false === preg_match('/[#|\\/]/', $target, $matches)) { throw new HttpException(404, 'Invalid route: ' . $target); } list($class, $method) = explode($matches[0], $target, 2); $class = 'Controller\\' . $class; if (!class_exists($class)) { throw new HttpException(404, sprintf('Controller "%s" does not exist.', $class)); } $instance = $this->injector->make($class); if (!method_exists($instance, $method)) { throw new HttpException(404, sprintf('Action "%s" not found on controller "%s"', $method, $class)); } return [$instance, $method]; }
public function testApply() { $injector = new Injector(); $configuration = $injector->make(PredisConfiguration::class); $configuration->apply($injector); $instance = $injector->make(Client::class); $this->assertInstanceOf(Client::class, $instance); }
/** * @inheritDoc */ public function apply(Injector $injector) { foreach ($this as $configuration) { if (!is_object($configuration)) { $configuration = $injector->make($configuration); } $configuration->apply($injector); } }
public function apply(Injector $injector) { $injector->prepare(Engine::class, function (Engine $engine) use($injector) { $session = $injector->make(Session::class); $engine->registerFunction('is_logged_in', function () use($session) { return $session->has('rdio.token') && $session->has('tidal.session'); }); }); }
public function listen($events, $listener, $priority = 0, $data = null) { $wrapper = function ($payload) use($events, $listener, $data) { if (!empty($data) && $payload instanceof Event) { $payload->setData($data); } if (is_array($listener) && count($listener) === 2 && is_string($listener[0])) { $object = $this->injector->make($listener[0]); $listener = [$object, $listener[1]]; } if (is_callable($listener)) { return call_user_func($listener, $payload); } else { $this->logger->warn("Listener is not callable: ", $listener); return false; } }; parent::listen($events, $wrapper, $priority); }
/** * @inheritDoc */ public function apply(Injector $injector) { $injector->define(Loader::class, [':filepaths' => $this->envfile]); $injector->share(Env::class); $injector->prepare(Env::class, function (Env $env, Injector $injector) { $loader = $injector->make(Loader::class); $values = $loader->parse()->toArray(); return $env->withValues($values); }); }
/** * Applies a configuration set to a dependency injector. * * @param Injector $injector */ public function apply(Injector $injector) { foreach (self::$entityRepositoryMap as $entityName => $repoClassName) { $injector->delegate($repoClassName, function () use($entityName, $injector) { /** @var EntityManager $entityManager */ $entityManager = $injector->make(EntityManager::class); return $entityManager->getRepository($entityName); }); } }
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()); }
/** * * {@inheritDoc} * * @see \Spark\Configuration\ConfigurationInterface::apply() */ public function apply(Injector $injector) { $host = $this->env['DB_HOST']; $username = $this->env['DB_USERNAME']; $password = $this->env['DB_PASSWORD']; $name = $this->env['DB_DBNAME']; $port = $this->env['DB_PORT']; $dsn = "mysql:dbname={$name};host={$host};port={$port}"; $injector->define('PDO', [':dsn' => $dsn, ':username' => $username, ':passwd' => $password]); $injector->define('FluentPDO', [':pdo' => $injector->make('PDO')]); }
/** * 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 testRenderBlock() { $blockRender = $this->injector->make('JigTest\\PlaceHolder\\PlaceHolderPlugin'); $this->jigDispatcher->addPlugin($blockRender); $contents = $this->jigDispatcher->renderTemplateFile('block/renderBlock'); $this->assertEquals(1, $blockRender->blockStartCallCount); $this->assertEquals(1, $blockRender->blockEndCallCount); $this->assertEquals("foo='bar'", $blockRender->passedSegementText); $this->assertContains("This is in a warning block", $contents); $this->assertContains("</span>", $contents); $this->assertContains("<span class='warning'>", $contents); $this->assertContains("This is in a warning block", $contents); }
/** * Sets up Twig and gets all commands from the specified path. * * @return void */ protected function getConsoleApp() { $files = glob($this->getCommandPath() . '/*.php'); $path = strlen($this->getCommandPath() . DIRECTORY_SEPARATOR); $pattern = '/\\.[^.\\s]{3,4}$/'; foreach ($files as $file) { $className = preg_replace($pattern, '', substr($file, $path)); $className = $this->getCommandNamespace() . '\\' . $className; $class = new \ReflectionClass($className); if ($class->isAbstract()) { continue; } $this->console->add($this->injector->make($className)); } return $this->console; }
public function testRendering() { /** @var ViewParser $view */ /** @var Dispatcher $dispatcher */ $dispatcher = (new Injector())->make('Minute\\Event\\Dispatcher'); $dispatcher->listen('one.plus.one', function (ViewEvent $event) { $event->setContent('2'); }); $injector = new Injector(); $injector->define('Dispatcher', [$dispatcher]); $injector->share($dispatcher); $view = $injector->make('Minute\\View\\ViewParser', ['foo' => 'bar']); $view->loadTemplate('A\\HasEvent'); $output = $view->render(); $this->assertEquals('<html><body>1 + 1 = 2.</body></html>', $output, 'Output is rendering correctly'); $view->setHelpers([new Helper('D/e', Helper::POSITION_BODY)]); $output = $view->render(); $this->assertEquals('<html><body>1 + 1 = 2.[Helper 1!]</body></html>', $output, 'Output is rendering correctly'); }
public function testMemoryCacheTest() { $key = 'mykey'; $value = ['a' => 'b']; foreach (['memory', 'file'] as $type) { if (MemcachedStorage::isAvailable()) { putenv('PHP_MEMCACHE_SERVER=localhost'); } /** @var QCache $qCache */ $injector = new Injector(); $qCache = $injector->make('Minute\\Cache\\QCache', [$type]); $qCache->flush(); $none = $qCache->get($key); $this->assertNull($none, 'Cache is empty'); $result = $qCache->set($key, $value); $this->assertEquals($result, $value, 'Cache is set'); $result = $qCache->get($key); $this->assertEquals($result, $value, 'Cache is retrieved'); $qCache->remove($key); $none = $qCache->get($key); $this->assertNull($none, 'Cache key is deleted'); } }
/** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { // Parse the configuration $configFile = $input->getArgument('configFile'); $configuration = ConfigurationParser::parseConfiguration(new YamlReader($configFile)); // Configure Propel and the logger $logger = $this->configureLogger($output, $configuration); $this->configurePropel($configuration, $logger); $injector = new Injector(); // Configure shared instances $eventLoop = EventLoopFactory::create(); $eventDispatcher = new EventDispatcher(); $aliases = [':logger' => $logger, ':loop' => $eventLoop]; $injector->share($configuration)->share($logger)->share($eventDispatcher)->share($eventLoop); // Create managers $statusManager = $injector->make('Jalle19\\StatusManager\\Manager\\StatusManager', $aliases); $instanceStateManager = $injector->make('Jalle19\\StatusManager\\Manager\\InstanceStateManager', $aliases); $webSocketManager = $injector->make('Jalle19\\StatusManager\\Manager\\WebSocketManager', $aliases); $persistenceManager = $injector->make('Jalle19\\StatusManager\\Manager\\PersistenceManager', $aliases); $statisticsManager = $injector->make('Jalle19\\StatusManager\\Manager\\StatisticsManager', $aliases); $inputErrorManager = $injector->make('Jalle19\\StatusManager\\Manager\\InputErrorManager', $aliases); $httpRequestManager = $injector->make('Jalle19\\StatusManager\\Manager\\HttpRequestManager', $aliases); // Wire the event dispatcher $webSocketManager->registerMessageHandler($statisticsManager); $webSocketManager->registerMessageHandler($webSocketManager); $eventDispatcher->addSubscriber($statusManager); $eventDispatcher->addSubscriber($instanceStateManager); $eventDispatcher->addSubscriber($webSocketManager); $eventDispatcher->addSubscriber($persistenceManager); $eventDispatcher->addSubscriber($inputErrorManager); $eventDispatcher->addSubscriber($httpRequestManager); // Configure the event loop and start the application $eventLoop->addPeriodicTimer($configuration->getUpdateInterval(), function () use($eventDispatcher) { // Emit an event on each tick $eventDispatcher->dispatch(Events::MAIN_LOOP_TICK); }); $eventDispatcher->dispatch(Events::MAIN_LOOP_STARTING); $eventLoop->run(); }
public function testCallsBeforeAndAfterControllerOneTime() { $handler = ControllerStub::class . '#index'; $injector = new Injector(); $injector->share(ControllerStub::class); $resolver = new ControllerActionResolver($injector, $this->emitter); $cb = $resolver->resolve($this->request, $handler); $this->emitter->emit(new BeforeControllerEvent($this->request, $cb)); $res = $cb(); $this->emitter->emit(new AfterControllerEvent($this->request, $res, $cb)); // imagine the engine gets ran again and these events are triggered again $this->emitter->emit(new BeforeControllerEvent($this->request, function () { })); $this->emitter->emit(new AfterControllerEvent($this->request, $res, function () { })); $controller = $injector->make(ControllerStub::class); $this->assertSame(1, $controller->beforeControllerCount(), 'beforeController not called exactly 1 time'); $this->assertSame(1, $controller->afterControllerCount(), 'afterController not called exactly 1 time'); }
/** * @param \Auryn\Injector $injector * @param \ImagickDemo\Control $control * @throws \Exception * @internal param Request $request * @return array|callable */ function getImageResponse(CategoryNav $categoryNav, \Auryn\Injector $injector) { $control = $injector->make('ImagickDemo\\Control'); $params = $control->getFullParams([]); return $this->getImageResponseInternal($categoryNav, $injector, $params); }
/** * * {@inheritDoc} * * @see \Spark\Configuration\ConfigurationInterface::apply() */ public function apply(Injector $injector) { $injector->define('UserMapper', [':fpdo' => $injector->make('FluentPDO')]); $injector->define('ShiftMapper', [':fpdo' => $injector->make('FluentPDO')]); }
/** * Handle the request. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param bool $catch * @return ResponseInterface * @throws \Exception * @throws \LogicException */ public function handle(ServerRequestInterface $request, ResponseInterface $response, $catch = true) { $builder = $this->injector->make('Relay', [$this->getResolver()]); $dispatcher = $builder->newInstance($this->getMiddleware()); return $dispatcher($request, $response); }