/** * @param $method * @param $path * @param $body * @param $options * @return Request */ protected function requestFactory($method, $path, $body = [], $options = []) { $uri = Uri::createFromString($path); $headers = new Headers(); $cookies = []; $_POST['_METHOD'] = $method; if (strtolower($method) != 'get' && is_array($body)) { foreach ($body as $key => $value) { $_POST[$key] = $value; } } $envMethod = 'POST'; if (strtolower($method) == 'get') { $envMethod = 'GET'; } $env = Environment::mock(['REQUEST_URI' => $path, 'REQUEST_METHOD' => $envMethod, 'HTTP_CONTENT_TYPE' => 'multipart/form-data; boundary=---foo']); $serverParams = $env->all(); $body = $this->buildBody($body); //echo $body->getContents(); // @todo // $request = new Request($method, $uri, $headers, $cookies, $serverParams, $body, []); $request = Request::createFromEnvironment($env); unset($_POST); return $request; }
/** * Perform request * * @param string $method * @param string $uri * @param array $params * @param array $server * @param string $content * * @throws \Slim\Exception\MethodNotAllowedException * @throws \Slim\Exception\NotFoundException */ public function request($method, $uri, array $params = [], array $server = [], $content = null) { $method = strtoupper($method); switch ($method) { case 'POST': case 'PUT': case 'PATCH': case 'DELETE': $this->server['slim.input'] = http_build_query($params); $query = ''; break; case 'GET': default: $query = http_build_query($params); break; } $server = array_merge($this->server, $server, ['CONTENT_TYPE' => 'application/json', 'REQUEST_URI' => $uri, 'REQUEST_METHOD' => $method, 'QUERY_STRING' => $query]); $env = Http\Environment::mock($server); $request = Http\Request::createFromEnvironment($env); $response = new Http\Response(); // dirty hack to set body of request :( if (!is_null($content)) { \Closure::bind(function ($request) use($content) { $request->bodyParsed = $content; }, null, $request)->__invoke($request); } $response = $this->app->__invoke($request, $response); $this->request = $request; $this->response = $response; }
/** * {@inheritdoc} */ public function register() { $this->getContainer()->share('settings', function () { return new Collection($this->defaultSettings); }); $this->getContainer()->share('environment', function () { return new Environment($_SERVER); }); $this->getContainer()->share('request', function () { return Request::createFromEnvironment($this->getContainer()->get('environment')); }); $this->getContainer()->share('response', function () { $headers = new Headers(['Content-Type' => 'text/html']); $response = new Response(200, $headers); return $response->withProtocolVersion($this->getContainer()->get('settings')['httpVersion']); }); $this->getContainer()->share('router', function () { return new Router(); }); $this->getContainer()->share('foundHandler', function () { return new RequestResponse(); }); $this->getContainer()->share('errorHandler', function () { return new Error($this->getContainer()->get('settings')['displayErrorDetails']); }); $this->getContainer()->share('notFoundHandler', function () { return new NotFound(); }); $this->getContainer()->share('notAllowedHandler', function () { return new NotAllowed(); }); $this->getContainer()->share('callableResolver', function () { return new CallableResolver($this->getContainer()); }); }
public function setUp() { $this->encryption = Mockery::mock(CookieEncryptionInterface::class); $this->request = Request::createFromEnvironment(Environment::mock()); $this->response = new Response(); $this->capturedRequest = null; }
public function setUp() { $this->request = Request::createFromEnvironment(Environment::mock()); $this->response = new Response(); $this->logger = new MemoryLogger(); $this->config = ['error' => 'critical', 'not-allowed' => 'info', 'not-found' => 'info']; }
public function requestFactory($method, $path) { $environment = Environment::mock(['REQUEST_METHOD' => $method, 'REQUEST_URI' => $path, 'QUERY_STRING' => 'foo=bar']); $request = Request::createFromEnvironment($environment); $request->withMethod('GET'); return $request; }
/** * Process the application given a request method and URI * * @param string $requestMethod the request method (e.g. GET, POST, etc.) * @param string $requestUri the request URI * @param array|object|null $requestData the request data * @return \Slim\Http\Response */ public function runApp($requestMethod, $requestUri, $requestData = null) { // Create a mock environment for testing with $environment = Environment::mock(['REQUEST_METHOD' => $requestMethod, 'REQUEST_URI' => $requestUri]); // Set up a request object based on the environment $request = Request::createFromEnvironment($environment); // Add request data, if it exists if (isset($requestData)) { $request = $request->withParsedBody($requestData); } // Set up a response object $response = new Response(); // Use the application settings $settings = (require __DIR__ . '/../../src/settings.php'); // Instantiate the application $app = new App($settings); // Set up dependencies require __DIR__ . '/../../src/dependencies.php'; // Register middleware if ($this->withMiddleware) { require __DIR__ . '/../../src/middleware.php'; } // Register routes require __DIR__ . '/../../src/routes.php'; // Process the application $response = $app->process($request, $response); // Return the response return $response; }
public function setUp() { $container = new \Slim\Container(include "./Skeleton/Config/test.config.php"); $this->controller = $container[DefaultController::class]; $this->response = new Response(); $this->request = Request::createFromEnvironment(Environment::mock()); $this->args = []; }
/** * @dataProvider environmentsProvider * @runInSeparateProcess * @preserveGlobalState disabled * * @param Environment $env * @param string $output */ public function testReturnStream($env, $output) { $request = Request::createFromEnvironment($env); ob_start(); tao_helpers_Http::returnStream($this->getStream(), null, $request); $result = ob_get_clean(); $this->assertEquals($output, $result); }
/** * @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(); } }
/** * */ public function testRunWithoutObjTypeIs404() { $request = Request::createFromEnvironment(Environment::mock()); $response = new Response(); $res = $this->obj->run($request, $response); $this->assertEquals(404, $res->getStatusCode()); $res = $this->obj->results(); $this->assertFalse($res['success']); }
/** * @dataProvider environmentsProvider * @preserveGlobalState disabled * * @param Environment $env */ public function testGetPayload($env) { $request = Request::createFromEnvironment($env); $datatableRequest = new DatatableRequest($request); $datatablePayload = new ConcreteDatatablePayload($datatableRequest); $datatablePayload->setSearchService($this->getSearchServiceMock($datatableRequest)); $payload = $datatablePayload->getPayload(); $this->assertTrue(is_array($payload)); }
/** * Assert that */ public function testRunWithInvalidCredentials() { $this->createUser('foo', 'foobar'); $request = Request::createFromEnvironment(Environment::mock(['QUERY_STRING' => 'username=test&password=test123'])); $response = new Response(); $res = $this->obj->run($request, $response); $this->assertFalse($this->obj->success()); $this->assertEquals(403, $res->getStatusCode()); }
public function testRunWithInvalidRecaptchaReturns404() { $request = Request::createFromEnvironment(Environment::mock(['QUERY_STRING' => 'token=foobar&username=foobar&password=foo&password_confirm=foo&g-recaptcha-response=foobar'])); $response = new Response(); $res = $this->obj->run($request, $response); $this->assertEquals(404, $res->getStatusCode()); $res = $this->obj->results(); $this->assertFalse($res['success']); }
/** * Create new container * * @param array $settings Associative array of settings. User settings are in a 'settings' sub-array */ public function __construct($settings = []) { $userSettings = []; if (isset($settings['settings'])) { $userSettings = $settings['settings']; unset($settings['settings']); } // Add settings factory that also collects the default settings $defaultSettings = $this->defaultSettings; $settings['factories']['settings'] = function ($c) use($userSettings, $defaultSettings) { return array_merge($defaultSettings, $userSettings); }; // Add default services if they aren't added already if (!isset($settings['environment'])) { $settings['factories']['environment'] = function ($c) { return new Environment($_SERVER); }; } if (!isset($settings['request'])) { $settings['factories']['request'] = function ($c) { return Request::createFromEnvironment($c['environment']); }; } if (!isset($settings['response'])) { $settings['factories']['response'] = function ($c) { $headers = new Headers(['Content-Type' => 'text/html']); $response = new Response(200, $headers); return $response->withProtocolVersion($c['settings']['httpVersion']); }; } if (!isset($settings['router'])) { $settings['factories']['router'] = function ($c) { return new Router(); }; } if (!isset($settings['callableResolver'])) { $settings['factories']['callableResolver'] = function ($c) { return new CallableResolver($c); }; } if (!isset($settings['foundHandler'])) { $settings['invokables']['foundHandler'] = RequestResponse::class; } if (!isset($settings['errorHandler'])) { $settings['factories']['errorHandler'] = function ($c) { return new Error($c->get('settings')['displayErrorDetails']); }; } if (!isset($settings['notFoundHandler'])) { $settings['invokables']['notFoundHandler'] = NotFound::class; } if (!isset($settings['notAllowedHandler'])) { $settings['invokables']['notAllowedHandler'] = NotAllowed::class; } parent::__construct($settings); }
/** * */ public function testRun() { $this->createUser('foo'); $request = Request::createFromEnvironment(Environment::mock(['QUERY_STRING' => 'obj_type=charcoal/admin/user'])); $response = new Response(); $res = $this->obj->run($request, $response); $this->assertEquals(200, $res->getStatusCode()); $res = $this->obj->results(); $this->assertTrue($res['success']); }
/** * Invoke middleware * * @param ServerRequestInterface $request PSR7 request object * @param ResponseInterface $response PSR7 response object * @param callable $next Next middleware callable * * @return ResponseInterface PSR7 response object */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { global $argv; $this->request = $request; if (isset($argv)) { list($call, $path, $params) = $argv; $this->request = \Slim\Http\Request::createFromEnvironment(\Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/' . $path . '?' . $params, 'QUERY_STRING' => $params])); unset($argv); } return $next($this->request, $response); }
public function getMockedController($token, $result) { $req = Request::createFromEnvironment(Env::mock()); $res = new Response(); $args = ['token' => $token]; $db = $this->getMockBuilder('\\Abridger\\DB')->disableOriginalConstructor()->setMethods(['prepare'])->getMock(); $query = $this->getMock('\\PDOStatement'); $query->method('fetch')->willReturn($result); $db->method('prepare')->willReturn($query); $cnt = new Container(['DB' => $db]); return new \Abridger\Controller\Web($cnt, $req, $res, $args); }
/** * */ public function testRun() { $container = $this->container(); $userProto = $container['model/factory']->create(User::class); $userProto->source()->createTable(); $request = Request::createFromEnvironment(Environment::mock(['QUERY_STRING' => 'obj_type=charcoal/admin/user&obj_orders[]=foo&obj_orders[]=bar'])); $response = new Response(); $res = $this->obj->run($request, $response); $this->assertEquals(200, $res->getStatusCode()); $res = $this->obj->results(); $this->assertTrue($res['success']); }
public function getMockedController($url, $result) { $req = Request::createFromEnvironment(Env::mock(['REQUEST_METHOD' => 'POST', 'url' => $url])); $req = $req->withParsedBody(['url' => $url]); $res = new Response(); $args = ['url' => $url]; $db = $this->getMockBuilder('\\Abridger\\DB')->disableOriginalConstructor()->setMethods(['prepare', 'lastInsertId'])->getMock(); $query = $this->getMock('\\PDOStatement'); $db->method('prepare')->willReturn($query); $db->method('lastInsertId')->willReturn($result); $cnt = new Container(['DB' => $db]); return new \Abridger\Controller\Api($cnt, $req, $res, $args); }
public function testCallStartsSession() { $session = new SessionMiddleware([]); $request = Request::createFromEnvironment(Environment::mock()); $response = new Response(); $next = function ($request, $response, $next) { return $response; }; $this->assertEquals(PHP_SESSION_NONE, session_status()); @$session($request, $response, $next); // silence cookie warning $this->assertEquals(PHP_SESSION_ACTIVE, session_status()); }
private function registerDefaultServices($settings) { $this->set('settings', new Collection($settings)); $this->set('environment', new Environment($_SERVER)); $this->set('request', Request::createFromEnvironment($this->get('environment'))); $this->set('response', (new Response(200, new Headers(['Content-Type' => 'text/html; charset=UTF-8'])))->withProtocolVersion($settings['httpVersion'])); $this->set('router', new Router()); $this->set('foundHandler', new RequestResponse()); $this->set('errorHandler', new Error($settings['displayErrorDetails'])); $this->set('notFoundHandler', new NotFound()); $this->set('notAllowedHandler', new NotAllowed()); $this->set('callableResolver', new CallableResolver($this)); }
public function testGetNoLocale() { $router = new \Slim\Router(); $container = new \Slim\Container(); $container['aimeos'] = new \Aimeos\Bootstrap(); $container['aimeos_config'] = new \Aimeos\Slim\Base\Config($container, array()); $container['aimeos_context'] = new \Aimeos\MShop\Context\Item\Standard(); $container['aimeos_i18n'] = new \Aimeos\Slim\Base\I18n($container); $container['request'] = \Slim\Http\Request::createFromEnvironment(\Slim\Http\Environment::mock()); $container['response'] = new \Slim\Http\Response(); $object = new \Aimeos\Slim\Base\View($container); $attr = array('site' => 'unittest', 'locale' => 'en', 'currency' => 'EUR'); $view = $object->create($container['aimeos_config']->get(), $container['request'], $container['response'], $attr, array()); $this->assertInstanceOf('\\Aimeos\\MW\\View\\Iface', $view); }
/** * Invoke middleware * * @param ServerRequestInterface $request PSR7 request object * @param ResponseInterface $response PSR7 response object * @param callable $next Next middleware callable * * @return ResponseInterface PSR7 response object */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { global $argv; $this->request = $request; if (isset($argv)) { $path = $this->get($argv, 1); $method = $this->get($argv, 2); $params = $this->get($argv, 3); if (strtoupper($method) === 'GET') { $this->request = \Slim\Http\Request::createFromEnvironment(\Slim\Http\Environment::mock(['REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $this->getUri($path, $params), 'QUERY_STRING' => $params])); } unset($argv); } return $next($this->request, $response); }
public function call($method, $path, $params = array(), $body = '') { $app = new \Slim\App(array('settings' => array('determineRouteBeforeAppMiddleware' => true))); $settings = array('disableSites' => false, 'routes' => array('admin' => '/{site}/admin', 'account' => '/{site}', 'default' => '/{site}', 'confirm' => '/{site}', 'update' => '/{site}')); $boot = new \Aimeos\Slim\Bootstrap($app, $settings); $boot->setup(dirname(__DIR__) . '/ext')->routes(dirname(__DIR__) . '/src/aimeos-routes.php'); $c = $app->getContainer(); $env = \Slim\Http\Environment::mock(array('REQUEST_METHOD' => $method, 'REQUEST_URI' => $path, 'QUERY_STRING' => http_build_query($params))); $c['request'] = \Slim\Http\Request::createFromEnvironment($env); $c['request']->getBody()->write($body); $c['response'] = new \Slim\Http\Response(); $twigconf = array('cache' => sys_get_temp_dir() . '/aimeos-slim-twig-cache'); $c['view'] = new \Slim\Views\Twig(dirname(__DIR__) . '/templates', $twigconf); $c['view']->addExtension(new \Slim\Views\TwigExtension($c['router'], $c['request']->getUri())); return $app->run(true); }
/** * Returns a new context object * * @param \Interop\Container\ContainerInterface $container Dependency injection container * @return \Aimeos\MShop\Context\Item\Standard Context object */ protected static function getContext(\Interop\Container\ContainerInterface $container) { $aimeos = $container->get('aimeos'); $context = $container->get('aimeos_context')->get(false, array(), 'command'); $env = \Slim\Http\Environment::mock(); $request = \Slim\Http\Request::createFromEnvironment($env); $response = new \Slim\Http\Response(); $tmplPaths = $aimeos->getCustomPaths('controller/jobs/templates'); $view = $container->get('aimeos_view')->create($context->getConfig(), $request, $response, array(), $tmplPaths); $langManager = \Aimeos\MShop\Factory::createManager($context, 'locale/language'); $langids = array_keys($langManager->searchItems($langManager->createSearch(true))); $i18n = $container->get('aimeos_i18n')->get($langids); $context->setEditor('aimeos:jobs'); $context->setView($view); $context->setI18n($i18n); return $context; }
/** * This method will be called when WP will execute * ajax action handler, and will be stop whole PHP * process execution at the end of execution of this * method, because WP work in such a way. */ public function __invoke() { $response = $this->factory->make(Response::class); $request = Request::createFromEnvironment($this->factory->make(Environment::class, ['items' => $_SERVER + $_REQUEST])); $callable = $this->callable; $result = $callable($request, $response); if (!$result instanceof MessageInterface) { echo $result; } else { foreach ($result->getHeaders() as $name => $headers) { foreach ($headers as $header) { @header($name . ': ' . $header); } } echo (string) $result->getBody(); } $this->wpService->wp_die(); }
public function testGetSections() { $app = new \Slim\App(array()); $basedir = dirname(dirname(__DIR__)); $settings = (require $basedir . '/src/aimeos-default.php'); $settings['page']['test'] = array('catalog/filter', 'basket/mini'); $settings['disableSites'] = false; $boot = new \Aimeos\Slim\Bootstrap($app, $settings); $boot->setup($basedir . '/ext')->routes($basedir . '/src/aimeos-routes.php'); $response = new \Slim\Http\Response(); $request = \Slim\Http\Request::createFromEnvironment(\Slim\Http\Environment::mock()); $object = new \Aimeos\Slim\Base\Page($app->getContainer()); $result = $object->getSections('test', $request, $response, array('site' => 'unittest')); $this->assertArrayHasKey('aiheader', $result); $this->assertArrayHasKey('aibody', $result); $this->assertArrayHasKey('catalog/filter', $result['aibody']); $this->assertArrayHasKey('catalog/filter', $result['aiheader']); $this->assertArrayHasKey('basket/mini', $result['aibody']); $this->assertArrayHasKey('basket/mini', $result['aiheader']); }
public function __construct(array $userSettings = []) { parent::__construct(); $this["settings"] = function ($c) use($userSettings) { return array_merge($c->defaultSettings, $userSettings); }; $this["environment"] = function () { return new Environment($_SERVER); }; $this["request"] = $this->factory(function ($c) { return Request::createFromEnvironment($c["environment"]); }); $this["response"] = $this->factory(function ($c) { $headers = new Headers(["Content-Type" => "text/html"]); $response = new Response(200, $headers); return $response->withProtocolVersion($c["settings"]["httpVersion"]); }); $this["router"] = function ($c) { return (new Router())->setContainer($c); }; }
/** * Perform request * * @param string $method * @param string $uri * @param array $params * @param array $server * * @throws \Slim\Exception\MethodNotAllowedException * @throws \Slim\Exception\NotFoundException */ public function request($method, $uri, array $params = [], array $server = []) { $method = strtoupper($method); switch ($method) { case 'POST': case 'PUT': case 'PATCH': case 'DELETE': $this->server['slim.input'] = http_build_query($params); $query = ''; break; case 'GET': default: $query = http_build_query($params); break; } $server = array_merge($this->server, $server, ['REQUEST_URI' => $uri, 'REQUEST_METHOD' => $method, 'QUERY_STRING' => $query]); $env = Http\Environment::mock($server); $request = Http\Request::createFromEnvironment($env); $response = new Http\Response(); $response = $this->app->__invoke($request, $response); $this->request = $request; $this->response = $response; }