Completed
Push — master ( 073016...e095ce )
by Derek Stephen
04:16
created

OfficialWebAppController::createStreamFromString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 7
ccs 0
cts 6
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller;
4
5
use App\Form\User\RegistrationForm;
6
use App\OAuth\SelfSignedProvider;
7
use Bone\Mvc\Controller;
8
use Bone\Mvc\Registry;
9
use Del\Icon;
10
use GuzzleHttp\Exception\ClientException;
11
use GuzzleHttp\Psr7\MultipartStream;
12
use Psr\Http\Message\RequestInterface;
13
use Zend\Diactoros\Response\JsonResponse;
14
use Zend\Diactoros\Response\RedirectResponse;
15
use Zend\Diactoros\Stream;
16
17
class OfficialWebAppController extends Controller
18
{
19
    /** @var SelfSignedProvider $oAuthClient */
20
    private $oAuthClient;
21
22
    /** @var string $host */
23
    private $host;
24
25
    /** @var string $locale */
26
    private $locale;
27
28
    /**
29
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
30
     */
31
    public function init()
32
    {
33
        $apiKeys = Registry::ahoy()->get('apiKeys');
34
        $options = $apiKeys['clientCredentials'];
35
36
        $this->host = $options['host'];
37
        $this->oAuthClient = new SelfSignedProvider($options);
38
        $this->locale = $this->getParam('locale', 'en_GB');
39
    }
40
41
    public function indexAction()
42
    {
43
44
    }
45
46
    public function thanksForRegisteringAction()
47
    {
48
49
    }
50
51
    /**
52
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
53
     */
54
    public function activateUserAccountAction()
55
    {
56
        $email = $this->getParam('email');
57
        $token = $this->getParam('token');
58
        $url = '/' . $this->locale.'/user/activate/' . $email . '/' . $token;
59
        $request = $this->getAuthenticatedRequest($url);
60
        try {
61
            $this->oAuthClient->getResponse($request);
62
            $this->view->activated = true;
63
            $this->view->message = [Icon::CHECK . ' Email successfully validated.', 'success'];
64
        } catch (ClientException $e) {
65
            $data = \json_decode($e->getResponse()->getBody()->getContents(), true);
66
            $this->view->message = [Icon::WARNING . '&nbsp;' . $data['error'], 'danger'];
67
            $this->view->activated = false;
68
        }
69
    }
70
71
    /**
72
     * @return RedirectResponse
73
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
74
     */
75
    public function registerAction()
76
    {
77
        $form = new RegistrationForm('register');
78
79
        if ($this->getRequest()->getMethod() == 'POST') {
80
81
            $formData = $this->getRequest()->getParsedBody();
82
            $form->populate($formData);
0 ignored issues
show
Bug introduced by
It seems like $formData can also be of type null and object; however, parameter $data of Del\Form\AbstractForm::populate() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

82
            $form->populate(/** @scrutinizer ignore-type */ $formData);
Loading history...
83
            $values = $form->getValues();
84
            $request = $this->getAuthenticatedRequest('/en_GB/user/register', 'POST');
85
            $request = $this->addMultipartFormData($request, [
86
                'email' => $values['email'],
87
                'password' => $values['password'],
88
                'confirm' => $values['confirm'],
89
            ]);
90
91
            try {
92
93
                $this->oAuthClient->getResponse($request);
94
                return new RedirectResponse('/website/thanks-for-registering');
95
96
            } catch (ClientException $e) {
97
98
                $data = \json_decode($e->getResponse()->getBody()->getContents(), true);
99
                $this->view->message = [Icon::WARNING . ' ' . $data['message'], 'danger'];
100
            }
101
        }
102
103
        $this->view->form = $form;
104
    }
105
106
    /**
107
     * Sample page using client_credentials grant to connect to the API
108
     *
109
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
110
     */
111
    public function clientCredentialsExampleAction()
112
    {
113
        $request = $this->getAuthenticatedRequest('/client');
114
        $response = $this->oAuthClient->getResponse($request);
115
116
        $data = \json_decode($response->getBody()->getContents());
117
        $response = new JsonResponse($data);
118
119
        return $response; // usually the data would be sent to a view for display, but that's outwith the scope
120
    }
121
122
123
    /**
124
     * @param $content
125
     * @return Stream
126
     */
127
    public function createStreamFromString($content)
128
    {
129
        $stream = new Stream('php://memory', 'wb+');
130
        $stream->write($content);
131
        $stream->rewind();
132
133
        return $stream;
134
    }
135
136
137
    /**
138
     * @param array $data
139
     * @return MultipartStream
140
     */
141
    public function createMultipartStream(array $data)
142
    {
143
        $elements = [];
144
        foreach ($data as $key => $val) {
145
            $elements[] = [
146
                'name' => $key,
147
                'contents' => $val,
148
            ];
149
        }
150
        $stream = new MultipartStream($elements);
151
152
        return $stream;
153
    }
154
155
    /**
156
     * @param $url
157
     * @param string $method
158
     * @return RequestInterface
159
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
160
     */
161
    public function getAuthenticatedRequest($url, $method = 'GET')
162
    {
163
        $token = $this->getAccessToken();
164
        $request = $this->oAuthClient->getAuthenticatedRequest($method, $this->host . $url, $token);
165
166
        return $request;
167
    }
168
169
    /**
170
     * @param RequestInterface $request
171
     * @param array $data
172
     * @return RequestInterface
173
     */
174
    public function addMultipartFormData(RequestInterface $request, array $data)
175
    {
176
        return $request->withBody($this->createMultipartStream($data));
177
    }
178
179
    /**
180
     * @return \League\OAuth2\Client\Token\AccessTokenInterface
181
     * @throws \League\OAuth2\Client\Provider\Exception\IdentityProviderException
182
     */
183
    private function getAccessToken()
184
    {
185
        return $this->oAuthClient->getAccessToken('client_credentials', ['scope' => ['admin']]);
186
    }
187
}
188