Dingo\Api\Http\Response::morph PHP Method

morph() public method

Morph the API response to the appropriate format.
public morph ( string $format = 'json' ) : Response
$format string
return Response
    public function morph($format = 'json')
    {
        $this->content = $this->getOriginalContent();
        $this->fireMorphingEvent();
        if (isset(static::$transformer) && static::$transformer->transformableResponse($this->content)) {
            $this->content = static::$transformer->transform($this->content);
        }
        $formatter = static::getFormatter($format);
        $defaultContentType = $this->headers->get('Content-Type');
        $this->headers->set('Content-Type', $formatter->getContentType());
        $this->fireMorphedEvent();
        if ($this->content instanceof EloquentModel) {
            $this->content = $formatter->formatEloquentModel($this->content);
        } elseif ($this->content instanceof EloquentCollection) {
            $this->content = $formatter->formatEloquentCollection($this->content);
        } elseif (is_array($this->content) || $this->content instanceof ArrayObject || $this->content instanceof Arrayable) {
            $this->content = $formatter->formatArray($this->content);
        } else {
            $this->headers->set('Content-Type', $defaultContentType);
        }
        return $this;
    }

Usage Example

 public function testChangingResponseHeadersWithEvents()
 {
     $this->events->listen('Dingo\\Api\\Event\\ResponseIsMorphing', function ($event) {
         $event->response->headers->set('x-foo', 'bar');
     });
     Response::addFormatter('json', new Json());
     $response = new Response(['foo' => 'bar']);
     $this->assertEquals('bar', $response->morph('json')->headers->get('x-foo'));
     $this->events->forget('Dingo\\Api\\Event\\ResponseIsMorphing');
 }