/** * Invoke * * @return void */ public function __invoke(Request $request, Response $response, callable $next) { $config = $request->getRoute()->getMiddlewareConfig('validation'); $input = $request->getMethod() === 'GET' ? $request->getQueryParams() : $request->getParams(); try { $validator = $this->getValidator($config); $validator->assert($input); } catch (NestedValidationException $validation_exception) { $exception = new HttpMessagesException('Validation error.'); $exception->setErrors($validation_exception->getMessages()); $exception->setInput($input); throw $exception; } $response = $next($request, $response); return $response; }
/** * Get Serializer * * @param Request $request Request * * @return Serializer Serializer */ private function getSerializer(Request $request) { $serializers = \Craft\craft()->config->get('serializers', 'HttpMessagesFractalMiddleware'); $default_serializer = \Craft\craft()->config->get('defaultSerializer', 'HttpMessagesFractalMiddleware'); if (!isset($serializers[$default_serializer])) { $exception = new HttpMessagesException(); $exception->setMessage(sprintf('The default serializer `%s` does not exist.', $default_serializer)); throw $exception; } $serializer = $serializers[$default_serializer]; return new $serializer(); }
/** * Get Element Permissions * * @param string $element_type Element Type * * @return array Element Permissions */ public function getElementPermissions($element_type) { $element_permissions = $this->getElementTypeConfig($element_type, 'permissions'); if (!$element_permissions) { $element_permissions = $this->getElementPermissions('*'); } if (!$element_permissions) { $exception = new HttpMessagesException(); $exception->withStatus(415)->setMessage(sprintf('Permissions for the `%s` element type is not defined.', $element_type)); throw $exception; } return $element_permissions; }
/** * Get Action * * @param string $method Method * @param string $element_type Element Type * @param boolean $element_id Element Id * * @return string Action */ private function getAction($method, $element_type, $element_id = null) { if ($method === 'GET' && !$element_id) { return 'actionIndex'; } if ($method === 'GET' && $element_id) { return 'actionShow'; } if ($method === 'POST' && !$element_id) { return 'actionStore'; } if (in_array($method, ['PUT', 'PATCH']) && $element_id) { return 'actionUpdate'; } if ($method === 'DELETE' && $element_id) { return 'actionDelete'; } $exception = new HttpMessagesException(); $exception->setStatus(405)->setMessage(sprintf('`%s` method not allowed for resource `%s`.', $method, $element_type)); throw $exception; }