<?php
namespace Fifa\ConnectId\Sdk\ExceptionHandler\Handler;
use Fifa\ConnectId\Sdk\Api\ApiException;
use Fifa\ConnectId\Sdk\Exception\UnauthorizedException;

/**
 * Class UnauthorizedRequestHandler
 * @package Fifa\ConnectId\Sdk\ExceptionHandler\Handler
 */
class UnauthorizedRequestHandler implements HandlerInterface
{
    /**
     * @var int
     */
    private $errorCode;

    /**
     * Constructor
     *
     * @param int $errorCode
     */
    public function __construct(int $errorCode = 401)
    {
        $this->errorCode = (int) $errorCode;
    }

    /**
     * String representation of the object
     */
    public function __toString()
    {
        return 'ErrorCode: ' . $this->errorCode;
    }

    /**
     * Method handles an UnauthorizedRequestException
     *
     * @param ApiException $e
     * @return UnauthorizedException|null
     */
    public function handle(ApiException $e): ?UnauthorizedException
    {
        if ($e->getCode() == $this->errorCode) {
            return new UnauthorizedException($e);
        }

        return null;
    }
}