private function hasRoutesConfigured() : bool { $slimContainer = $this->slimApp->getContainer(); $slimRouter = $slimContainer->get('router'); /** @var $slimRouter SlimRouter */ return (bool) count($slimRouter->getRoutes()); }
public function __construct(\Slim\App $app) { $this->app = $app; $this->view = $app->getContainer()->get('view'); $this->pdo = $app->getContainer()->get('pdo'); if (!$this->pdo instanceof PDO) { throw new \RuntimeException(sprintf('%s requires a PDO instance, app did not contain "PDO" key', __CLASS__)); } }
/** * @param String $method * @param Uri $uri * @param array $post */ protected function runApp($method, $uri, $post = []) { $this->buildApp(); $this->buildRequest($method, $uri, $post); $this->app->getContainer()['request'] = $this->request; $this->app->getContainer()['response'] = $this->response; $this->response = $this->app->run(true); $this->response->getBody()->rewind(); $this->html = $this->response->getBody()->getContents(); }
/** * Test extend single routes. */ public function testExtendSingle() { $this->assertCount(0, $this->slim_app->getContainer()->get('router')->getRoutes()); $this->model_router->mapModel('App\\Model\\User', null, null, function (Extender $extender) { $extender->extend('accounts'); }); $this->assertCount(3, $this->slim_app->getContainer()->get('router')->getRoutes()); /** @var Route $user_accounts_route */ $user_accounts_route = $this->slim_app->getContainer()->get('router')->getRoutes()['route2']; $this->assertEquals(['GET'], $user_accounts_route->getMethods()); $this->assertEquals('user_accounts', $user_accounts_route->getName()); }
protected function setRouteForPostTypes($postType, $defaultController) { $controllerPageMapping = $this->app->getContainer()->get(ControllerPageMappingField::class); /** * @FIXME: In future versions, need to change * adding routes to the map of get|post. All WP PAGES and POSTS must * coresponds to only GET method. Because it is has content only for reading. * All other logic like writing or another logic should be implemented in WIDGETS * or in controllers via declarring new routes and handlers for them. */ foreach ($this->wpService->get_posts(['numberposts' => -1, 'post_type' => $postType]) as $post) { $controller = $controllerPageMapping->getValue($post->ID); $this->app->map(['get', 'post'], parse_url(get_permalink($post), PHP_URL_PATH), $this->app->getContainer()->get(empty($controller) ? $defaultController : $controller))->setArgument('requestedEntity', $post); } }
/** * @param \swoole_http_request $request * @param \swoole_http_response $response * @throws \Exception */ public function __invoke($request, $response) { $this->app->getContainer()['environment'] = $this->app->getContainer()->factory(function () { return new Environment($_SERVER); }); $this->app->getContainer()['request'] = $this->app->getContainer()->factory(function ($container) { return Request::createFromEnvironment($container['environment']); }); $this->app->getContainer()['response'] = $this->app->getContainer()->factory(function ($container) { $headers = new Headers(['Content-Type' => 'text/html']); $response = new Response(200, $headers); return $response->withProtocolVersion($container->get('settings')['httpVersion']); }); /** * @var ResponseInterface $appResponse */ $appResponse = $this->app->run(true); // set http header foreach ($appResponse->getHeaders() as $key => $value) { $filter_header = function ($header) { $filtered = str_replace('-', ' ', $header); $filtered = ucwords($filtered); return str_replace(' ', '-', $filtered); }; $name = $filter_header($key); foreach ($value as $v) { $response->header($name, $v); } } // set http status $response->status($appResponse->getStatusCode()); // send response to browser if (!$this->isEmptyResponse($appResponse)) { $body = $appResponse->getBody(); if ($body->isSeekable()) { $body->rewind(); } $settings = $this->app->getContainer()->get('settings'); $chunkSize = $settings['responseChunkSize']; $contentLength = $appResponse->getHeaderLine('Content-Length'); if (!$contentLength) { $contentLength = $body->getSize(); } $totalChunks = ceil($contentLength / $chunkSize); $lastChunkSize = $contentLength % $chunkSize; $currentChunk = 0; while (!$body->eof() && $currentChunk < $totalChunks) { if (++$currentChunk == $totalChunks && $lastChunkSize > 0) { $chunkSize = $lastChunkSize; } $response->write($body->read($chunkSize)); if (connection_status() != CONNECTION_NORMAL) { break; } } $response->end(); } }
/** * @inheritdoc */ public function run($appNamespace = self::ROOT_NAMESPACE) { // // Each application must exist inside its own namespace. Chubby uses that namespace to search for modules. $this->appNamespace = $appNamespace; // // Slim can be initiated in one of two ways: // 1. Without a container. Slim will create the default container. // 2. Receiving a container in the constructor. We can pass Slim some settings and services // by passing a pre-created container. We do this here via a configuration file. $container = $this->getContainerConfig(); $this->slim = new \Slim\App($container); $container = $this->slim->getContainer(); // $this->modules = \Chubby\PackageLoader::loadModules($container); if (!is_array($this->modules) || !count($this->modules)) { throw new \Exception("Chubby Framework requires at least one module."); } // // Initialize the modules following the order given by each module's priority. foreach ($this->modules as $priority => $modules) { foreach ($modules as $module) { $module['object']->setApp($this); $module['object']->init(); } } // $this->slim->run(); return $this; }
public static function register(App $app, $config) { $app->getContainer()['imagecache'] = function () use($config) { return new Manager($config); }; $app->get("/{$config['path_web']}/{$config['path_cache']}/{preset}/{file:.*}", (new ImagecacheRegister())->request())->setName('onigoetz.imagecache'); }
/** * @param SlimApp $slimApp * @return SlimRoute */ private function getSlimRouteFromApplication(SlimApp $slimApp) { $slimRouter = $slimApp->getContainer()->get('router'); /** @var $slimRouter SlimRouter */ $slimRoutes = $slimRouter->getRoutes(); return $slimRoutes['route0']; }
public function testLoginLogout() { /** * @var Auth $auth * @var Request $request * @var Response $response */ $container = $this->app->getContainer(); $auth = $container->get("auth"); $request = $container->get('request'); $response = $container->get('response'); $middleware = $this->middleware; $middleware($request, $response, $this->app); /** @var Response $response */ $response = $auth->login($response, "*****@*****.**", "wrongpw"); $this->assertInstanceOf(Response::class, $response); $this->assertEmpty($response->getHeaders()); $this->assertNull($auth->getUser()); $this->assertFalse($auth->isAuthenticated()); /** @var Response $response */ $response = $auth->login($response, "*****@*****.**", "test1234"); $this->assertInstanceOf(Response::class, $response); $this->assertArrayHasKey("Set-Cookie", $response->getHeaders()); $this->assertInstanceOf(TestUser::class, $auth->getUser()); $this->assertTrue($auth->isAuthenticated()); /** @var Response $response */ $response = $auth->logout($response); $this->assertInstanceOf(Response::class, $response); $this->assertArrayHasKey("Set-Cookie", $response->getHeaders()); $this->assertNull($auth->getUser()); $this->assertFalse($auth->isAuthenticated()); }
/** * Load the module. This will run for all modules, use for routes mainly * @param string $moduleName Module name */ public function initModules(App $app) { $container = $app->getContainer(); $this->initDependencies($container); $this->initMiddleware($app); $this->initRoutes($app); }
public function load(array $settings = []) { $service = new SlimApp($settings); $provider = new ServiceProvider(); $provider->register($service->getContainer()); $this->setService($service); }
public function setUp() { $app = new App(); $kernel = new Kernel($app, $app->getContainer()); $kernel->registerServices(); $kernel->registerRoutes(); $this->app = $app; }
function __construct(\Slim\App $app, RequestInterface $request, ResponseInterface $response, $args = false) { $this->app = $app; $this->container = $app->getContainer(); $this->request = $request; $this->response = $response; $this->args = $args; }
public static function init(\Slim\App $app) { error_reporting(E_ALL); ini_set('display_errors', true); date_default_timezone_set('Asia/Shanghai'); $container = $app->getContainer(); $settings = $container->get('settings'); $settings['displayErrorDetails'] = true; $settings['core.baseNamespace'] = 'Application'; $settings['view.basePath'] = __DIR__; return parent::init($app); }
protected function dispatchApplication(array $server, array $pipe = []) { $app = new App(); $app->getContainer()['environment'] = function () use($server) { return new Environment($server); }; $middlewareFactory = new PhpDebugBarMiddlewareFactory(); $middleware = $middlewareFactory(); $app->add($middleware); foreach ($pipe as $pattern => $middleware) { $app->get($pattern, $middleware); } return $app->run(true); }
/** * Register DebugBar service. * * @param App $app * * @return void */ public function register(App $app) { $container = $app->getContainer(); $container['debugbar'] = function ($container) { return new SlimDebugBar($container, $this->settings); }; if (!$this->settings['enabled']) { return; } $app->group('/_debugbar', function () { $this->get('/open', 'Kitchenu\\Debugbar\\Controllers\\OpenHandlerController:handle')->setName('debugbar-openhandler'); $this->get('/assets/stylesheets', 'Kitchenu\\Debugbar\\Controllers\\AssetController:css')->setName('debugbar-assets-css'); $this->get('/assets/javascript', 'Kitchenu\\Debugbar\\Controllers\\AssetController:js')->setName('debugbar-assets-js'); }); $app->add(new Debugbar($container['debugbar'], $container['errorHandler'])); }
/** * @inheritdoc */ public function bootstrap(SlimApp $app) { $container = $app->getContainer(); $actionsMap = []; if (isset($container['_actionMaps'])) { $actionsMap = $container['_actionMaps']; } $actionsMap[] = get_class($this); $container['_actionMaps'] = $actionsMap; foreach ($this->actions() as $className) { $reflection = new \ReflectionClass($className); if ($reflection->implementsInterface(ActionInterface::class)) { $hasMiddleware = $reflection->implementsInterface(MiddlewareInterface::class); $this->implementAction($app, $className, $hasMiddleware); } } }
public function testMiddlewareIsWorkingAndEditorIsSet() { $app = new App(['settings' => ['debug' => true, 'whoops.editor' => 'sublime']]); $container = $app->getContainer(); $container['environment'] = function () { return Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); }; $app->get('/foo', function ($req, $res, $args) { return $res; }); $app->add(new WhoopsMiddleware()); // Invoke app $response = $app->run(); // Get added whoops handlers $handlers = $container['whoops']->getHandlers(); $this->assertEquals(2, count($handlers)); $this->assertEquals('subl://open?url=file://test_path&line=169', $handlers[0]->getEditorHref('test_path', 169)); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { if (false === is_file('composer.json')) { throw new Exception('Commands must be run from root of project.'); } try { $app = new App(); require 'src/routes.php'; $routes = $app->getContainer()->get('router')->getRoutes(); foreach ($routes as $route) { foreach ($route->getMethods() as $method) { $name = str_pad($route->getName(), 10, ' ', STR_PAD_LEFT); $method = str_pad($method, 8, ' ', STR_PAD_RIGHT); $routeStr = str_pad($route->getPattern(), 15, ' ', STR_PAD_RIGHT); $resolvesTo = is_string($route->getCallable()) ? $route->getCallable() : ''; $output->writeln('<info>' . $name . $method . $routeStr . $resolvesTo . '</info>'); } } } catch (Exception $e) { $output->writeln($e->getMessage()); } }
/** * Integration test IpRestrictMiddleware::_invoke() when the given IP is allowed. */ public function testIpAllow() { // Prepare the Request and the application. $app = new App(); // Setup a demo environment $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET', 'REMOTE_ADDR' => '127.0.0.2']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $headers->set('Accept', 'text/html'); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app->getContainer()['request'] = $req; $app->getContainer()['response'] = $res; // Set the options value. $this->options = ['error_code' => 403, 'exception_message' => 'NOT ALLOWED']; $app->add(new IpRestrictMiddleware($this->ipSet, false, $this->options)); $appMessage = 'I am In'; $app->get('/foo', function ($req, $res) use($appMessage) { $res->write($appMessage); return $res; }); $resOut = $app->run(); $body = (string) $resOut->getBody(); $this->assertEquals($appMessage, $body, 'The client is allowed to access the application.'); }
/** * AbstractFilterableMiddleware constructor. * @param App $app */ public function __construct(App $app) { $this->app = $app; $this->settings = $app->getContainer()->get('settings'); }
/** * @runInSeparateProcess */ public function testExceptionErrorHandlerDisplaysErrorDetails() { $app = new App(['settings' => ['displayErrorDetails' => true]]); // Prepare request and response objects $env = Environment::mock(['SCRIPT_NAME' => '/index.php', 'REQUEST_URI' => '/foo', 'REQUEST_METHOD' => 'GET']); $uri = Uri::createFromEnvironment($env); $headers = Headers::createFromEnvironment($env); $cookies = []; $serverParams = $env->all(); $body = new Body(fopen('php://temp', 'r+')); $req = new Request('GET', $uri, $headers, $cookies, $serverParams, $body); $res = new Response(); $app->getContainer()['request'] = $req; $app->getContainer()['response'] = $res; $mw = function ($req, $res, $next) { throw new \Exception('middleware exception'); }; $app->add($mw); $app->get('/foo', function ($req, $res) { return $res; }); $resOut = $app->run(); $this->assertEquals(500, $resOut->getStatusCode()); $this->expectOutputRegex('/.*middleware exception.*/'); }
<?php use Slim\App; use Slim\Views\Twig; require '../vendor/autoload.php'; $app = new App(); $view = new Twig('../resources/views'); $env = $view->getEnvironment(); $env->addGlobal('year', date('Y')); $container = $app->getContainer(); $container->register($view); // Routes $app->get('/', function ($request, $response, $args) { return $this->view->render($response, 'index.html.twig', ['page_title' => 'Project Mercury']); })->setName('index'); $app->run();
public function __construct(App $app = null, $param = null) { $this->app = $app; $this->container = $app->getContainer(); $this->undefinedObject = $param; }
/** * SlimアプリケーションのMockを作成 * * @param String $path アクセスするURI * @param String $method 使用するhttpメソッド * @return Object */ protected function create($path, $method = 'GET') { $app = new App(); $env = Environment::mock(['REQUEST_URI' => $path, 'REQUEST_METHOD' => $method]); $uri = Uri::createFromEnvironment($env); //$headers = Headers::createFromEnvironment($env); $headers = new Headers(['Content-Type' => 'application/json;charset=utf8']); $cookies = []; $serverParams = $env->all(); $this->request = new Request($method, $uri, $headers, $cookies, $serverParams, $this->body); $this->response = new Response(); $this->setContainer($app->getContainer()); return $app; }
public function testGetAppContainer() { $container = new Container([]); $app = new App($container); $this->assertInstanceOf('SlimAura\\Container', $app->getContainer()); }
<?php if (PHP_SAPI == 'cli-server') { // To help the built-in PHP dev server, check if the request was actually for // something which should probably be served as a static file $file = __DIR__ . preg_replace('#(\\?.*)$#', '', $_SERVER['REQUEST_URI']); if (is_file($file)) { return false; } } require __DIR__ . '/../vendor/autoload.php'; use Slim\App; use App\Loader\Kernel; use Slim\Middleware\DebugBar; use Slim\Routes\DebugBarRoutes; session_start(); // Instantiate the app $settings = (require __DIR__ . '/../config/settings.php'); $app = new App($settings); if ($app->getContainer()->get('settings')['debugbar'] === true) { $debugbar = new DebugBar(null, ['logger' => 'logger']); $app->add($debugbar); $routes = new DebugBarRoutes($app); $routes->registerRoutes(); } $kernel = new Kernel($app, $app->getContainer()); $kernel->registerServices(); $kernel->registerRoutes(); // Run app $app->run();
public function bootstrap(SlimApp $app) { $app->getContainer()->emitter->addListener('AfterRun', function ($e) { $e->getApp(); }); }
<?php // Include autoloader. require __DIR__ . '/../vendor/autoload.php'; use Slim\App; use Slim\Collection; $app = new App(); $settings = $app->getContainer()['settings']; /* @var Collection $settings */ // Set core configuration. $settings->replace(require __DIR__ . '/../config.php'); // Set local configuration. if (is_file(__DIR__ . '/../config.local.php')) { call_user_func(function () use(&$settings) { $config = (require __DIR__ . '/../config.local.php'); if (is_array($config)) { $settings->replace($config); } }); } // Bootstrap the application. foreach (require __DIR__ . '/../bootstrap.php' as $key => $value) { $app->getContainer()[$key] = $value; } // Load in functions. require __DIR__ . '/../functions.php'; // Load the routes. $routeFiles = glob(__DIR__ . '/../routes/*.php', GLOB_NOSORT); if (is_array($routeFiles)) { foreach ($routeFiles as $routeFile) { call_user_func(function ($file, $app) {