/** * {@inheritdoc} */ public function hydrate(Jarvis $app) { $app['annoReader'] = function ($app) { $cache = null; if (isset($app['doctrine.cache'])) { $cache = new DoctrineCache($app['doctrine.cache']); } return new Reader(new Parser(), $cache ?: new ArrayCache()); }; $app->lock('annoReader'); $app->addReceiver(JarvisEvents::CONTROLLER_EVENT, function (ControllerEvent $event) use($app) { $app->request->attributes->add((array) $event->arguments()); if (!is_array($event->callback())) { return; } list($controller, $action) = $event->callback(); $annotations = array_merge($app->annoReader->getClassAnnotations($controller)->toArray(), $app->annoReader->getMethodAnnotations($controller, $action)->toArray()); $handlers = $app->find(self::ANNO_SERVICE_HANDLER_BASE_ID . '*'); foreach ($annotations as $annotation) { foreach ($handlers as $handler) { if ($handler instanceof AnnotationHandlerInterface && $handler->supports($annotation)) { $handler->handle($annotation); } } } $arguments = []; $reflectionMethod = new \ReflectionMethod($controller, $action); foreach ($reflectionMethod->getParameters() as $reflectionParam) { if ($app->request->attributes->has($name = $reflectionParam->getName())) { $arguments[$name] = $app->request->attributes->get($name); } } $event->setArguments($arguments); }); }
public function hydrate(Jarvis $app) { $app['doctrine.cache'] = function () { return new VoidCache(); }; $app['doctrine.annotation.driver'] = function () { return new AnnotationDriver(new AnnotationReader()); }; $app['entyMgr'] = function (Jarvis $app) : EntityManagerInterface { $settings = $app['doctrine.settings']; $cache = $app['doctrine.cache']; $config = Setup::createConfiguration($settings['debug'], $settings['proxies_dir'], $cache); $driver = $app['doctrine.annotation.driver']; if (isset($settings['entities_paths'])) { $driver->addPaths((array) $settings['entities_paths']); } AnnotationRegistry::registerLoader('class_exists'); $config->setMetadataDriverImpl($driver); $config->setAutoGenerateProxyClasses($settings['debug']); $config->setMetadataCacheImpl($cache); $config->setResultCacheImpl($cache); $config->setQueryCacheImpl($cache); $entyMgr = EntityManager::create($settings['dbal'], $config); if (isset($app['doctrine.orm.entyMgr.decorator']) && is_string($fqcn = $app['doctrine.orm.entyMgr.decorator']) && is_subclass_of($fqcn, EntityManagerDecorator::class)) { $entyMgr = new $fqcn($entyMgr); } $entyMgr->getEventManager()->addEventListener([Events::preRemove, Events::postRemove, Events::prePersist, Events::postPersist, Events::preUpdate, Events::postUpdate, Events::postLoad, Events::preFlush, Events::onFlush, Events::postFlush, Events::onClear], new EventListener($app)); $app->broadcast(DoctrineReadyEvent::READY_EVENT, new DoctrineReadyEvent($entyMgr)); return $entyMgr; }; $app['db_conn'] = function ($app) { $app['entyMgr']->getConnection(); }; $app->lock(['entyMgr', 'db_conn', 'doctrine.annotation.driver']); }
protected function mountEventReceivers(Jarvis $app) { $app->on(BroadcasterInterface::EXCEPTION_EVENT, function (ExceptionEvent $event) use($app) : void { $throwable = $event->exception(); $msg = sprintf('[%s] error in %s at line %s with message: %s', get_class($throwable), $throwable->getFile(), $throwable->getLine(), $throwable->getMessage()); if (!$app['debug']) { error_log($msg); $msg = ''; } $event->setResponse(new Response($msg, Response::HTTP_INTERNAL_SERVER_ERROR)); }, BroadcasterInterface::RECEIVER_LOW_PRIORITY); $app->on(BroadcasterInterface::CONTROLLER_EVENT, function (ControllerEvent $event) use($app) : void { $finalArgs = []; $rawArgs = $event->arguments(); $refMethod = new \ReflectionMethod($event->callback(), '__invoke'); foreach ($refMethod->getParameters() as $refParam) { if (null !== ($refClass = $refParam->getClass())) { if (isset($app[$refClass->getName()])) { $finalArgs[$refParam->getPosition()] = $app[$refClass->getName()]; continue; } } if (in_array($refParam->name, array_keys($rawArgs))) { $finalArgs[$refParam->getPosition()] = $rawArgs[$refParam->name]; } } $event->setArguments($finalArgs); }, BroadcasterInterface::RECEIVER_LOW_PRIORITY); }
/** * {@inheritdoc} */ public function hydrate(Jarvis $container) { $container['twig'] = function ($container) { $config = array_merge(['auto-reload' => true, 'debug' => $container->debug, 'strict_variables' => true], $container->settings->get('twig', [])); if (!isset($config['templates_paths'])) { throw new \LogicException('Parameter `templates_paths` is missing to configure Twig.'); } $loader = new \Twig_Loader_Filesystem($config['templates_paths'], $config); return new \Twig_Environment($loader); }; $container->lock('twig'); }
/** * {@inheritdoc} */ public function hydrate(Jarvis $app) { $app['twig'] = function (Jarvis $app) : \Twig_Environment { $settings = array_merge(['auto_reload' => true, 'debug' => $app['debug'], 'strict_variables' => true], (array) ($app['twig.settings'] ?? [])); if (!isset($settings['templates_paths'])) { throw new \LogicException('Parameter `templates_paths` is missing to configure Twig.'); } $twig = new \Twig_Environment(new \Twig_Loader_Filesystem($settings['templates_paths']), $settings); $app->broadcast(TwigReadyEvent::READY_EVENT, new TwigReadyEvent($twig)); return $twig; }; $app->lock('twig'); }
public function analyze(Request $request = null) { $request = $request ?: $this->request; $response = null; $key = $request->getPathInfo(); if ($this['http.cache']->contains($key)) { $value = $this['http.cache']->fetch($key); $content = $value['content']; $modified = \DateTime::createFromFormat('Y-m-d H:i:s', $value['modified']); $statusCode = Response::HTTP_OK; $ifModified = $this->request->headers->get('if-modified-since', null); if (null !== $ifModified) { $ifModified = \DateTime::createFromFormat('D, d M Y H:i:s T', $ifModified); if ($modified->getTimestamp() === $ifModified->getTimestamp()) { $content = null; $statusCode = Response::HTTP_NOT_MODIFIED; } } $response = new Response($content, $statusCode); $response->setLastModified($modified); } if (null === $response) { $this->forceHydrate(); $response = parent::analyze($request); } return $response; }
public function testBeginRoute() { $app = new Jarvis(); $response = $app->run(Request::create('/hello/jarvis')); $this->assertSame(Response::HTTP_NOT_FOUND, $response->getStatusCode()); $app['router']->beginRoute()->setPattern('/hello/{name}')->setHandler(function ($name) { return "Hello {$name}!"; })->end()->beginRoute('with_params')->setPattern('/hello/{name:\\w+}/{id:\\d+}')->setHandler(function ($name, $id) { return "{$name} ({$id})"; })->end(); $response = $app->run(Request::create('/hello/jarvis')); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); $this->assertSame('Hello jarvis!', $response->getContent()); $response = $app->run(Request::create('/hello/jarvis/123')); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); $this->assertSame('jarvis (123)', $response->getContent()); }
/** * {@inheritdoc} */ public function hydrate(Jarvis $jarvis) { $jarvis['annotation.handler.rest.pagination'] = function ($jarvis) { return new PaginationHandler($jarvis->request); }; $jarvis['annotation.handler.rest.sort'] = function ($jarvis) { return new SortHandler($jarvis->request); }; $jarvis['annotation.handler.rest.criteria'] = function ($jarvis) { return new CriteriaHandler($jarvis->request); }; $jarvis->addReceiver(JarvisEvents::EXCEPTION_EVENT, function (ExceptionEvent $event) { $exception = $event->getException(); if (!$exception instanceof RestHttpException) { return; } $event->setResponse(new JsonResponse(['reason' => $exception->getMessage()], 0 === $exception->getCode() ? Response::HTTP_INTERNAL_SERVER_ERROR : $exception->getCode())); }, Jarvis::RECEIVER_HIGH_PRIORITY); }
public function testControllerSmartTypeHint() { $app = new Jarvis(['debug' => true]); $app['router']->beginRoute()->setHandler(function (\DateTime $datetime) { return str_replace(':', 'h', $datetime->format('d/m/Y H:i')); })->end(); $response = $app->run(); $this->assertSame(Response::HTTP_INTERNAL_SERVER_ERROR, $response->getStatusCode()); $app['current_datetime'] = function () { return new \DateTime('1988-06-08 00:00:00'); }; $response = $app->run(); $this->assertSame(Response::HTTP_INTERNAL_SERVER_ERROR, $response->getStatusCode()); $app['current_datetime'] = function () : \DateTime { return new \DateTime('1988-06-08 00:00:00'); }; $response = $app->run(); $this->assertSame(Response::HTTP_OK, $response->getStatusCode()); $this->assertSame('08/06/1988 00h00', $response->getContent()); $this->assertTrue(isset($app['DateTime'])); }
/** * {@inheritdoc} */ public function hydrate(Jarvis $jarvis) { $doctrineConfig = $jarvis->settings->get('doctrine', []); if (empty($doctrineConfig)) { throw new \LogicException('You need to configure DoctrineORM Skill.'); } /* DBAL */ $jarvis['dbal_config'] = new \Doctrine\DBAL\Configuration(); $jarvis->lock('dbal_config'); $jarvis['dbal_connection'] = function ($jarvis) use($doctrineConfig) { return \Doctrine\DBAL\DriverManager::getConnection($doctrineConfig['db'], $jarvis->dbal_config); }; /* Doctrine ORM */ $jarvis['doctrine_orm.entity_path'] = [$doctrineConfig['orm']['entity_path']]; $jarvis['doctrine_orm.debug'] = $doctrineConfig['orm']['debug']; $jarvis['doctrine.orm_config'] = function ($jarvis) { return \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($jarvis['doctrine_orm.entity_path'], $jarvis['doctrine_orm.debug']); }; $jarvis['doctrine_orm.entity.manager'] = function ($jarvis) use($doctrineConfig) { return \Doctrine\ORM\EntityManager::create($doctrineConfig['db'], $jarvis['doctrine.orm_config']); }; }
public function testBroadcastTerminateEventOnDestruct() { $app = new Jarvis(); $receiver = new FakeReceiver(); $app->on(BroadcasterInterface::TERMINATE_EVENT, [$receiver, 'onEventBroadcast']); $this->assertNull($receiver->event); unset($app); gc_collect_cycles(); $this->assertNotNull($receiver->event); $this->assertInstanceOf(SimpleEvent::class, $receiver->event); }
/** * @expectedException \LogicException * @expectedMessageException Permanent event cannot be broadcasted multiple times. */ public function testForbidPermanentEventMultiBroadcast() { $app = new Jarvis(); $permanentEvent = new PermanentEvent(); $name = 'permanent.event'; $app->broadcast($name, $permanentEvent); $app->broadcast($name, $permanentEvent); }