/** * @param ApplicationInterface $app * * @throws Exception */ public function run(ApplicationInterface $app) { $this->application = $app; $action = $app->getRequest()->getAction(); if ($action) { $actionMiddleware = new ActionMiddleware(Invokable::cast($action)); $serviceId = $action instanceof ServiceReference ? $action->getId() : $this->computeServiceName($app->getRequest()->getUri()->getPath()); $app->getStep('action')->plug($actionMiddleware); } else { $route = $app->getRequest()->getRoute(); // compute service id $serviceId = $this->computeServiceName($route); // if no service matching the route has been registered, // try to locate a class that could be used as service if (!$app->getServicesFactory()->isServiceRegistered($serviceId)) { $actionClass = $this->resolveActionClassName($route); $action = $this->resolveActionFullyQualifiedName($actionClass); if (!$action) { throw new Exception(sprintf('No callback found to map the requested route "%s"', $route), Exception::ACTION_NOT_FOUND); } $app->getServicesFactory()->registerService(['id' => $serviceId, 'class' => $action]); } // replace action by serviceId to ensure it will be fetched using the ServicesFactory $actionReference = new ServiceReference($serviceId); // wrap action to inject returned value in application $app->getStep('action')->plug($actionMiddleware = new ActionMiddleware($actionReference)); } // store action as application parameter for further reference $app->setParam('runtime.action.middleware', $actionMiddleware); $app->setParam('runtime.action.service-id', $serviceId); }
/** * @param ApplicationInterface $app * * @throws \Doctrine\ORM\ORMException * @throws \ObjectivePHP\Primitives\Exception * @throws \ObjectivePHP\ServicesFactory\Exception */ public function buildEntityManagers(ApplicationInterface $app) { $entityManagers = $app->getConfig()->subset(Config\EntityManager::class); foreach ($entityManagers as $connection => $params) { if (isset($params['db'])) { $params = $params['db']; } // normalize if needed $entitiesPaths = $params['entities.locations']; Collection::cast($entitiesPaths)->each(function (&$path) { if (strpos($path, '/') !== 0) { $path = getcwd() . '/' . $path; } }); // TODO: handle isDev depending on app config $emConfig = Setup::createAnnotationMetadataConfiguration((array) $entitiesPaths, true); $emConfig->setNamingStrategy(new UnderscoreNamingStrategy()); $em = EntityManager::create($params, $emConfig); if (!empty($params['mapping_types']) && is_array($params['mapping_types'])) { $platform = $em->getConnection()->getDatabasePlatform(); foreach ($params['mapping_types'] as $type => $mapping) { if (!Type::hasType($type) && class_exists($mapping)) { Type::addType($type, $mapping); $mapping = $type; } $platform->registerDoctrineTypeMapping($type, $mapping); } } // register entity manager as a service $emServiceId = 'doctrine.em.' . Str::cast($connection)->lower(); $app->getServicesFactory()->registerService(['id' => $emServiceId, 'instance' => $em]); $app->getServicesFactory()->registerService(['id' => 'db.connection.' . $connection, 'instance' => $em->getConnection()->getWrappedConnection()]); } }
/** * @param ApplicationInterface $app * @return mixed * @throws Exception */ public function run(ApplicationInterface $app) { $middlewareReference = $this->route(); $middleware = $this->getMiddleware($middlewareReference); // auto inject dependencies $servicesFactory = $app->getServicesFactory(); if ($servicesFactory) { $normalizedMiddleware = null; switch (true) { // middlewares can be an array containing [$object, 'method'] case is_array($middleware) && !empty($middleware[0]) && is_object($middleware[0]): $normalizedMiddleware = $middleware[0]; break; case $middleware instanceof Invokable: $normalizedMiddleware =& $middleware->getCallable(); break; case is_object($middleware): $normalizedMiddleware = $middleware; break; } if ($normalizedMiddleware) { $servicesFactory->injectDependencies($normalizedMiddleware); } } // TODO fix http return code (probably 405) if (!is_callable($middleware)) { throw new Exception(sprintf('No middleware matching routed reference "%s" has been registered', $middlewareReference)); } return $middleware($app); }
/** * @param ApplicationInterface $app */ public function registerServices(ApplicationInterface $app) { $servers = $app->getConfig()->subset(BeanstalkServer::class); foreach ($servers as $service => $data) { $serviceName = self::SERVICE_PREFIX . $service; $service = new ClassServiceSpecs($serviceName, Pheanstalk::class); $service->setParams([$data['host'], $data['port'], $data['timeout'], $data['persistent']]); $service->setSetters(['useTube' => [$data['tube']]]); $app->getServicesFactory()->registerService($service); } }
public function run(ApplicationInterface $app) { $matchedRoute = $app->getRequest()->getMatchedRoute(); $action = Invokable::cast($matchedRoute->getAction()); $app->getServicesFactory()->injectDependencies($action->getCallable()); $app->setParam('runtime.action.middleware', $action); $result = $action->getCallable()($app); if ($result instanceof Response) { $app->setResponse($result); } else { // set default content type $app->setResponse((new HttpResponse())->withHeader('Content-Type', 'text/html')); Collection::cast($result)->each(function ($value, $var) { Vars::set($var, $value); }); } }
/** * @param ApplicationInterface $app * * @return null */ public function bootstrapEloquent(ApplicationInterface $app) { $capsules = $app->getConfig()->subset(EloquentCapsule::class); if (!$capsules) { // eloquent has not been configured return null; } $capsuleManager = new CapsuleManager(); // loop over declared capsules foreach ($capsules as $id => $capsule) { // add default values $capsule += ['charset' => 'utf8', 'collation' => 'utf8_unicode_ci']; $capsuleManager->addConnection($capsule, $id); } // register the capsule manager as service $app->getServicesFactory()->registerService(['id' => 'eloquent.capsule', 'instance' => $capsuleManager]); $capsuleManager->setAsGlobal(); $capsuleManager->bootEloquent(); }
/** * @param ApplicationInterface $app */ public function __invoke(ApplicationInterface $app) { $exception = $app->getException(); if (php_sapi_name() == 'cli') { throw $exception; } else { $output = Tag::h1('An error occurred'); do { $output .= $this->renderException($exception); } while ($exception = $exception->getPrevious()); $output .= Tag::h2('Workflow'); foreach ($app->getExecutionTrace() as $step => $middlewares) { $output .= Tag::h3('Step: ' . $step); /** * @var Hook $hook */ foreach ($middlewares as $middleware) { $output .= Tag::dt([$middleware->getReference() . ': ', $middleware->getDescription()]); } } // display config $output .= Tag::h2('Configuration'); ob_start(); var_dump($app->getConfig()->getInternalValue()); $output .= ob_get_clean(); // display services $output .= Tag::h2('Services'); foreach ($app->getServicesFactory()->getServices() as $spec) { $output .= Tag::h3($spec->getId()); ob_start(); var_dump($spec); $output .= ob_get_clean(); } // manually emit response (new SapiEmitter())->emit((new HtmlResponse($output))->withStatus(500)); } }
/** * @param ApplicationInterface $app * * @throws \ObjectivePHP\ServicesFactory\Exception\Exception * @internal param ApplicationInterface $application * */ protected function injectInitialServices(ApplicationInterface $app) { $app->getServicesFactory()->registerService(['id' => 'application', 'instance' => $app], ['id' => 'config', 'instance' => $app->getConfig()], ['id' => 'events-handler', 'instance' => $app->getEventsHandler()]); }
/** * Shorthand to access ServicesFactory * * @return ServicesFactory */ public function getServicesFactory() : ServicesFactory { return $this->application->getServicesFactory(); }