Failed Conditions
Push — master ( 3876bf...075658 )
by Florent
04:13
created

ClientRegistrationEndpoint::process()   A

Complexity

Conditions 3
Paths 10

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 22
rs 9.2
cc 3
eloc 16
nc 10
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\Component\Server\Endpoint\ClientRegistration;
15
16
use Assert\Assertion;
17
use Interop\Http\Factory\ResponseFactoryInterface;
18
use Interop\Http\ServerMiddleware\DelegateInterface;
19
use Interop\Http\ServerMiddleware\MiddlewareInterface;
20
use OAuth2Framework\Component\Server\Command\Client\CreateClientCommand;
21
use OAuth2Framework\Component\Server\DataTransporter;
22
use OAuth2Framework\Component\Server\Model\Client\Client;
23
use OAuth2Framework\Component\Server\Model\DataBag\DataBag;
24
use OAuth2Framework\Component\Server\Model\InitialAccessToken\InitialAccessToken;
25
use OAuth2Framework\Component\Server\Response\OAuth2Exception;
26
use OAuth2Framework\Component\Server\Response\OAuth2ResponseFactoryManager;
27
use Psr\Http\Message\ResponseInterface;
28
use Psr\Http\Message\ServerRequestInterface;
29
use SimpleBus\Message\Bus\MessageBus;
30
31
final class ClientRegistrationEndpoint implements MiddlewareInterface
32
{
33
    /**
34
     * @var MessageBus
35
     */
36
    private $messageBus;
37
38
    /**
39
     * @var ResponseFactoryInterface
40
     */
41
    private $responseFactory;
42
43
    /**
44
     * ClientRegistrationEndpoint constructor.
45
     *
46
     * @param ResponseFactoryInterface $responseFactory
47
     * @param MessageBus               $messageBus
48
     */
49
    public function __construct(ResponseFactoryInterface $responseFactory, MessageBus $messageBus)
50
    {
51
        $this->responseFactory = $responseFactory;
52
        $this->messageBus = $messageBus;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function process(ServerRequestInterface $request, DelegateInterface $delegate = null): ResponseInterface
59
    {
60
        $this->checkRequest($request);
61
        $data = new DataTransporter();
62
        $initialAccessToken = $request->getAttribute('initial_access_token');
63
64
        try {
65
            if (null !== $initialAccessToken) {
66
                Assertion::isInstanceOf($initialAccessToken, InitialAccessToken::class, 'Initial Access Token is missing or invalid.');
67
                $userAccountId = $initialAccessToken->getUserAccountId();
68
            } else {
69
                $userAccountId = null;
70
            }
71
            $commandParameters = DataBag::createFromArray(json_decode($request->getBody()->getContents(), true));
72
            $command = CreateClientCommand::create($userAccountId, $commandParameters, $data);
73
            $this->messageBus->handle($command);
74
        } catch (\InvalidArgumentException $e) {
75
            throw new OAuth2Exception(400, ['error' => OAuth2ResponseFactoryManager::ERROR_INVALID_REQUEST, 'error_description' => $e->getMessage()]);
76
        }
77
78
        return $this->createResponse($data->getData());
79
    }
80
81
    /**
82
     * @param ServerRequestInterface $request
83
     *
84
     * @throws OAuth2Exception
85
     */
86
    private function checkRequest(ServerRequestInterface $request)
87
    {
88
        if ('POST' !== $request->getMethod()) {
89
            throw new OAuth2Exception(
90
                405,
91
                [
92
                    'error' => OAuth2ResponseFactoryManager::ERROR_INVALID_REQUEST,
93
                    'error_description' => 'Unsupported method.',
94
                ]
95
            );
96
        }
97
    }
98
99
    /**
100
     * @param Client $client
101
     *
102
     * @return \Psr\Http\Message\ResponseInterface
103
     */
104
    private function createResponse(Client $client): ResponseInterface
105
    {
106
        $response = $this->responseFactory->createResponse(201);
107
        foreach (['Content-Type' => 'application/json', 'Cache-Control' => 'no-store', 'Pragma' => 'no-cache'] as $k => $v) {
108
            $response = $response->withHeader($k, $v);
109
        }
110
        $response->getBody()->write(json_encode($client->all()));
111
112
        return $response;
113
    }
114
}
115