The information contained in the URI always take precedence
over the other information (server and parameters).
public static create ( string $uri, string $method = 'GET', array $parameters = [], array $cookies = [], array $files = [], array $server = [], string $content = null ) : |
||
$uri | string | The URI |
$method | string | The HTTP method |
$parameters | array | The query (GET) or request (POST) parameters |
$cookies | array | The request cookies ($_COOKIE) |
$files | array | The request files ($_FILES) |
$server | array | The server parameters ($_SERVER) |
$content | string | The raw body data |
리턴 | A Request instance |
/** * Perform an action on a Contenttype record. * * The action part of the POST request should take the form: * [ * contenttype => [ * id => [ * action => [field => value] * ] * ] * ] * * For example: * [ * 'pages' => [ * 3 => ['modify' => ['status' => 'held']], * 5 => null, * 4 => ['modify' => ['status' => 'draft']], * 1 => ['delete' => null], * 2 => ['modify' => ['status' => 'published']], * ], * 'entries' => [ * 4 => ['modify' => ['status' => 'published']], * 1 => null, * 5 => ['delete' => null], * 2 => null, * 3 => ['modify' => ['title' => 'Drop Bear Attacks']], * ] * ] * * @param Request $request Symfony Request * * @return Response */ public function action(Request $request) { // if (!$this->checkAntiCSRFToken($request->get('bolt_csrf_token'))) { // $this->app->abort(Response::HTTP_BAD_REQUEST, Trans::__('Something went wrong')); // } $contentType = $request->get('contenttype'); $actionData = $request->get('actions'); if ($actionData === null) { throw new \UnexpectedValueException('No content action data provided in the request.'); } foreach ($actionData as $contentTypeSlug => $recordIds) { if (!$this->getContentType($contentTypeSlug)) { // sprintf('Attempt to modify invalid ContentType: %s', $contentTypeSlug); continue; } else { $this->app['storage.request.modify']->action($contentTypeSlug, $recordIds); } } $referer = Request::create($request->server->get('HTTP_REFERER')); $taxonomy = null; foreach (array_keys($this->getOption('taxonomy', [])) as $taxonomyKey) { if ($referer->query->get('taxonomy-' . $taxonomyKey)) { $taxonomy[$taxonomyKey] = $referer->query->get('taxonomy-' . $taxonomyKey); } } $options = (new ListingOptions())->setOrder($referer->query->get('order'))->setPage($referer->query->get('page_' . $contentType))->setFilter($referer->query->get('filter'))->setTaxonomies($taxonomy); $context = ['contenttype' => $this->getContentType($contentType), 'multiplecontent' => $this->app['storage.request.listing']->action($contentType, $options), 'filter' => array_merge((array) $taxonomy, (array) $options->getFilter()), 'permissions' => $this->getContentTypeUserPermissions($contentType, $this->users()->getCurrentUser())]; return $this->render('@bolt/async/record_list.twig', ['context' => $context]); }
public function testAssetsController() { $assetsControler = new AssetsController(); $request = new Request(); $req = $request->create('/assets?application=Towel&path=css/towel_test.css', 'GET'); $response = $assetsControler->index($req); $this->assertEquals('200', $response->getStatusCode()); $this->assertEquals('body { font-size: 20px; }', $response->getContent()); $req = $request->create('/assets?application=Towel&path=css/Error.css', 'GET'); $response = $assetsControler->index($req); $this->assertEquals('404', $response->getStatusCode()); }
/** * @expectedException RuntimeException * @expectedExceptionMessage Test Exception */ public function testExceptionListenerDisabledByDefault() { $app = $this->createApplication(); $this->assertFalse($app['new_relic.log_exceptions']); $app['new_relic.interactor.real']->expects($this->never())->method('noticeException'); $response = $app->handle(Request::create('/error')); }
public function testUpdateResult() { $this->allowLogin($this->getApp()); $this->setRequest(Request::create('/bolt/dbupdate_result')); $this->checkTwigForTemplate($this->getApp(), '@bolt/dbcheck/dbcheck.twig'); $this->controller()->updateResult($this->getRequest()); }
public function setUp() { $this->document = $this->buildMock('Symfony\\Cmf\\Component\\Routing\\Tests\\Enhancer\\RouteObject'); $mapping = array('Symfony\\Cmf\\Component\\Routing\\Tests\\Enhancer\\RouteObject' => 'cmf_content.controller:indexAction'); $this->mapper = new FieldByClassEnhancer('_content', '_controller', $mapping); $this->request = Request::create('/test'); }
protected function checkRouteResponse(Application $app, $path, $expectedContent, $method = 'get', $message = null) { $app->register(new ServiceControllerServiceProvider()); $request = Request::create($path, $method); $response = $app->handle($request); $this->assertEquals($expectedContent, $response->getContent(), $message); }
public function __invoke(ServiceManagerInterface $serviceManager, array $moreParams = []) { if (!isset($moreParams['buffer'])) { throw new Exception\UnexpectedValueException('Could not parse request.'); } /** @var RequestParser $requestParser */ $requestParser = $serviceManager->get('RequestParser'); /** @var Request $request */ $request = null; $requestParser->on(['state'], function (Event $event, $method, $path, $version) use(&$request) { $request = Request::create($path, $method); $event->getEventEmitter()->on(['header'], function (Event $e, $headerName, $headerValue) use($request) { /** @var Request $request */ $name = \str_replace('-', '_', \strtoupper($headerName)); if ($name === 'COOKIE') { $cookieData = []; parse_str($headerValue, $cookieData); $request->setCookieParams(new ArrayObject($cookieData)); } else { $request->setHeader($name, $headerValue); } }); $event->getEventEmitter()->on(['body'], function (Event $e, $body) use($request) { /** @var Request $request */ if (!in_array($request->getMethod(), ['GET', 'HEAD']) && !empty($body)) { $postData = []; parse_str($body, $postData); $request->setPostParams(new ArrayObject($postData)); } }); }); $requestParser->parse($moreParams['buffer']); return $request; }
public function testImplicitGrant() { // Start session manually. $session = new Session(new MockFileSessionStorage()); $session->start(); // Query authorization endpoint with response_type = token. $parameters = array('response_type' => 'token', 'client_id' => 'http://democlient1.com/', 'redirect_uri' => 'http://democlient1.com/redirect_uri', 'scope' => 'demoscope1', 'state' => $session->getId()); $server = array('PHP_AUTH_USER' => 'demousername1', 'PHP_AUTH_PW' => 'demopassword1'); $client = $this->createClient(); $crawler = $client->request('GET', '/api/oauth2/authorize', $parameters, array(), $server); $this->assertTrue($client->getResponse()->isRedirect()); // Check basic auth response that can simply compare. $authResponse = Request::create($client->getResponse()->headers->get('Location'), 'GET'); $this->assertEquals('http://democlient1.com/redirect_uri', $authResponse->getSchemeAndHttpHost() . $authResponse->getBaseUrl() . $authResponse->getPathInfo()); // Check basic token response that can simply compare. $tokenResponse = $authResponse->query->all(); $this->assertEquals('bearer', $tokenResponse['token_type']); $this->assertEquals('demoscope1', $tokenResponse['scope']); $this->assertEquals($session->getId(), $tokenResponse['state']); // Query debug endpoint with access_token. $parameters = array(); $server = array('HTTP_Authorization' => implode(' ', array('Bearer', $tokenResponse['access_token']))); $client = $this->createClient(); $crawler = $client->request('GET', '/api/oauth2/debug', $parameters, array(), $server); $debugResponse = json_decode($client->getResponse()->getContent(), true); $this->assertEquals('demousername1', $debugResponse['username']); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $session = new Session(); $request = Request::create('/'); $request->setSession($session); /** @var RequestStack $stack */ $stack = $this->container->get('request_stack'); $stack->pop(); $stack->push($request); // Set the current user to one that can access comments. Specifically, this // user does not have access to the 'administer comments' permission, to // ensure only published comments are visible to the end user. $current_user = $this->container->get('current_user'); $current_user->setAccount($this->createUser(array(), array('access comments'))); // Install tables and config needed to render comments. $this->installSchema('comment', array('comment_entity_statistics')); $this->installConfig(array('system', 'filter', 'comment')); // Comment rendering generates links, so build the router. $this->installSchema('system', array('router')); $this->container->get('router.builder')->rebuild(); // Set up a field, so that the entity that'll be referenced bubbles up a // cache tag when rendering it entirely. $this->addDefaultCommentField('entity_test', 'entity_test'); }
public function testShouldBootAndHandleRequest() { if (version_compare(PHP_VERSION, '5.6', '>=')) { $this->markTestSkipped('CodeIgniter v2.1 is not compatible with PHP >= 5.6'); } $session = new Session(new MockArraySessionStorage()); $request = Request::create('/welcome/'); $request->setSession($session); $requestStack = $this->prophesize('Symfony\\Component\\HttpFoundation\\RequestStack'); $requestStack->getCurrentRequest()->willReturn($request); $container = $this->prophesize('Symfony\\Component\\DependencyInjection\\ContainerInterface'); $container->get('request_stack')->willReturn($requestStack->reveal()); $container->getParameter(Argument::any())->willReturn('foo'); $container->set(Argument::type('string'), Argument::any())->shouldBeCalled(); $classLoader = new CodeIgniterClassLoader(); $kernel = new CodeIgniterKernel(); $kernel->setRootDir($_ENV['THEODO_EVOLUTION_FAKE_PROJECTS'] . '/codeigniter21'); $kernel->setOptions(array('environment' => 'prod', 'version' => '2.1.4', 'core' => false)); $kernel->setClassLoader($classLoader); $kernel->boot($container->reveal()); $this->assertTrue($kernel->isBooted()); $this->assertTrue($classLoader->isAutoloaded()); // CodeIgniter creates a global variables $this->assertArrayHasKey('BM', $GLOBALS); $this->assertArrayHasKey('EXT', $GLOBALS); $this->assertArrayHasKey('CFG', $GLOBALS); $this->assertArrayHasKey('UNI', $GLOBALS); $this->assertArrayHasKey('URI', $GLOBALS); $this->assertArrayHasKey('RTR', $GLOBALS); $this->assertArrayHasKey('OUT', $GLOBALS); $this->assertArrayHasKey('SEC', $GLOBALS); $response = $kernel->handle($request, 1, true); $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response); $this->assertEquals(200, $response->getStatusCode()); }
public function testResponse() { $request = Request::create('/thumbs/320x240r/generic-logo.jpg', 'GET'); $responder = $this->initializeResponder($request); $response = $responder->respond(); $this->assertInstanceOf(Response::class, $response); }
public function testRender() { $container = $this->getMock('Symfony\\Component\\DependencyInjection\\ContainerInterface'); $container->expects($this->once())->method('get')->will($this->returnValue($this->getMockBuilder('\\Twig_Environment')->disableOriginalConstructor()->getMock())); $renderer = new ContainerAwareHIncludeFragmentRenderer($container); $renderer->render('/', Request::create('/')); }
/** @test */ public function it_converts_exception_to_json() { $resolver = $this->getMock('Symfony\\Component\\HttpKernel\\Controller\\ControllerResolverInterface'); $resolver->expects($this->once())->method('getController')->will($this->returnValue(function () { throw new NotFoundHttpException(); })); $resolver->expects($this->once())->method('getArguments')->will($this->returnValue([])); $logger = $this->getMock('Psr\\Log\\LoggerInterface'); $logger->expects($this->once())->method('error'); $dispatcher = new EventDispatcher(); $httpKernel = new HttpKernel($dispatcher, $resolver); $kernel = new KernelForTest('test', true); $kernel->boot(); $kernel->getContainer()->set('http_kernel', $httpKernel); $dispatcher->addSubscriber(new RequestFormatNegotiationListener()); $dispatcher->addSubscriber(new RequestFormatValidationListener()); $dispatcher->addSubscriber(new ResponseConversionListener()); $dispatcher->addSubscriber(new ExceptionConversionListener($logger)); $request = Request::create('/exception', 'GET', [], [], [], ['HTTP_ACCEPT' => 'application/json']); $request->attributes->set('_format', 'json'); $response = $kernel->handle($request)->prepare($request); $this->assertSame(404, $response->getStatusCode()); $this->assertSame('application/vnd.error+json', $response->headers->get('Content-Type')); $this->assertJsonStringEqualsJsonString(json_encode(['message' => 'Not Found']), $response->getContent()); }
protected function setUp() { $this->request = Request::create(self::TEST_URL); $this->token = $this->getMock('Symfony\\Component\\Security\\Core\\Authentication\\Token\\TokenInterface'); $this->event = $this->getMockBuilder('Symfony\\Component\\Security\\Http\\Event\\InteractiveLoginEvent')->disableOriginalConstructor()->getMock(); $this->listener = new LoginListener(); }
/** * Save the image to the given outputFile * * @param $outputFile * @return string the URL to the saved image */ public function save($outputFile) { $glideApi = GlideApiFactory::create(); $outputImageData = $glideApi->run(Request::create(null, null, $this->modificationParameters), file_get_contents($this->getPathToImage())); file_put_contents($outputFile, $outputImageData); return $this->getURL(); }
public function testToString() { $app = $this->initApp(Request::create('/?some=thing')); list($manager, $expected, $parms) = $this->prepareEncodeHttpQuery(); $manager->initialize($app['request']); $this->assertEquals('?' . $expected, (string) $manager); }
/** * @expectedException \Dingo\OAuth2\Exception\ClientException */ public function testValidatingConfidentialClientFailsWhenUnableToGetIdAndSecret() { $grant = new GrantStub(); $request = Request::create('test', 'GET'); $grant->setRequest($request) and $grant->setStorage($storage = $this->getStorageMock()); $grant->execute(); }
public function testShouldDelegateGetArguments() { $req = Request::create('/'); $this->mockResolver->expects($this->once())->method('getArguments')->with($req)->will($this->returnValue(123)); $this->assertEquals(123, $this->resolver->getArguments($req, function () { })); }
public function testRemoveFolder() { $this->setRequest(Request::create('/async/removefolder', 'POST', ['namespace' => 'files', 'parent' => '', 'foldername' => '__phpunit_test_delete_me'])); $response = $this->controller()->removeFolder($this->getRequest()); $this->assertInstanceOf('\\Symfony\\Component\\HttpFoundation\\JsonResponse', $response); $this->assertEquals(200, $response->getStatusCode()); }
/** * @inheritdoc * @param array $values */ public function __construct(array $values = []) { $values['amazon_s3_client'] = $this->share(function (Application $app) { return S3Client::factory(array_merge($this->getCredentials(), ['version' => '2006-03-01', 'ssl.certificate_authority' => false])); }); $values['amazon_s3_credentials_cookie_name'] = 'credentials'; $values['controller.amazon_s3_client'] = $this->share(function (Application $app) { return new AmazonS3Controller($app['twig'], $app['amazon_s3_client']); }); $values['controller.authentication'] = $this->share(function (Application $app) { return new AuthenticationController($app['twig'], $app['amazon_s3_credentials_cookie_name']); }); parent::__construct($values); $this->register(new TwigServiceProvider(), ['twig.path' => __DIR__ . '/../views', 'twig.options' => ['cache' => is_writable(__DIR__ . '/..') ? __DIR__ . '/../cache/twig' : false]]); $this->register(new UrlGeneratorServiceProvider()); $this->register(new ServiceControllerServiceProvider()); $this->get('/login', 'controller.authentication:loginAction')->bind('login')->before(function (Request $request, Application $app) { $credentials = $this->getCredentials(); if (!empty($credentials)) { return new RedirectResponse($app['url_generator']->generate('list')); } }); $this->post('/login', 'controller.authentication:authenticateAction'); $this->post('/logout', 'controller.authentication:logoutAction')->bind('logout'); $this->get('/{bucket}', 'controller.amazon_s3_client:listAction')->value('bucket', null)->bind('list')->before(function (Request $request, Application $app) { $credentials = $this->getCredentials(); if (empty($credentials)) { return $app->handle(Request::create($app['url_generator']->generate('login')), HttpKernelInterface::SUB_REQUEST, false); } }); }
public function testGetCandidatesLimit() { $candidates = new Candidates(array(), 1); $request = Request::create('/my/path/is/deep.html'); $paths = $candidates->getCandidates($request); $this->assertEquals(array('/my/path/is/deep.html', '/my/path/is/deep'), $paths); }
/** * Tests form behaviour. */ public function testActionUrlBehavior() { // Create a new request which has a request uri with multiple leading // slashes and make it the master request. $request_stack = \Drupal::service('request_stack'); /** @var \Symfony\Component\HttpFoundation\RequestStack $original_request */ $original_request = $request_stack->pop(); // Just request some more so there is no request left. $request_stack->pop(); $request_stack->pop(); $request = Request::create($original_request->getSchemeAndHttpHost() . '//example.org'); $request_stack->push($request); $form = \Drupal::formBuilder()->getForm($this); $markup = \Drupal::service('renderer')->renderRoot($form); $this->setRawContent($markup); $elements = $this->xpath('//form/@action'); $action = (string) $elements[0]; $this->assertEqual($original_request->getSchemeAndHttpHost() . '//example.org', $action); // Create a new request which has a request uri with a single leading slash // and make it the master request. $request_stack = \Drupal::service('request_stack'); $original_request = $request_stack->pop(); $request = Request::create($original_request->getSchemeAndHttpHost() . '/example.org'); $request_stack->push($request); $form = \Drupal::formBuilder()->getForm($this); $markup = \Drupal::service('renderer')->renderRoot($form); $this->setRawContent($markup); $elements = $this->xpath('//form/@action'); $action = (string) $elements[0]; $this->assertEqual('/example.org', $action); }
public function dataForStart() { if (!class_exists('Symfony\\Component\\HttpFoundation\\Request')) { return array(array()); } return array(array(80, 443, Request::create('http://localhost/foo/bar?baz=bat'), 'https://localhost/foo/bar?baz=bat'), array(80, 443, Request::create('https://localhost/foo/bar?baz=bat'), 'http://localhost/foo/bar?baz=bat'), array(80, 123, Request::create('http://localhost/foo/bar?baz=bat'), 'https://localhost:123/foo/bar?baz=bat'), array(8080, 443, Request::create('https://localhost/foo/bar?baz=bat'), 'http://localhost:8080/foo/bar?baz=bat')); }
public function testGetSet() { $client = new RestClient(); $options = array('identifier' => 'my identifier'); $service = new Service(new EventDispatcher(), $client, $options); $this->assertEquals($client, $service->getClient()); $this->assertNull($service->getRequest()); $this->assertNull($service->getResponse()); $client = new RestClient(array('timeout' => 10)); $request = Request::create('/'); $response = new Response('a content'); $this->assertEquals($service, $service->setClient($client)); $this->assertEquals($service, $service->setRequest($request)); $this->assertEquals($service, $service->setResponse($response)); $this->assertEquals($client, $service->getClient()); $this->assertEquals($request, $service->getRequest()); $this->assertEquals($response, $service->getResponse()); // Test hashkey with/without cache enable $service->configure(array('identifier' => 'test cache', 'cache_ttl' => 10)); $this->assertNotNull($service->getHashKey()); $this->assertEquals(10, $service->getTtl()); $this->assertNull($service->getLogger()); $service->configure(array('logger' => new Logger('logger'), 'identifier' => 'test')); $this->assertNotNull($service->getLogger()); $this->assertTrue($service->hasOption('logger')); $this->assertFalse($service->hasOption('unknown')); $this->assertTrue($service->isAuthenticated()); $this->assertFalse($service->isLoaded()); }
/** * @dataProvider getFormat * @runInSeparateProcess */ public function testExecution($format) { $tmpDir = sys_get_temp_dir() . '/sf_hello'; $filesystem = new Filesystem(); $filesystem->remove($tmpDir); $filesystem->mkdirs($tmpDir); chdir($tmpDir); $tester = new CommandTester(new InitCommand()); $tester->execute(array('--name' => 'Hello' . $format, '--app-path' => 'hello' . $format, '--web-path' => 'web', '--src-path' => 'src', '--format' => $format)); // autoload $content = file_get_contents($file = $tmpDir . '/src/autoload.php'); $content = str_replace("__DIR__.'/vendor", "'" . __DIR__ . "/../../../../src/vendor", $content); file_put_contents($file, $content); // Kernel $class = 'Hello' . $format . 'Kernel'; $file = $tmpDir . '/hello' . $format . '/' . $class . '.php'; $this->assertTrue(file_exists($file)); $content = file_get_contents($file); $content = str_replace("__DIR__.'/../src/vendor/Symfony/src/Symfony/Bundle'", "'" . __DIR__ . "/../../../../src/vendor/Symfony/src/Symfony/Bundle'", $content); file_put_contents($file, $content); require_once $file; $kernel = new $class('dev', true); $response = $kernel->handle(Request::create('/')); $this->assertRegExp('/successfully/', $response->getContent()); $filesystem->remove($tmpDir); }
/** * Creates a Request. * * @param Request $request The current Request instance * @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo)) * * @return Request A Request instance */ public function createRequest(Request $request, $path) { if ($path && '/' !== $path[0] && 0 !== strpos($path, 'http')) { $path = $this->generateUrl($path, true); } return Request::create($path, 'get', array(), $request->cookies->all(), array(), $request->server->all()); }
/** * @param InputInterface $input * @param OutputInterface $output * * @return void */ public function execute(InputInterface $input, OutputInterface $output) { $kernel = $this->container->get('kernel'); $router = $this->container->get('router'); $route = $input->getOption('route'); $uri = $input->getOption('uri'); $uri = $route ? $router->generate($route) : $uri; $parameters = $input->getOption('parameters'); $parameters = json_decode($parameters, JSON_OBJECT_AS_ARRAY); $cookies = $input->getOption('cookies'); $cookies = json_decode($cookies, JSON_OBJECT_AS_ARRAY); $files = $input->getOption('files'); $files = json_decode($files, JSON_OBJECT_AS_ARRAY); $server = $input->getOption('server'); $server = json_decode($server, JSON_OBJECT_AS_ARRAY); $encoding = $input->getOption('encoding'); $content = $input->getOption('content'); $content = $this->decode($content, $encoding); $method = $input->getOption('method') ?: 'GET'; $method = ($method === 'GET' and $content) ? 'POST' : $method; $request = Request::create($uri, $method, $parameters, $cookies, $files, $server, $content); $response = $kernel->handle($request, Kernel::SUB_REQUEST); $result = $response->getContent(); if ($response->headers->get('Content-Type') === 'application/json') { $result = json_decode($result, JSON_OBJECT_AS_ARRAY); $result = json_encode($result, JSON_PRETTY_PRINT); } $output->writeln($result); return; }
private function buildSymfonyRequest(Request $request, Response $response) { $sfRequest = SymfonyRequest::create($request->getPath(), $request->getMethod()); $sfRequest->attributes->set('react.espresso.request', $request); $sfRequest->attributes->set('react.espresso.response', $response); return $sfRequest; }
public function testSetValidHeaders() { $request = Request::create('/'); $mode = new ApacheMode([['directory' => __DIR__]]); $mode->setHeaders($request); $this->assertArrayHasKey('x-sendfile-type', $request->headers->all()); }
public function testRegisterAndRender() { $app = new Application(); $app->register(new MonologExtension(), array('monolog.class_path' => __DIR__ . '/../../../../vendor/monolog/src')); $app['monolog.handler'] = $app->share(function () use($app) { return new TestHandler($app['monolog.level']); }); $app->get('/log', function () use($app) { $app['monolog']->addDebug('logging a message'); }); $app->get('/error', function () { throw new \RuntimeException('very bad error'); }); $app->error(function (\Exception $e) { return 'error handled'; }); $this->assertFalse($app['monolog.handler']->hasDebugRecords()); $this->assertFalse($app['monolog.handler']->hasErrorRecords()); $request = Request::create('/log'); $app->handle($request); $request = Request::create('/error'); $app->handle($request); $this->assertTrue($app['monolog.handler']->hasDebugRecords()); $this->assertTrue($app['monolog.handler']->hasErrorRecords()); }