public function testProcessPostRequestReturnsToken() { $request = new Request(); $request->setMethod('post'); $parameters = new ParameterDataContainer(); $parameters->setBodyParam('format', 'ZIP'); $event = new MvcEvent(); $event->setParam('ZFContentNegotiationParameterData', $parameters); $request->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $request->getHeaders()->addHeaderLine('Accept', 'application/json'); $this->controller->setRequest($request); $this->controller->setEvent($event); $cwd = getcwd(); chdir(__DIR__ . '/TestAsset'); $result = $this->controller->indexAction(); chdir($cwd); $this->assertInternalType('array', $result); $this->assertTrue(isset($result['token'])); $this->assertTrue(isset($result['format'])); $package = sys_get_temp_dir() . '/apigility_' . $result['token'] . '.' . $result['format']; $this->assertTrue(file_exists($package)); return $result; }
/** * Perform content negotiation * * For HTTP methods expecting body content, attempts to match the incoming * content-type against the list of allowed content types, and then performs * appropriate content deserialization. * * If an error occurs during deserialization, an ApiProblemResponse is * returned, indicating an issue with the submission. * * @param MvcEvent $e * @return null|ApiProblemResponse */ public function __invoke(MvcEvent $e) { $request = $e->getRequest(); if (!method_exists($request, 'getHeaders')) { // Not an HTTP request; nothing to do return; } $routeMatch = $e->getRouteMatch(); $parameterData = new ParameterDataContainer(); // route parameters: $routeParams = $routeMatch->getParams(); $parameterData->setRouteParams($routeParams); // query parameters: $parameterData->setQueryParams($request->getQuery()->toArray()); // body parameters: $bodyParams = array(); $contentType = $request->getHeader('Content-type'); switch ($request->getMethod()) { case $request::METHOD_POST: if ($contentType && $contentType->match('application/json')) { $bodyParams = $this->decodeJson($request->getContent()); break; } $bodyParams = $request->getPost()->toArray(); break; case $request::METHOD_PATCH: case $request::METHOD_PUT: case $request::METHOD_DELETE: $content = $request->getContent(); if ($contentType && $contentType->match('multipart/form-data')) { $parser = new MultipartContentParser($contentType, $request); $bodyParams = $parser->parse(); if ($request->getFiles()->count()) { $this->attachFileCleanupListener($e, $parser->getUploadTempDir()); } break; } if ($contentType && $contentType->match('application/json')) { $bodyParams = $this->decodeJson($content); break; } // Stolen from AbstractRestfulController parse_str($content, $bodyParams); if (!is_array($bodyParams) || 1 == count($bodyParams) && isset($bodyParams[0])) { $bodyParams = $content; } break; default: break; } if ($bodyParams instanceof ApiProblemResponse) { return $bodyParams; } $bodyParams = $bodyParams ?: array(); $parameterData->setBodyParams($bodyParams); $e->setParam('ZFContentNegotiationParameterData', $parameterData); }
public function testProcessPutRequest() { $currentDir = getcwd(); $tmpDir = sys_get_temp_dir() . "/" . uniqid(__NAMESPACE__ . '_'); mkdir($tmpDir); mkdir("{$tmpDir}/module/Foo", 0775, true); mkdir("{$tmpDir}/config"); file_put_contents("{$tmpDir}/config/application.config.php", '<' . '?php return array(\'modules\'=>array(\'Foo\'));'); file_put_contents("{$tmpDir}/module/Foo/Module.php", "<" . "?php\n\nnamespace Foo;\n\nclass Module\n{\n}"); chdir($tmpDir); require 'module/Foo/Module.php'; $moduleManager = $this->getMockBuilder('Zend\\ModuleManager\\ModuleManager')->disableOriginalConstructor()->getMock(); $moduleManager->expects($this->any())->method('getLoadedModules')->will($this->returnValue(['Foo' => new \Foo\Module()])); $moduleResource = new ModuleModel($moduleManager, [], []); $controller = new ModuleCreationController($moduleResource); $request = new Request(); $request->setMethod('put'); $request->getHeaders()->addHeaderLine('Accept', 'application/json'); $request->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $parameters = new ParameterDataContainer(); $parameters->setBodyParam('module', 'Foo'); $event = new MvcEvent(); $event->setParam('ZFContentNegotiationParameterData', $parameters); $plugins = new PluginManager(); $plugins->setInvokableClass('bodyParam', 'ZF\\ContentNegotiation\\ControllerPlugin\\BodyParam'); $controller->setRequest($request); $controller->setEvent($event); $controller->setPluginManager($plugins); $result = $controller->apiEnableAction(); $this->assertInstanceOf('ZF\\ContentNegotiation\\ViewModel', $result); $payload = $result->getVariable('payload'); $entity = method_exists($payload, 'getEntity') ? $payload->getEntity() : $payload->entity; $this->assertInstanceOf('ZF\\Hal\\Entity', $payload); $this->assertInstanceOf('ZF\\Apigility\\Admin\\Model\\ModuleEntity', $entity); $this->assertEquals('Foo', $entity->getName()); $this->removeDir($tmpDir); chdir($currentDir); }
public function testUpdateAuthenticationMapRequest() { $request = new Request(); $request->setMethod('put'); $request->getHeaders()->addHeaderLine('Accept', 'application/vnd.apigility.v2+json'); $request->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $request->getQuery()->set('version', 2); $this->controller->setRequest($request); $parameters = new ParameterDataContainer(); $parameters->setBodyParams(['authentication' => 'testoauth2mongo']); $this->event->setParam('ZFContentNegotiationParameterData', $parameters); $params = ['name' => 'Status']; $this->routeMatch = new RouteMatch($params); $this->routeMatch->setMatchedRouteName('zf-apigility/api/module/authentication'); $this->event->setRouteMatch($this->routeMatch); $result = $this->controller->mappingAction(); $this->assertInstanceOf('ZF\\ContentNegotiation\\ViewModel', $result); $this->assertEquals('testoauth2mongo', $result->getVariable('authentication')); }
public function testAddInputFilter() { $inputFilter = [['name' => 'bar', 'validators' => [['name' => 'NotEmpty', 'options' => ['type' => 127]], ['name' => 'Digits']]]]; $request = new Request(); $request->setMethod('put'); $request->setContent(json_encode($inputFilter)); $request->getHeaders()->addHeaderLine('Accept', 'application/json'); $request->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $module = 'InputFilter'; $controller = 'InputFilter\\V1\\Rest\\Foo\\Controller'; $params = ['name' => $module, 'controller_service_name' => $controller]; $routeMatch = new RouteMatch($params); $routeMatch->setMatchedRouteName('zf-apigility-admin/api/module/rest-service/rest_input_filter'); $event = new MvcEvent(); $event->setRouteMatch($routeMatch); $parameters = new ParameterDataContainer(); $parameters->setBodyParams($inputFilter); $event->setParam('ZFContentNegotiationParameterData', $parameters); $plugins = new PluginManager(); $plugins->setInvokableClass('bodyParams', 'ZF\\ContentNegotiation\\ControllerPlugin\\BodyParams'); $this->controller->setRequest($request); $this->controller->setEvent($event); $this->controller->setPluginManager($plugins); $result = $this->controller->indexAction(); $this->assertInstanceOf('ZF\\ContentNegotiation\\ViewModel', $result); $payload = $result->payload; $this->assertInstanceOf('ZF\\Hal\\Entity', $payload); $entity = $payload->entity; $this->assertInstanceOf('ZF\\Apigility\\Admin\\Model\\InputFilterEntity', $entity); $config = (include $this->basePath . '/module.config.php'); $validator = $config['zf-content-validation'][$controller]['input_filter']; $expected = $config['input_filter_specs'][$validator]; $expected['input_filter_name'] = $validator; $this->assertEquals($expected, $entity->getArrayCopy()); }
/** * @dataProvider validResourcePayloads */ public function testInjectsContentValidationInputFilterFromMvcEventIntoResourceEvent($method, $event, $id, $data, $returnValue) { $resourceEvent = null; $this->resource->getEventManager()->attach($event, function ($e) use($returnValue, &$resourceEvent) { $resourceEvent = $e; return $resource; }); $this->controller->setCollectionHttpMethods(array('GET', 'POST', 'PUT', 'PATCH', 'DELETE')); $this->controller->setEntityHttpMethods(array('GET', 'PUT', 'PATCH', 'DELETE')); $request = $this->controller->getRequest(); $request->setMethod($method); $this->event->setRequest($request); $container = new ParameterDataContainer(); $container->setBodyParams($data); $this->event->setParam('ZFContentNegotiationParameterData', $container); if ($id) { $this->event->getRouteMatch()->setParam('id', $id); } $inputFilter = new InputFilter(); $this->event->setParam('ZF\\ContentValidation\\InputFilter', $inputFilter); $result = $this->controller->onDispatch($this->event); $this->assertInstanceOf('ZF\\Rest\\ResourceEvent', $resourceEvent); $this->assertSame($inputFilter, $resourceEvent->getInputFilter()); }
/** * @group event */ public function testTriggeredEventBeforeValidateReturnsApiProblemResponseFromCallback() { $services = new ServiceManager(); $factory = new InputFilterFactory(); $services->setService('FooValidator', $factory->createInputFilter(array( 'foo' => array( 'name' => 'foo', 'validators' => array( array('name' => 'Digits'), ), ) ))); $listener = new ContentValidationListener(array( 'Foo' => array('input_filter' => 'FooValidator'), ), $services, array( 'Foo' => 'foo_id', )); $eventManager = new EventManager(); $listener->setEventManager($eventManager); $runner = $this; $hasRun = false; $eventManager->attach( ContentValidationListener::EVENT_BEFORE_VALIDATE, function (MvcEvent $e) use ($runner, &$hasRun) { $runner->assertInstanceOf( 'Zend\InputFilter\InputFilterInterface', $e->getParam('ZF\ContentValidation\InputFilter') ); $hasRun = true; return new ApiProblemResponse(new ApiProblem(422, 'Validation failed')); } ); $request = new HttpRequest(); $request->setMethod('PUT'); $matches = new RouteMatch(array('controller' => 'Foo')); $params = array_fill(0, 10, array( 'foo' => '123', )); $dataParams = new ParameterDataContainer(); $dataParams->setBodyParams($params); $event = new MvcEvent(); $event->setRequest($request); $event->setRouteMatch($matches); $event->setParam('ZFContentNegotiationParameterData', $dataParams); $response = $listener->onRoute($event); $this->assertTrue($hasRun); $this->assertInstanceOf('ZF\ApiProblem\ApiProblemResponse', $response); $this->assertEquals(422, $response->getApiProblem()->status); $this->assertEquals('Validation failed', $response->getApiProblem()->detail); }
/** * @group 20 */ public function testEmptyPostShouldReturnValidationError() { $services = new ServiceManager(); $factory = new InputFilterFactory(); $services->setService('FooValidator', $factory->createInputFilter(array('foo' => array('name' => 'foo', 'validators' => array(array('name' => 'Digits'))), 'bar' => array('name' => 'bar', 'validators' => array(array('name' => 'Regex', 'options' => array('pattern' => '/^[a-z]+/i'))))))); $listener = new ContentValidationListener(array('Foo' => array('input_filter' => 'FooValidator')), $services, array('Foo' => 'foo_id')); $request = new HttpRequest(); $request->setMethod('POST'); $matches = new RouteMatch(array('controller' => 'Foo')); $dataParams = new ParameterDataContainer(); $dataParams->setBodyParams(array()); $event = new MvcEvent(); $event->setRequest($request); $event->setRouteMatch($matches); $event->setParam('ZFContentNegotiationParameterData', $dataParams); $response = $listener->onRoute($event); $this->assertInstanceOf('ZF\\ApiProblem\\ApiProblemResponse', $response); $this->assertEquals(422, $response->getApiProblem()->status); }