PHP code example of tandrewcl / api-response-convert

1. Go to this page and download the library: Download tandrewcl/api-response-convert library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

tandrewcl / api-response-convert example snippets


...
use tandrewcl\ApiResponseConvertBundle\Converter\ResponseConverterInterface;
use tandrewcl\ApiResponseConvertBundle\Handler\ResponseHandler;
use tandrewcl\ApiResponseConvertBundle\Model\ConvertedResponseModel;
...

class FooConverter implements ResponseConverterInterface
{
    public static function getDefaultSupportedClassPriority(): int
    {
        return -245;
    }

    public function support(mixed $data): bool
    {
        return $data instanceof \Exception;
    }

    public static function getDefaultSupportedClassName(): string
    {
        return \Exception::class;
    }

    /**
     * @param \Exception $data
     */
    public function convert(mixed $data, ResponseHandler $responseHandler): ConvertedResponseModel
    {
        return new ConvertedResponseModel(
           message: $data->getMessage(), statusCode: Response::HTTP_INTERNAL_SERVER_ERROR
        );
    }
}

...
use tandrewcl\ApiResponseConvertBundle\Handler\ResponseHandler;
use Symfony\Component\HttpFoundation\JsonResponse;
...

class FooController
{
    public function __construct(
        private readonly ResponseHandler $responseHandler
    )
    {
    }

    public function indexAction(): JsonResponse
    {
        ...

        return $this->responseHandler->generateResponse($data);
    }