Skip to content
Snippets Groups Projects
ApiResponse.php 2.15 KiB
Newer Older
i.vasilenko@iq-adv.ru's avatar
i.vasilenko@iq-adv.ru committed
<?php

namespace App\Response;

use ReflectionClass;
use Symfony\Component\HttpFoundation\JsonResponse;

class ApiResponse extends JsonResponse
{
    private bool $status = true;

    private array $messages = [];

    private ?array $responseData = null;

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

    /**
     * Добавление ошибки
     *
     * @param string $message
     *
     * @return self
     */
    public function addError(string $message): self
    {
        $this->status = false;
        return $this->addMessage($message);
    }

    /**
     * Добавление ошибок
     *
     * @param array $errors
     *
     * @return $this
     */
    public function addErrors(array $errors): self
    {
        $this->status = false;
        foreach ($errors as $error) {
            $this->addError($error);
        }

        return $this;
    }

    /**
     * Добавление сообщения
     *
     * @param string $message
     *
     * @return self
     */
    public function addMessage(string $message): self
    {
        $this->messages[] = $message;
        return $this->setResult();
    }

    /**
     * Запись контента ответа
     *
     * @param array|null $responseData
     *
     * @return void
     */
    public function setResponseData(?array $responseData): void
    {
        $this->responseData = $responseData;

        $this->setResult();
    }

    /**
     * @return bool
     */
    public function isSuccess(): bool
    {
        return $this->status;
i.vasilenko@iq-adv.ru's avatar
i.vasilenko@iq-adv.ru committed
    }

    /**
     * Установка результата
     *
     * @return self
     */
    protected function setResult(): self
    {
        $result = [
            'status' => $this->status,
        ];

        if (!empty($this->responseData)) {
            $result['data'] = $this->responseData;
        }
        if (!isset($result['data'])) {
            $result['message'] = implode(', ', $this->messages);
        }

        return $this->setData($result);
    }
}