PHP code example of firehed / api

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

    

firehed / api example snippets




namespace MyApp\API\Endpoints\User;

use Firehed\API\Traits\EndpointTestCases;

/**
 * @covers MyApp\API\Endpoints\User\Create
 */
class CreateTest extends \PHPUnit\Framework\TestCase
{

    use EndpointTestCases;

    protected function getEndpoint()
    {
        return new Create();
    }
}


use Firehed\API;
use Psr\Log\LoggerInterface;
use Your\Application\Endpoints;

$container = new Pimple\Container();
// Endpoint config
$container[Endpoints\UserPost::class] = function ($c) {
    return new Endpoints\UserPost($c['some-dependency']);
};

// Other services
$container[API\Authentication\ProviderInterface::class] = function ($c) {
    // return your provider
};
$container[API\Authorization\ProviderInterface::class] = function ($c) {
    // return your provider
};
$container[LoggerInterface::class] = function ($c) {
    return new Monolog\Logger('your-application');
};

// ...
return new Pimple\Psr11\Container($container);


declare(strict_types=1);

namespace Your\Project;

use Firehed\API\Authentication\ProviderInterface as AuthnProvider;
use Firehed\API\Authorization\Exception as AuthException;
use Firehed\API\Authorization\ProviderInterface as AuthzProvider;
use Firehed\API\Authorization\Ok;
use Firehed\API\Container;
use Firehed\API\Interfaces\AuthenticatedEndpointInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;

// This elides a lot of details and error handling for simplicity
class AuthProvider implements AuthnProvider, AuthzProvider
{
    public function authenticate(ServerRequestInterface $request): ContainerInterface
    {
        list($_, $token) = explode(' ', $request->getHeaderLine('Authorization'), 2);
        // Find a user, app, etc. from the token string
        return new Container([
            App::class => $app,
            User::class => $user,
            // ...
            'oauth_scopes' => $scopes,
        ]);
    }

    public function authorize(AuthenticatedEndpointInterface $endpoint, ContainerInterface $container): Ok
    {
        $scopes = $container->get('oauth_scopes');
        if (!$endpoint instanceof YourInternalScopeInterface) {
            throw new \LogicException('Endpoint is invalid');
        }
        // This is a method in YourInternalScopeInterface
        $neededScopes = $endpoint->getRequiredScopes();
        foreach ($neededScopes as $scope) {
            if (!in_array($scope, $scopes)) {
                throw new AuthException(sprintf('Missing scope %s', $scope));
            }
        }
        return new Ok();
    }
}