Exemple #1
1
 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);
     }
 }
Exemple #2
0
 private function registerExceptionHandlerServices(Injector $injector)
 {
     $injector->share(Run::class);
     $injector->prepare(Run::class, function (Run $run) {
         $run->pushHandler(new PrettyPageHandler());
     });
     $injector->share(ExceptionHandlingPlugin::class);
 }
 /**
  * @inheritDoc
  */
 public function apply(Injector $injector)
 {
     $injector->alias('Psr\\Http\\Message\\ResponseInterface', 'Zend\\Diactoros\\Response');
     $injector->share('Psr\\Http\\Message\\ResponseInterface');
     $injector->delegate('Psr\\Http\\Message\\ServerRequestInterface', 'Zend\\Diactoros\\ServerRequestFactory::fromGlobals');
     $injector->share('Psr\\Http\\Message\\ServerRequestInterface');
     $injector->alias('Psr\\Http\\Message\\RequestInterface', 'Psr\\Http\\Message\\ServerRequestInterface');
 }
Exemple #4
0
 /**
  * Sets the templates path.
  *
  * @param  string            $path
  * @param  \Twig_Environment $twig
  * @param  array             $extensions
  * @return self
  */
 public function setTemplatePath($path, \Twig_Environment $twig = null, $extensions = [])
 {
     $this->paths['templates'] = $path;
     if (is_null($twig)) {
         $loader = new \Twig_Loader_Filesystem($path);
         $twig = new \Twig_Environment($loader);
     }
     $twig->setExtensions($extensions);
     $this->injector->share($twig);
     return $this;
 }
 /**
  * @param array $injections Single dimensional array of shareable values from the Silex\Application (pimple) object
  *
  * @return void
  */
 public function performInjections(array $injections)
 {
     foreach ($injections as $shareable) {
         $this->injector->share($this->application[$shareable]);
     }
     /**
      * This can only be done here because security / user is only read to be read after boot
      */
     if (isset($this->application['twig']) && isset($this->application['security.authorization_checker'])) {
         $this->application['twig']->addExtension(new SecurityExtension($this->application['security.authorization_checker']));
     }
 }
Exemple #6
0
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;
}
Exemple #7
0
 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);
 }
 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();
 }
 public function __invoke(Injector $injector)
 {
     $injector->share($injector);
     foreach ($this->classes as $class) {
         $injector->execute($class);
     }
 }
Exemple #10
0
 function setMedoo()
 {
     $injector = new Injector();
     $injector->share('medoo');
     $injector->define('medoo', [':options' => $this->databaseconfig]);
     $this->medoodb = $injector->make('medoo');
 }
Exemple #11
0
 /**
  * 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);
 }
 /**
  * Applies a configuration set to a dependency injector.
  *
  * @param Injector $injector
  */
 public function apply(Injector $injector)
 {
     $paths = ["src/Users/Entity/", "src/Shifts/Entity/"];
     $isDevMode = true;
     // the connection configuration
     $dbParams = array('host' => $_ENV['DB_HOST'], 'driver' => $_ENV['DB_DRIVER'], 'user' => $_ENV['DB_USER'], 'password' => $_ENV['DB_PASSWORD'], 'dbname' => $_ENV['DB_DATABASE_NAME']);
     $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, null, null, false);
     $injector->share(EntityManager::create($dbParams, $config));
 }
 /**
  * Applies a configuration set to a dependency injector.
  *
  * @param Injector $injector
  */
 public function apply(Injector $injector)
 {
     // Create a new Manager instance.
     $manager = new Manager(new ArrayDriver());
     // Managers can do everything
     $manager->role('manager')->allow('all');
     //        $manager->role('employee')->allow('guest', 'read');
     $injector->share($manager);
 }
 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 getServiceLocator()
 {
     if (!$this->service_locator) {
         $di_container = new DiContainer(new StandardReflector());
         $di_container->share($di_container);
         $service_provisioner = $di_container->make(ServiceProvisioner::CLASS);
         $this->service_locator = $service_provisioner->provision();
     }
     return $this->service_locator;
 }
Exemple #16
0
 /**
  * @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);
     });
 }
Exemple #17
0
 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());
 }
Exemple #18
0
function injector(Injector $injector = null) : Injector
{
    static $persistent;
    if (isset($injector)) {
        $persistent = $injector;
        $persistent->share($persistent);
    }
    if (!isset($persistent)) {
        $persistent = new Injector();
        $persistent->share($persistent);
    }
    return $persistent ?? ($persistent = new Injector());
}
Exemple #19
0
 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());
 }
 /**
  *
  * {@inheritDoc}
  *
  * @see \Spark\Configuration\ConfigurationInterface::apply()
  */
 public function apply(Injector $injector)
 {
     $acl = new Acl();
     $acl->addRole(new Role('manager'))->addRole(new Role('employee'));
     $acl->addResource(new Resource('GetEmployeeShifts'));
     $acl->addResource(new Resource('GetEmployeeShiftsSummary'));
     $acl->addResource(new Resource('GetShiftDetail'));
     $acl->addResource(new Resource('ModifyShift'));
     $acl->addResource(new Resource('GetShiftsByDate'));
     $acl->addResource(new Resource('GetEmployee'));
     $acl->allow('employee', 'GetEmployeeShifts');
     $acl->allow('employee', 'GetEmployeeShiftsSummary');
     $acl->allow('employee', 'GetShiftDetail');
     $acl->allow('manager', 'GetEmployee');
     $acl->allow('manager', 'ModifyShift');
     $acl->allow('manager', 'GetShiftsByDate');
     $injector->share($acl);
 }
 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');
 }
Exemple #22
0
 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');
 }
/**
 * @return \Auryn\Injector
 * @throws \Auryn\ConfigException
 */
function createTestInjector($mocks = array(), $shares = array())
{
    $injector = new \Auryn\Injector();
    // Read application config params
    $injectionParams = (require __DIR__ . "/./testInjectionParams.php");
    /** @var $injectionParams \Tier\InjectionParams */
    $injector->share(new ScriptPath(__DIR__ . "/../fixtures/"));
    //$injectionParams->mergeMocks($mocks);
    $injectionParams->addToInjector($injector);
    foreach ($mocks as $class => $implementation) {
        if (is_object($implementation) == true) {
            $injector->alias($class, get_class($implementation));
            $injector->share($implementation);
        } else {
            $injector->alias($class, $implementation);
        }
    }
    $injector->share($injector);
    return $injector;
}
/**
 * @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;
}
 /**
  * @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();
 }
Exemple #26
0
<?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;
Exemple #27
0
<?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);
Exemple #28
0
 public function getInjector()
 {
     $this->injector = $injector = new Injector();
     $injector->share(Binding::class);
     $injector->share(BootLoader::class);
     $injector->share(Config::class);
     $injector->share(Database::class);
     $injector->share(Dispatcher::class);
     $injector->share(HttpRequestEx::class);
     $injector->share(HttpResponseEx::class);
     $injector->share(LoggerEx::class);
     $injector->share(QCache::class);
     $injector->share(Router::class);
     $injector->share(Session::class);
     $injector->share(Connection::class);
     $injector->share($injector);
     return $injector;
 }
 /**
  * Run the application
  *
  * @param string $runner
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function run($runner = 'Relay\\Relay')
 {
     $this->configuration->apply($this->injector);
     return $this->injector->share($this->middleware)->prepare('Equip\\Directory', $this->routing)->execute($runner);
 }
Exemple #30
0
 /**
  * @param Injector $injector
  * @param Router   $router
  */
 public function __construct(Injector $injector, Router $router)
 {
     $this->injector = $injector;
     $this->router = $router;
     $this->injector->share($router);
 }