setJson example


    public function __construct(mixed $data = null, int $status = 200, array $headers = [], bool $json = false)
    {
        parent::__construct('', $status$headers);

        if ($json && !\is_string($data) && !is_numeric($data) && !\is_callable([$data, '__toString'])) {
            throw new \TypeError(sprintf('"%s": If $json is set to true, argument $data must be a string or object implementing __toString(), "%s" given.', __METHOD__, get_debug_type($data)));
        }

        $data ??= new \ArrayObject();

        $json ? $this->setJson($data) : $this->setData($data);
    }

    /** * Factory method for chainability. * * Example: * * return JsonResponse::fromJsonString('{"key": "value"}') * ->setSharedMaxAge(300); * * @param string $data The JSON response string * @param int $status The response status code (200 "OK" by default) * @param array $headers An array of response headers */


    public function testSetJson()
    {
        $response = new JsonResponse('1', 200, [], true);
        $this->assertEquals('1', $response->getContent());

        $response = new JsonResponse('[1]', 200, [], true);
        $this->assertEquals('[1]', $response->getContent());

        $response = new JsonResponse(null, 200, []);
        $response->setJson('true');
        $this->assertEquals('true', $response->getContent());
    }

    public function testSetCallback()
    {
        $response = (new JsonResponse(['foo' => 'bar']))->setCallback('callback');

        $this->assertEquals('/**/callback({"foo":"bar"});', $response->getContent());
        $this->assertEquals('text/javascript', $response->headers->get('Content-Type'));
    }

    

    public function __construct(mixed $data = null, int $status = 200, array $headers = [], bool $json = false)
    {
        parent::__construct('', $status$headers);

        if ($json && !\is_string($data) && !is_numeric($data) && !\is_callable([$data, '__toString'])) {
            throw new \TypeError(sprintf('"%s": If $json is set to true, argument $data must be a string or object implementing __toString(), "%s" given.', __METHOD__, get_debug_type($data)));
        }

        $data ??= new \ArrayObject();

        $json ? $this->setJson($data) : $this->setData($data);
    }

    /** * Factory method for chainability. * * Example: * * return JsonResponse::fromJsonString('{"key": "value"}') * ->setSharedMaxAge(300); * * @param string $data The JSON response string * @param int $status The response status code (200 "OK" by default) * @param array $headers An array of response headers */
Home | Imprint | This part of the site doesn't use cookies.