public function run(ApplicationInterface $app)
 {
     $connector = Connector::getInstance();
     $connector->setSourcesBasePath(getcwd());
     $matcher = new Matcher();
     // redirect errors to PhpConsole
     \PhpConsole\Handler::getInstance()->start();
     $app->getEventsHandler()->bind('*', function (EventInterface $event) use($app, $connector, $matcher) {
         /**
          * @var $connector \PhpConsole\Connector
          */
         if ($connector->isActiveClient()) {
             $console = \PhpConsole\Handler::getInstance();
             $context = $event->getContext();
             $origin = $event->getOrigin();
             switch (true) {
                 case $event->getName() == 'application.workflow.step.run':
                     $console->debug(sprintf('Starting running step %s', $origin->getName()), 'workflow.step');
                     break;
                 case $event->getName() == 'application.workflow.hook.run':
                     $middleware = $origin->getMiddleware();
                     $console->debug(sprintf('Running Middleware %s (%s)', $middleware->getReference(), $middleware->getDescription()), 'workflow.hook');
                     $this->dumpNotifications($console, $middleware->getNotifications());
                     break;
                 case $matcher->match(ServicesFactory::EVENT_INSTANCE_BUILT . '.*', $event->getName()):
                     $console->debug(sprintf('Built service %s (%s)', $context['serviceSpecs']->getId(), is_object($context['instance']) ? get_class($context['instance']) : get_type($context['instance'])), 'services');
                     break;
                 case $matcher->match($event->getName(), '*.notify.*'):
                     $this->dumpNotifications($console, $event->getContext('notifications'));
                     break;
             }
         }
     });
 }
 public function route(ApplicationInterface $app) : RoutingResult
 {
     // add routes
     $routes = $app->getConfig()->subset(FastRoute::class);
     $dispatcher = \FastRoute\simpleDispatcher(function (RouteCollector $collector) use($routes) {
         foreach ($routes as $id => $data) {
             $collector->addRoute($data['method'], $data['route'], $data['handler']);
         }
     });
     // Fetch method and URI from somewhere
     $httpMethod = $app->getRequest()->getMethod();
     $uri = $_SERVER['REQUEST_URI'];
     // Strip query string (?foo=bar) and decode URI
     if (false !== ($pos = strpos($uri, '?'))) {
         $uri = substr($uri, 0, $pos);
     }
     $uri = rawurldecode($uri);
     $routeInfo = $dispatcher->dispatch($httpMethod, $uri);
     switch ($routeInfo[0]) {
         case Dispatcher::FOUND:
             $handler = $routeInfo[1];
             $vars = $routeInfo[2];
             // FastRoute does not allow to name routes for further reference,
             // so we name matched route "anonymous" by default
             $matchedRoute = new MatchedRoute($this, 'anonymous', $handler, $vars);
             return new RoutingResult($matchedRoute);
             break;
         case Dispatcher::NOT_FOUND:
         case Dispatcher::METHOD_NOT_ALLOWED:
         default:
             return new RoutingResult();
             break;
     }
 }
 /**
  * @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()]);
     }
 }
Ejemplo n.º 4
0
 /**
  * @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);
 }
Ejemplo n.º 5
0
 public function __invoke(ApplicationInterface $application)
 {
     $appConfig = $application->getConfig();
     foreach ($appConfig->packages->registered as $packageClass) {
         $application->getStep('init')->plug($packageClass);
     }
 }
Ejemplo n.º 6
0
 /**
  * @param Application $app
  *
  * @throws \ObjectivePHP\Config\Exception
  */
 public function __invoke(ApplicationInterface $app)
 {
     // setup autoloading for current package
     //
     // note that a relative path is relative to the application root directory!
     $app->getAutoloader()->addPsr4('Project\\Package\\Example\\', 'packages/Example/src');
     // init package here
     $configLoader = new DirectoryLoader();
     $configLoader->loadInto($app->getConfig(), __DIR__ . '/config');
 }
 /**
  * @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);
     }
 }
Ejemplo n.º 8
0
 /**
  * @param ApplicationInterface $app
  * @return mixed
  *
  */
 public function run(ApplicationInterface $app)
 {
     $path = rtrim($app->getRequest()->getUri()->getPath(), '/');
     // default to home
     if (!$path) {
         $path = '/';
     }
     // check if path is routed
     $aliases = $app->getConfig()->subset(UrlAlias::class);
     if ($aliases) {
         $path = $aliases[$path] ?? $path;
     }
     // look for matching route
     $routes = $app->getConfig()->subset(SimpleRoute::class)->reverse();
     /** @var SimpleRoute $route */
     $routed = false;
     foreach ($routes as $alias => $route) {
         if ($route->matches($app->getRequest())) {
             $app->getRequest()->setAction($route->getAction());
             $app->getRequest()->setRoute($alias);
             $routed = true;
             break;
         }
     }
     // inject route if none matched
     if (!$routed) {
         $app->getRequest()->setRoute($path);
     }
 }
 /**
  * @param ApplicationInterface $app
  *
  * @return null
  * @throws \ObjectivePHP\Config\Exception
  */
 public function __invoke(ApplicationInterface $app)
 {
     // init package here
     $configLoader = new DirectoryLoader();
     $packageConfig = $configLoader->load(__DIR__ . '/../config');
     $app->getConfig()->merge($packageConfig);
     $config = $app->getConfig();
     // if devtools are disabled by configuration, stop here
     if (!$config->get(EnableDevtools::class)) {
         return null;
     }
     // plug listeners according to configuration
     if ($config->get(DevtoolsMonitor::class . '.php-console')) {
         (new PhpConsoleListener())->__invoke($app);
     }
 }
Ejemplo n.º 10
0
 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);
         });
     }
 }
Ejemplo n.º 11
0
 /**
  * @param ApplicationInterface $app
  * @return bool
  * @throws Exception
  */
 public function run(ApplicationInterface $app) : bool
 {
     // check route filter
     if ($this->getFilter() != '*') {
         $request = $app->getRequest();
         if (!$request) {
             throw new Exception('Cannot run RouteFilter: no request has been set');
         }
         $route = $request->getRoute();
         if (!$route) {
             throw new Exception('Cannot run RouteFilter: no route has been set');
         }
         if (!$app->getRouteMatcher()->match($this->getFilter(), $route)) {
             return false;
         }
     }
     return true;
 }
Ejemplo n.º 12
0
 public function run(ApplicationInterface $app)
 {
     $response = $app->getResponse();
     if (!$response) {
         throw new Exception(sprintf('Cannot filter response ContentType against "%s" because no response has been set', $this->getFilter()->join(', ')));
     }
     $contentTypes = $response->getHeader('Content-Type');
     $result = false;
     $this->getFilter()->each(function ($filter) use($contentTypes, &$result) {
         foreach ($contentTypes as $contentType) {
             if (strpos($contentType, $filter) === 0) {
                 $result = true;
                 break;
             }
         }
     });
     return $result;
 }
 /**
  * @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();
 }
Ejemplo n.º 14
0
 /**
  * @param $className
  *
  * @return null|string
  */
 public function resolveActionFullyQualifiedName($className)
 {
     $registeredActionNamespaces = $this->application->getConfig()->get(ActionNamespace::class);
     foreach ((array) $registeredActionNamespaces as $namespace) {
         $fullClassName = $namespace . '\\' . $className;
         if (class_exists('\\' . $fullClassName)) {
             return $fullClassName;
         }
     }
     return null;
 }
Ejemplo n.º 15
0
 public function route(ApplicationInterface $app) : RoutingResult
 {
     $path = rtrim($app->getRequest()->getUri()->getPath(), '/');
     // default to home
     if (!$path) {
         $path = '/';
     }
     // check if path is routed
     $aliases = $app->getConfig()->subset(UrlAlias::class);
     if ($aliases) {
         $path = $aliases[$path] ?? $path;
     }
     $actionClass = $this->resolveActionClassName($path);
     $registeredActionNamespaces = $app->getConfig()->get(ActionNamespace::class);
     $action = $this->resolveActionFullyQualifiedName($actionClass, $registeredActionNamespaces);
     if (!$action) {
         return new RoutingResult();
     }
     // return empty RoutingResult
     return new RoutingResult(new MatchedRoute($this, $path, $action));
 }
Ejemplo n.º 16
0
 /**
  * @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));
     }
 }
Ejemplo n.º 17
0
 /**
  * @param ApplicationInterface $app
  *
  * @return mixed
  */
 protected function getViewName(ApplicationInterface $app)
 {
     return $app->getParam('view.template');
 }
Ejemplo n.º 18
0
 /**
  * @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()]);
 }
Ejemplo n.º 19
0
 /**
  * @param ApplicationInterface $app
  */
 public function __invoke(ApplicationInterface $app)
 {
     $response = $app->getResponse();
     $emitter = new SapiEmitter();
     $emitter->emit($response);
 }
Ejemplo n.º 20
0
 /**
  * @param ApplicationInterface $app
  * @return bool
  */
 public function run(ApplicationInterface $app) : bool
 {
     $env = (array) $this->getFilter();
     return in_array($app->getEnv(), $env);
 }
Ejemplo n.º 21
0
 /**
  * @param ApplicationInterface $application
  *
  * @return mixed
  */
 public function run(ApplicationInterface $app)
 {
     $app->setParam('layout.name', 'home');
 }
 /**
  * Instantiate Response
  *
  * @param ApplicationInterface $app
  */
 public function __invoke(ApplicationInterface $app)
 {
     // TODO handle CLI repsonse
     $app->setResponse(new HttpResponse());
 }
Ejemplo n.º 23
0
 /**
  * Shorthand to access ServicesFactory
  *
  * @return ServicesFactory
  */
 public function getServicesFactory() : ServicesFactory
 {
     return $this->application->getServicesFactory();
 }