Created
April 21, 2015 10:06
-
-
Save weaverryan/1a0ffef7729b4f935583 to your computer and use it in GitHub Desktop.
ApiProblem wrapper class example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace AppBundle\Api; | |
| use Symfony\Component\HttpFoundation\Response; | |
| /** | |
| * A wrapper for holding data to be used for a application/problem+json response | |
| */ | |
| class ApiProblem | |
| { | |
| const TYPE_VALIDATION_ERROR = 'validation_error'; | |
| const TYPE_INVALID_REQUEST_BODY_FORMAT = 'invalid_body_format'; | |
| private static $titles = array( | |
| self::TYPE_VALIDATION_ERROR => 'There was a validation error', | |
| self::TYPE_INVALID_REQUEST_BODY_FORMAT => 'Invalid JSON format sent', | |
| ); | |
| private $statusCode; | |
| private $type; | |
| private $title; | |
| private $extraData = array(); | |
| public function __construct($statusCode, $type = null) | |
| { | |
| $this->statusCode = $statusCode; | |
| $this->type = $type; | |
| if ($type === null) { | |
| // no type? The default is about:blank and the title should | |
| // be the standard status code message | |
| $this->type = 'about:blank'; | |
| $this->title = isset(Response::$statusTexts[$statusCode]) | |
| ? Response::$statusTexts[$statusCode] | |
| : 'Unknown status code :('; | |
| } else { | |
| if (!isset(self::$titles[$type])) { | |
| throw new \InvalidArgumentException('No title for type '.$type); | |
| } | |
| $this->title = self::$titles[$type]; | |
| } | |
| } | |
| public function toArray() | |
| { | |
| return array_merge( | |
| $this->extraData, | |
| array( | |
| 'status' => $this->statusCode, | |
| 'type' => $this->type, | |
| 'title' => $this->title, | |
| ) | |
| ); | |
| } | |
| public function set($name, $value) | |
| { | |
| $this->extraData[$name] = $value; | |
| } | |
| public function getStatusCode() | |
| { | |
| return $this->statusCode; | |
| } | |
| public function getTitle() | |
| { | |
| return $this->title; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment