PHP code example of mnavarrocarter / problem-details

1. Go to this page and download the library: Download mnavarrocarter/problem-details 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/ */

    

mnavarrocarter / problem-details example snippets




namespace App\Errors;

use MNC\ProblemDetails\ApiException;

class AuthenticationProblemException extends ApiException
{
    public function __construct(string $detail = '', array $extra = [], ?\Throwable $previous = null)
    {
        $type = 'errors/authentication';
        $title = 'Authentication Error';
        $statusCode = 401;
        parent::__construct($type, $title, $statusCode, $detail, $extra, $previous);
    }
}




namespace App\Errors;

use MNC\ProblemDetails\ApiException;

class AuthenticationProblemException extends ApiException
{
    public function __construct(string $detail = '', array $extra = [], ?\Throwable $previous = null)
    {
        $type = 'errors/authentication';
        $title = 'Authentication Error';
        $statusCode = 401;
        parent::__construct($type, $title, $statusCode, $detail, $extra, $previous);
    }
    
    public static function invalidCredentials(array $sentCredentials)
    {
        return new self(
            'Invalid credentials',
            $sentCredentials  
        );
    }
}




namespace App\Services;

use App\Error\AuthenticationProblemException;

class Authenticator extends ApiException
{
    public function authenticate(array $sentCredentials)
    {
        if ($this->areValidCredentials($sentCredentials)) {
            return $this->findUser($sentCredentials);
        }
        throw AuthenticationProblemException::invalidCredentials($sentCredentials);
    }
}





namespace App\Controller;

use MNC\ProblemDetails\ApiException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SomeController extends Controller
{
    public function someAction(Request $request)
    {
        try {
            $variable = $this->tryAction($request);
        } catch (ApiException $e) {
            return $this->json($e, $e->getStatusCode());
        }
        return $variable;
    }
}