diff --git a/composer.json b/composer.json
index a42d398..efa19e3 100644
--- a/composer.json
+++ b/composer.json
@@ -1,20 +1,20 @@
{
- "name": "kodicms/laravel-api",
- "license": "GNU GENERAL PUBLIC LICENSE",
- "authors": [
- {
- "name": "Pavel Buchnev",
- "email": "butschster@gmail.com"
- }
- ],
- "require": {
- "php": ">=5.5.9",
- "laravel/framework": "5.1.*"
- },
- "autoload": {
- "psr-4": {
- "KodiCMS\\API\\" : "src/"
- }
- },
- "minimum-stability": "stable"
+ "name": "kodicms/laravel-api",
+ "license": "GNU GENERAL PUBLIC LICENSE",
+ "authors": [
+ {
+ "name": "Pavel Buchnev",
+ "email": "butschster@gmail.com"
+ }
+ ],
+ "require": {
+ "php": ">=5.5.9",
+ "laravel/framework": "5.1.*"
+ },
+ "autoload": {
+ "psr-4": {
+ "KodiCMS\\API\\": "src/"
+ }
+ },
+ "minimum-stability": "stable"
}
diff --git a/src/Exceptions/AuthenticateException.php b/src/Exceptions/AuthenticateException.php
index ae7c9d0..5f33902 100644
--- a/src/Exceptions/AuthenticateException.php
+++ b/src/Exceptions/AuthenticateException.php
@@ -7,8 +7,8 @@
class AuthenticateException extends Exception
{
- /**
- * @var int
- */
- protected $code = Response::ERROR_UNAUTHORIZED;
+ /**
+ * @var int
+ */
+ protected $code = Response::ERROR_UNAUTHORIZED;
}
\ No newline at end of file
diff --git a/src/Exceptions/Exception.php b/src/Exceptions/Exception.php
index 8294d42..b98e5e6 100644
--- a/src/Exceptions/Exception.php
+++ b/src/Exceptions/Exception.php
@@ -7,21 +7,21 @@
class Exception extends \RuntimeException
{
- /**
- * @var int
- */
- protected $code = Response::ERROR_UNKNOWN;
+ /**
+ * @var int
+ */
+ protected $code = Response::ERROR_UNKNOWN;
- /**
- * @return array
- */
- public function responseArray()
- {
- return [
- 'code' => $this->getCode(),
- 'type' => Response::TYPE_ERROR,
- 'message' => $this->getMessage(),
- ];
- }
+ /**
+ * @return array
+ */
+ public function responseArray()
+ {
+ return [
+ 'code' => $this->getCode(),
+ 'type' => Response::TYPE_ERROR,
+ 'message' => $this->getMessage(),
+ ];
+ }
}
\ No newline at end of file
diff --git a/src/Exceptions/MissingParameterException.php b/src/Exceptions/MissingParameterException.php
index 88ab4fe..01d2f68 100644
--- a/src/Exceptions/MissingParameterException.php
+++ b/src/Exceptions/MissingParameterException.php
@@ -7,44 +7,47 @@
class MissingParameterException extends Exception
{
- /**
- * @var string
- */
- protected $code = Response::ERROR_MISSING_PAPAM;
-
- /**
- * @var array
- */
- protected $rules = [ ];
-
-
- /**
- * @param Validator $validator
- */
- public function __construct(Validator $validator)
- {
- $this->rules = $validator->errors()->getMessages();
- $this->message = trans('api::core.messages.missing_params', [ 'field' => implode(', ', array_keys($validator->failed())) ]);
- }
-
-
- /**
- * @return array
- */
- public function getFailedRules()
- {
- return $this->rules;
- }
-
-
- /**
- * @return array
- */
- public function responseArray()
- {
- $data = parent::responseArray();
- $data['failed_rules'] = $this->getFailedRules();
-
- return $data;
- }
+
+ /**
+ * @var string
+ */
+ protected $code = Response::ERROR_MISSING_PAPAM;
+
+ /**
+ * @var array
+ */
+ protected $rules = [ ];
+
+
+ /**
+ * @param Validator $validator
+ */
+ public function __construct(Validator $validator)
+ {
+ $this->rules = $validator->errors()->getMessages();
+ $this->message = trans('api.messages.missing_params', [
+ 'field' => implode(', ', array_keys($validator->failed()))
+ ]);
+ }
+
+
+ /**
+ * @return array
+ */
+ public function getFailedRules()
+ {
+ return $this->rules;
+ }
+
+
+ /**
+ * @return array
+ */
+ public function responseArray()
+ {
+ $data = parent::responseArray();
+ $data['failed_rules'] = $this->getFailedRules();
+
+ return $data;
+ }
}
diff --git a/src/Exceptions/PermissionException.php b/src/Exceptions/PermissionException.php
index 9a08d31..b7cb39d 100644
--- a/src/Exceptions/PermissionException.php
+++ b/src/Exceptions/PermissionException.php
@@ -7,42 +7,42 @@
class PermissionException extends Exception
{
- /**
- * @var string
- */
- protected $permission = '';
-
-
- /**
- * @param null $permission
- * @param string $message
- */
- public function __construct($permission = null, $message = "")
- {
- $this->setPermission($permission);
- $this->message = empty( $message ) ? trans('api::core.messages.error_permissions') : $message;
- }
-
-
- /**
- * @param $permission
- */
- public function setPermission($permission)
- {
- $this->permission = $permission;
- }
-
-
- /**
- * @return array
- */
- public function responseArray()
- {
- return [
- 'code' => Response::ERROR_PERMISSIONS,
- 'type' => Response::TYPE_ERROR,
- 'permission' => $this->permission
- ];
- }
+ /**
+ * @var string
+ */
+ protected $permission = '';
+
+
+ /**
+ * @param null $permission
+ * @param string $message
+ */
+ public function __construct($permission = null, $message = "")
+ {
+ $this->setPermission($permission);
+ $this->message = empty( $message ) ? trans('api.messages.error_permissions') : $message;
+ }
+
+
+ /**
+ * @param $permission
+ */
+ public function setPermission($permission)
+ {
+ $this->permission = $permission;
+ }
+
+
+ /**
+ * @return array
+ */
+ public function responseArray()
+ {
+ return [
+ 'code' => Response::ERROR_PERMISSIONS,
+ 'type' => Response::TYPE_ERROR,
+ 'permission' => $this->permission
+ ];
+ }
}
diff --git a/src/Exceptions/ValidationException.php b/src/Exceptions/ValidationException.php
index e6b7f69..f9b6433 100644
--- a/src/Exceptions/ValidationException.php
+++ b/src/Exceptions/ValidationException.php
@@ -2,72 +2,72 @@
namespace KodiCMS\API\Exceptions;
-use Illuminate\Validation\Validator;
use KodiCMS\API\Http\Response;
+use Illuminate\Validation\Validator;
class ValidationException extends Exception
{
- /**
- * @var array
- */
- protected $messages = [ ];
-
- /**
- * @var array
- */
- protected $rules = [ ];
-
- /**
- * @var int
- */
- protected $code = Response::ERROR_VALIDATION;
-
-
- /**
- * @param Validator $object
- *
- * @return $this
- */
- public function setValidator(Validator $object)
- {
- $this->messages = $object->errors()->getMessages();
- $this->rules = $object->failed();
-
- return $this;
- }
-
-
- /**
- *
- * @return array
- */
- public function getFailedRules()
- {
- return $this->rules;
- }
-
-
- /**
- *
- * @return array
- */
- public function getErrorMessages()
- {
- return $this->messages;
- }
-
-
- /**
- * /**
- * @return array
- */
- public function responseArray()
- {
- $data = parent::responseArray();
- $data['failed_rules'] = $this->getFailedRules();
- $data['errors'] = $this->getErrorMessages();
-
- return $data;
- }
+ /**
+ * @var array
+ */
+ protected $messages = [ ];
+
+ /**
+ * @var array
+ */
+ protected $rules = [ ];
+
+ /**
+ * @var int
+ */
+ protected $code = Response::ERROR_VALIDATION;
+
+
+ /**
+ * @param Validator $object
+ *
+ * @return $this
+ */
+ public function setValidator(Validator $object)
+ {
+ $this->messages = $object->errors()->getMessages();
+ $this->rules = $object->failed();
+
+ return $this;
+ }
+
+
+ /**
+ *
+ * @return array
+ */
+ public function getFailedRules()
+ {
+ return $this->rules;
+ }
+
+
+ /**
+ *
+ * @return array
+ */
+ public function getErrorMessages()
+ {
+ return $this->messages;
+ }
+
+
+ /**
+ * /**
+ * @return array
+ */
+ public function responseArray()
+ {
+ $data = parent::responseArray();
+ $data['failed_rules'] = $this->getFailedRules();
+ $data['errors'] = $this->getErrorMessages();
+
+ return $data;
+ }
}
diff --git a/src/Http/Controllers/Controller.php b/src/Http/Controllers/Controller.php
index 004c695..4360d89 100644
--- a/src/Http/Controllers/Controller.php
+++ b/src/Http/Controllers/Controller.php
@@ -15,239 +15,255 @@
abstract class Controller extends BaseController
{
- /**
- * Массив возвращаемых значений, будет преобразован в формат JSON
- * @var array
- */
- public $responseArray = ['content' => null];
-
- /**
- * @var array
- */
- public $requiredFields = [];
-
- /**
- * Получение значения передаваемого параметра
- *
- * Если параметр указан как обязательный, то при его отсутсвии на запрос
- * вернется ошибка
- *
- * @param string $key Ключ
- * @param mixed $default Значение по умолчанию, если параметр отсутсвует
- * @param bool|string|array $isRequired Параметр обязателен для передачи
- * @return string
- * @throws MissingApiParameterException
- */
- public function getParameter($key, $default = null, $isRequired = false)
- {
- if (!empty($isRequired))
- {
- $this->validateParameters([$key => $isRequired]);
- }
-
- return array_get($this->request->all(), $key, $default);
- }
-
- /**
- * @param string $key
- * @param bool|string|array $rules
- * @return string
- * @throws MissingApiParameterException
- */
- public function getRequiredParameter($key, $rules = true)
- {
- return $this->getParameter($key, null, $rules);
- }
-
- /**
- * @param string $message
- */
- public function setMessage($message)
- {
- $this->responseArray['message'] = $message;
- }
-
- /**
- * @param array $errors
- */
- public function setErrors(array $errors)
- {
- $this->responseArray['errors'] = $errors;
- }
-
- /**
- * @param mixed $data
- */
- public function setContent($data)
- {
- if ($data instanceof View)
- {
- $data = $data->render();
- }
-
- $this->responseArray['content'] = $data;
- }
-
- /**
- * @param array $parameters
- * @return bool
- * @throws MissingApiParameterException
- */
- final public function validateParameters(array $parameters)
- {
- $parameters = array_map(function ($rules)
- {
- if (is_bool($rules) AND $rules === true)
- {
- return 'required';
- }
-
- return $rules;
-
- }, $parameters);
-
- $validator = Validator::make($this->request->all(), $parameters);
-
- if ($validator->fails())
- {
- throw new MissingParameterException($validator);
- }
-
- return true;
- }
-
- /**
- * Execute an action on the controller.
- *
- * @param string $method
- * @param array $parameters
- * @return array
- */
- public function callAction($method, $parameters)
- {
- $this->responseArray['type'] = Response::TYPE_CONTENT;
- $this->responseArray['method'] = $this->request->method();
- $this->responseArray['code'] = Response::NO_ERROR;
-
- if (isset($this->requiredFields[$method]) AND is_array($this->requiredFields[$method]))
- {
- $this->validateParameters($this->requiredFields[$method]);
- }
-
- $response = parent::callAction($method, $parameters);
-
- if ($response instanceof RedirectResponse)
- {
- $this->responseArray['type'] = Response::TYPE_REDIRECT;
- $this->responseArray['targetUrl'] = $response->getTargetUrl();
- $this->responseArray['code'] = $response->getStatusCode();
- }
- else if ($response instanceof View)
- {
- return new JsonResponse($response->render());
- }
- else if ($response instanceof JsonResponse)
- {
- return $response;
- }
-
- return (new Response(config('app.debug')))->createResponse($this->responseArray);
- }
-
- /**
- * @param string $command
- *
- * @return $this
- */
- public function addJavascriptCommand($command)
- {
- $this->responseArray['commands'][] = $command;
-
- return $this;
- }
-
- /**
- * Handle calls to missing methods on the controller.
- *
- * @param string $method
- * @param array $parameters
- * @return mixed
- *
- * @throws BadMethodCallException
- */
- public function __call($method, $parameters)
- {
- throw new BadMethodCallException("The requested API action [$method] does not exist.");
- }
-
- /***************************************
- * Magic methods
- ***************************************/
-
- /**
- * @param string $key
- * @param mixed $value
- */
- public function __set($key, $value)
- {
- $this->responseArray[$key] = $value;
- }
-
- /**
- * @param string $key
- * @return mixed
- */
- public function __get($key)
- {
- return $this->responseArray[$key];
- }
-
- /**
- * @param string $key
- * @return bool
- */
- public function __isset($key)
- {
- return isset($this->responseArray[$key]);
- }
-
- /**
- * @param string $key
- */
- public function __unset($key)
- {
- unset($this->responseArray[$key]);
- }
-
- /**
- * Throw the failed validation exception.
- *
- * @param \Illuminate\Http\Request $request
- * @param \Illuminate\Contracts\Validation\Validator $validator
- * @return void
- */
- protected function throwValidationException(Request $request, $validator)
- {
- $exception = new ValidationException();
- $exception->setValidator($validator);
-
- throw $exception;
- }
-
- /**
- * Create the response for when a request fails validation.
- *
- * @param \Illuminate\Http\Request $request
- * @param array $errors
- * @return \Illuminate\Http\Response
- */
- protected function buildFailedValidationResponse(Request $request, array $errors)
- {
- if ($request->ajax())
- {
- return (new Response(config('app.debug')))->createResponse($errors, 422);
- }
-
- return redirect()->to($this->getRedirectUrl())->withInput($request->input())->withErrors($errors, $this->errorBag());
- }
+
+ /**
+ * Массив возвращаемых значений, будет преобразован в формат JSON
+ * @var array
+ */
+ public $responseArray = [ 'content' => null ];
+
+ /**
+ * @var array
+ */
+ public $requiredFields = [ ];
+
+
+ /**
+ * Получение значения передаваемого параметра
+ *
+ * Если параметр указан как обязательный, то при его отсутсвии на запрос
+ * вернется ошибка
+ *
+ * @param string $key Ключ
+ * @param mixed $default Значение по умолчанию, если параметр отсутсвует
+ * @param bool|string|array $isRequired Параметр обязателен для передачи
+ *
+ * @return string
+ * @throws MissingApiParameterException
+ */
+ public function getParameter($key, $default = null, $isRequired = false)
+ {
+ if ( ! empty( $isRequired )) {
+ $this->validateParameters([ $key => $isRequired ]);
+ }
+
+ return array_get($this->request->all(), $key, $default);
+ }
+
+
+ /**
+ * @param string $key
+ * @param bool|string|array $rules
+ *
+ * @return string
+ * @throws MissingApiParameterException
+ */
+ public function getRequiredParameter($key, $rules = true)
+ {
+ return $this->getParameter($key, null, $rules);
+ }
+
+
+ /**
+ * @param string $message
+ */
+ public function setMessage($message)
+ {
+ $this->responseArray['message'] = $message;
+ }
+
+
+ /**
+ * @param array $errors
+ */
+ public function setErrors(array $errors)
+ {
+ $this->responseArray['errors'] = $errors;
+ }
+
+
+ /**
+ * @param mixed $data
+ */
+ public function setContent($data)
+ {
+ if ($data instanceof View) {
+ $data = $data->render();
+ }
+
+ $this->responseArray['content'] = $data;
+ }
+
+
+ /**
+ * @param array $parameters
+ *
+ * @return bool
+ * @throws MissingApiParameterException
+ */
+ final public function validateParameters(array $parameters)
+ {
+ $parameters = array_map(function ($rules) {
+ if (is_bool($rules) AND $rules === true) {
+ return 'required';
+ }
+
+ return $rules;
+
+ }, $parameters);
+
+ $validator = Validator::make($this->request->all(), $parameters);
+
+ if ($validator->fails()) {
+ throw new MissingParameterException($validator);
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Execute an action on the controller.
+ *
+ * @param string $method
+ * @param array $parameters
+ *
+ * @return array
+ */
+ public function callAction($method, $parameters)
+ {
+ $this->responseArray['type'] = Response::TYPE_CONTENT;
+ $this->responseArray['method'] = $this->request->method();
+ $this->responseArray['code'] = Response::NO_ERROR;
+
+ if (isset( $this->requiredFields[$method] ) AND is_array($this->requiredFields[$method])) {
+ $this->validateParameters($this->requiredFields[$method]);
+ }
+
+ $response = parent::callAction($method, $parameters);
+
+ if ($response instanceof RedirectResponse) {
+ $this->responseArray['type'] = Response::TYPE_REDIRECT;
+ $this->responseArray['targetUrl'] = $response->getTargetUrl();
+ $this->responseArray['code'] = $response->getStatusCode();
+ } else {
+ if ($response instanceof View) {
+ return new JsonResponse($response->render());
+ } else {
+ if ($response instanceof JsonResponse) {
+ return $response;
+ }
+ }
+ }
+
+ return (new Response(config('app.debug')))->createResponse($this->responseArray);
+ }
+
+
+ /**
+ * @param string $command
+ *
+ * @return $this
+ */
+ public function addJavascriptCommand($command)
+ {
+ $this->responseArray['commands'][] = $command;
+
+ return $this;
+ }
+
+
+ /**
+ * Handle calls to missing methods on the controller.
+ *
+ * @param string $method
+ * @param array $parameters
+ *
+ * @return mixed
+ *
+ * @throws BadMethodCallException
+ */
+ public function __call($method, $parameters)
+ {
+ throw new BadMethodCallException("The requested API action [$method] does not exist.");
+ }
+
+ /***************************************
+ * Magic methods
+ ***************************************/
+
+ /**
+ * @param string $key
+ * @param mixed $value
+ */
+ public function __set($key, $value)
+ {
+ $this->responseArray[$key] = $value;
+ }
+
+
+ /**
+ * @param string $key
+ *
+ * @return mixed
+ */
+ public function __get($key)
+ {
+ return $this->responseArray[$key];
+ }
+
+
+ /**
+ * @param string $key
+ *
+ * @return bool
+ */
+ public function __isset($key)
+ {
+ return isset( $this->responseArray[$key] );
+ }
+
+
+ /**
+ * @param string $key
+ */
+ public function __unset($key)
+ {
+ unset( $this->responseArray[$key] );
+ }
+
+
+ /**
+ * Throw the failed validation exception.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @param \Illuminate\Contracts\Validation\Validator $validator
+ *
+ * @return void
+ */
+ protected function throwValidationException(Request $request, $validator)
+ {
+ $exception = new ValidationException();
+ $exception->setValidator($validator);
+
+ throw $exception;
+ }
+
+
+ /**
+ * Create the response for when a request fails validation.
+ *
+ * @param \Illuminate\Http\Request $request
+ * @param array $errors
+ *
+ * @return \Illuminate\Http\Response
+ */
+ protected function buildFailedValidationResponse(Request $request, array $errors)
+ {
+ if ($request->ajax()) {
+ return (new Response(config('app.debug')))->createResponse($errors, 422);
+ }
+
+ return redirect()->to($this->getRedirectUrl())->withInput($request->input())->withErrors($errors, $this->errorBag());
+ }
}
diff --git a/src/Http/Response.php b/src/Http/Response.php
index b13ee77..7664b73 100644
--- a/src/Http/Response.php
+++ b/src/Http/Response.php
@@ -11,146 +11,152 @@
class Response
{
- const NO_ERROR = 200;
- const ERROR_MISSING_PAPAM = 110;
- const ERROR_VALIDATION = 120;
- const ERROR_UNKNOWN = 130;
- const ERROR_TOKEN = 140;
- const ERROR_MISSING_ASSIGMENT = 150;
- const ERROR_PERMISSIONS = 220;
- const ERROR_UNAUTHORIZED = 403;
- const ERROR_PAGE_NOT_FOUND = 404;
-
- const TYPE_ERROR = 'error';
- const TYPE_CONTENT = 'content';
- const TYPE_REDIRECT = 'redirect';
-
- private $debug;
-
- /**
- * @param bool $debug
- */
- public function __construct($debug = true)
- {
- $this->debug = $debug;
- }
-
- /**
- * Creates the error Response associated with the given Exception.
- *
- * @param \Exception $exception
- * @return Response A Response instance
- */
- public function createExceptionResponse(\Exception $exception)
- {
- $responseData = [
- 'code' => $exception->getCode(),
- 'type' => static::TYPE_ERROR,
- 'message' => $exception->getMessage()
- ];
-
- if ($exception instanceof Exception or method_exists($exception, 'responseArray'))
- {
- $responseData = array_merge($responseData, $exception->responseArray());
- }
- else if ($exception instanceof ModelNotFoundException)
- {
- $responseData['code'] = static::ERROR_PAGE_NOT_FOUND;
- }
- else if ($exception instanceof MassAssignmentException)
- {
- $responseData['code'] = static::ERROR_MISSING_ASSIGMENT;
- $responseData['field'] = $exception->getMessage();
- }
-
- if ($this->debug)
- {
- $responseData['file'] = $exception->getFile();
- $responseData['line'] = $exception->getLine();
- }
-
- return $this->createResponse($responseData, 500);
- }
-
- /**
- * @param array $responseData
- * @param integer $code
- * @return Response
- */
- public function createResponse(array $responseData, $code = 200)
- {
- $responseType = Request::route()->parameter('type', '.json');
-
- switch($responseType)
- {
- case '.yaml':
- return $this->yamlResponse($responseData, $code);
- case '.xml':
- return $this->xmlResponse($responseData, $code);
- default:
- return $this->jsonResponse($responseData, $code);
- }
- }
-
- /**
- * @param array $data
- * @param integer $code
- * @return Response
- */
- protected function yamlResponse($data, $code)
- {
- $yaml = Yaml::dump($data);
- return new \Illuminate\Http\Response($yaml, $code, [
- 'Content-Type' => 'text/x-yaml'
- ]);
- }
-
- /**
- * @param array $data
- * @param integer $code
- * @return Response
- */
- protected function xmlResponse($data, $code)
- {
- $xml = new \SimpleXMLElement('');
-
- $this->arrayToXml($data, $xml);
-
- return new \Illuminate\Http\Response((string) $xml->asXML(), $code, [
- 'Content-Type' => 'application/xml'
- ]);
- }
-
- protected function arrayToXml($data, &$xml)
- {
- foreach ($data as $key => $value)
- {
- if (is_numeric($key))
- {
- $key = "item_{$key}";
- }
-
- if (is_array($value))
- {
- $subNode = $xml->addChild($key);
- $this->arrayToXml($value, $subNode);
- }
- else
- {
- $xml->addChild($key, htmlspecialchars($value));
- }
- }
- }
-
- /**
- * @param array $data
- * @param integer $code
- * @return JsonResponse
- */
- protected function jsonResponse($data, $code)
- {
- return new JsonResponse($data, $code, [
- 'Content-Type' => 'application/json'
- ]);
- }
+
+ const NO_ERROR = 200;
+ const ERROR_MISSING_PAPAM = 110;
+ const ERROR_VALIDATION = 120;
+ const ERROR_UNKNOWN = 130;
+ const ERROR_TOKEN = 140;
+ const ERROR_MISSING_ASSIGMENT = 150;
+ const ERROR_PERMISSIONS = 220;
+ const ERROR_UNAUTHORIZED = 403;
+ const ERROR_PAGE_NOT_FOUND = 404;
+
+ const TYPE_ERROR = 'error';
+ const TYPE_CONTENT = 'content';
+ const TYPE_REDIRECT = 'redirect';
+
+ private $debug;
+
+
+ /**
+ * @param bool $debug
+ */
+ public function __construct($debug = true)
+ {
+ $this->debug = $debug;
+ }
+
+
+ /**
+ * Creates the error Response associated with the given Exception.
+ *
+ * @param \Exception $exception
+ *
+ * @return Response A Response instance
+ */
+ public function createExceptionResponse(\Exception $exception)
+ {
+ $responseData = [
+ 'code' => $exception->getCode(),
+ 'type' => static::TYPE_ERROR,
+ 'message' => $exception->getMessage()
+ ];
+
+ if ($exception instanceof Exception or method_exists($exception, 'responseArray')) {
+ $responseData = array_merge($responseData, $exception->responseArray());
+ } else {
+ if ($exception instanceof ModelNotFoundException) {
+ $responseData['code'] = static::ERROR_PAGE_NOT_FOUND;
+ } else {
+ if ($exception instanceof MassAssignmentException) {
+ $responseData['code'] = static::ERROR_MISSING_ASSIGMENT;
+ $responseData['field'] = $exception->getMessage();
+ }
+ }
+ }
+
+ if ($this->debug) {
+ $responseData['file'] = $exception->getFile();
+ $responseData['line'] = $exception->getLine();
+ }
+
+ return $this->createResponse($responseData, 500);
+ }
+
+
+ /**
+ * @param array $responseData
+ * @param integer $code
+ *
+ * @return Response
+ */
+ public function createResponse(array $responseData, $code = 200)
+ {
+ $responseType = Request::route()->parameter('type', '.json');
+
+ switch ($responseType) {
+ case '.yaml':
+ return $this->yamlResponse($responseData, $code);
+ case '.xml':
+ return $this->xmlResponse($responseData, $code);
+ default:
+ return $this->jsonResponse($responseData, $code);
+ }
+ }
+
+
+ /**
+ * @param array $data
+ * @param integer $code
+ *
+ * @return Response
+ */
+ protected function yamlResponse($data, $code)
+ {
+ $yaml = Yaml::dump($data);
+
+ return new \Illuminate\Http\Response($yaml, $code, [
+ 'Content-Type' => 'text/x-yaml'
+ ]);
+ }
+
+
+ /**
+ * @param array $data
+ * @param integer $code
+ *
+ * @return Response
+ */
+ protected function xmlResponse($data, $code)
+ {
+ $xml = new \SimpleXMLElement('');
+
+ $this->arrayToXml($data, $xml);
+
+ return new \Illuminate\Http\Response((string) $xml->asXML(), $code, [
+ 'Content-Type' => 'application/xml'
+ ]);
+ }
+
+
+ protected function arrayToXml($data, &$xml)
+ {
+ foreach ($data as $key => $value) {
+ if (is_numeric($key)) {
+ $key = "item_{$key}";
+ }
+
+ if (is_array($value)) {
+ $subNode = $xml->addChild($key);
+ $this->arrayToXml($value, $subNode);
+ } else {
+ $xml->addChild($key, htmlspecialchars($value));
+ }
+ }
+ }
+
+
+ /**
+ * @param array $data
+ * @param integer $code
+ *
+ * @return JsonResponse
+ */
+ protected function jsonResponse($data, $code)
+ {
+ return new JsonResponse($data, $code, [
+ 'Content-Type' => 'application/json'
+ ]);
+ }
}
diff --git a/src/Http/RouteAPI.php b/src/Http/RouteAPI.php
index 74e357b..0d41efd 100644
--- a/src/Http/RouteAPI.php
+++ b/src/Http/RouteAPI.php
@@ -8,140 +8,140 @@
class RouteAPI
{
- /**
- * Register a new GET route with the router.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function get($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return $this->addResponseType(Route::get($uri, $action));
- }
-
-
- /**
- * Register a new POST route with the router.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function post($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return $this->addResponseType(Route::post($uri, $action));
- }
-
-
- /**
- * Register a new PUT route with the router.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function put($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return $this->addResponseType(Route::put($uri, $action));
- }
-
-
- /**
- * Register a new PATCH route with the router.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function patch($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return $this->addResponseType(Route::patch($uri, $action));
- }
-
-
- /**
- * Register a new DELETE route with the router.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function delete($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return $this->addResponseType(Route::delete($uri, $action));
- }
-
-
- /**
- * Register a new OPTIONS route with the router.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function options($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return $this->addResponseType(Route::options($uri, $action));
- }
-
-
- /**
- * Register a new route responding to all verbs.
- *
- * @param string $uri
- * @param \Closure|array|string $action
- *
- * @return \Illuminate\Routing\Route
- */
- public function any($uri, $action)
- {
- $uri = $this->buildUri($uri);
-
- return Route::any($uri, $action);
- }
-
-
- /**
- * @param Router $route
- *
- * @return $this
- */
- protected function addResponseType(Router $route)
- {
- return $route->where('type', '\.[a-z]+');
- }
-
-
- /**
- * @param string $uri
- *
- * @return string
- */
- protected function buildUri($uri)
- {
- if (strpos($uri, 'api.') === false) {
- $uri = 'api.' . $uri;
- }
-
- return $uri . '{type?}';
- }
+ /**
+ * Register a new GET route with the router.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function get($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return $this->addResponseType(Route::get($uri, $action));
+ }
+
+
+ /**
+ * Register a new POST route with the router.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function post($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return $this->addResponseType(Route::post($uri, $action));
+ }
+
+
+ /**
+ * Register a new PUT route with the router.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function put($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return $this->addResponseType(Route::put($uri, $action));
+ }
+
+
+ /**
+ * Register a new PATCH route with the router.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function patch($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return $this->addResponseType(Route::patch($uri, $action));
+ }
+
+
+ /**
+ * Register a new DELETE route with the router.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function delete($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return $this->addResponseType(Route::delete($uri, $action));
+ }
+
+
+ /**
+ * Register a new OPTIONS route with the router.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function options($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return $this->addResponseType(Route::options($uri, $action));
+ }
+
+
+ /**
+ * Register a new route responding to all verbs.
+ *
+ * @param string $uri
+ * @param \Closure|array|string $action
+ *
+ * @return \Illuminate\Routing\Route
+ */
+ public function any($uri, $action)
+ {
+ $uri = $this->buildUri($uri);
+
+ return Route::any($uri, $action);
+ }
+
+
+ /**
+ * @param Router $route
+ *
+ * @return $this
+ */
+ protected function addResponseType(Router $route)
+ {
+ return $route->where('type', '\.[a-z]+');
+ }
+
+
+ /**
+ * @param string $uri
+ *
+ * @return string
+ */
+ protected function buildUri($uri)
+ {
+ if (strpos($uri, 'api.') === false) {
+ $uri = 'api.' . $uri;
+ }
+
+ return $uri . '{type?}';
+ }
}
diff --git a/src/RouteApiFacade.php b/src/RouteApiFacade.php
index e385a67..a164563 100644
--- a/src/RouteApiFacade.php
+++ b/src/RouteApiFacade.php
@@ -5,15 +5,16 @@
use KodiCMS\API\Http\RouteAPI;
use Illuminate\Support\Facades\Facade;
-class RouteApiFacade extends Facade {
+class RouteApiFacade extends Facade
+{
- /**
- * Get the registered name of the component.
- *
- * @return string
- */
- protected static function getFacadeAccessor()
- {
- return RouteAPI::class;
- }
+ /**
+ * Get the registered name of the component.
+ *
+ * @return string
+ */
+ protected static function getFacadeAccessor()
+ {
+ return RouteAPI::class;
+ }
}
\ No newline at end of file