IlluminateTranslationPlugin::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 4
c 1
b 0
f 1
nc 1
nop 3
dl 0
loc 6
rs 10
1
<?php
2
3
namespace W2w\Laravel\Apie\Plugins\IlluminateTranslation;
4
5
use erasys\OpenApi\Spec\v3\Document;
6
use erasys\OpenApi\Spec\v3\Operation;
7
use erasys\OpenApi\Spec\v3\Parameter;
8
use Illuminate\Contracts\Translation\Translator;
9
use Illuminate\Foundation\Application;
10
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
11
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
12
use W2w\Laravel\Apie\Plugins\IlluminateTranslation\Normalizers\LocationableExceptionNormalizer;
13
use W2w\Laravel\Apie\Plugins\IlluminateTranslation\Normalizers\ValidationExceptionNormalizer;
14
use W2w\Laravel\Apie\Plugins\IlluminateTranslation\SubActions\TransChoiceSubAction;
15
use W2w\Laravel\Apie\Plugins\IlluminateTranslation\ValueObjects\Locale;
16
use W2w\Lib\Apie\Events\DecodeEvent;
17
use W2w\Lib\Apie\Events\DeleteResourceEvent;
18
use W2w\Lib\Apie\Events\ModifySingleResourceEvent;
19
use W2w\Lib\Apie\Events\NormalizeEvent;
20
use W2w\Lib\Apie\Events\ResponseEvent;
21
use W2w\Lib\Apie\Events\RetrievePaginatedResourcesEvent;
22
use W2w\Lib\Apie\Events\RetrieveSingleResourceEvent;
23
use W2w\Lib\Apie\Events\StoreExistingResourceEvent;
24
use W2w\Lib\Apie\Events\StoreNewResourceEvent;
25
use W2w\Lib\Apie\PluginInterfaces\ApieAwareInterface;
26
use W2w\Lib\Apie\PluginInterfaces\ApieAwareTrait;
27
use W2w\Lib\Apie\PluginInterfaces\NormalizerProviderInterface;
28
use W2w\Lib\Apie\PluginInterfaces\OpenApiEventProviderInterface;
29
use W2w\Lib\Apie\PluginInterfaces\ResourceLifeCycleInterface;
30
use W2w\Lib\Apie\PluginInterfaces\SubActionsProviderInterface;
31
use W2w\Lib\Apie\Plugins\Core\Normalizers\ExceptionNormalizer;
32
33
class IlluminateTranslationPlugin implements ApieAwareInterface, OpenApiEventProviderInterface, ResourceLifeCycleInterface, SubActionsProviderInterface, NormalizerProviderInterface
34
{
35
    use ApieAwareTrait;
36
37
    /**
38
     * @var array
39
     */
40
    private $locales;
41
42
    /**
43
     * @var Translator
44
     */
45
    private $translator;
46
47
    /**
48
     * @var Application
49
     */
50
    private $application;
51
52
    /**
53
     * @param string[] $locales
54
     * @param Translator $translator
55
     */
56
    public function __construct(array $locales, Translator $translator, Application $application)
57
    {
58
        $this->locales = $locales;
59
        $this->translator = $translator;
60
        $this->application = $application;
61
        Locale::$locales = $this->locales;
62
    }
63
64
    public function onOpenApiDocGenerated(Document $document): Document
65
    {
66
        foreach ($document->paths as $path) {
67
            $this->patchOperation($path->get);
68
            $this->patchOperation($path->put);
69
            $this->patchOperation($path->post);
70
            $this->patchOperation($path->patch);
71
            $this->patchOperation($path->delete);
72
            $this->patchOperation($path->options);
73
            $this->patchOperation($path->head);
74
            $this->patchOperation($path->trace);
75
        }
76
        return $document;
77
    }
78
79
    private function patchOperation(?Operation $operation)
80
    {
81
        if ($operation === null) {
82
            return;
83
        }
84
        if (null === $operation->parameters) {
85
            $operation->parameters = [];
86
        }
87
        Locale::$locales = $this->locales;
88
        $operation->parameters[] = new Parameter(
89
            'Accept-Language',
90
            Parameter::IN_HEADER,
91
            'language',
92
            [
93
                'schema' => Locale::toSchema(),
94
            ]
95
        );
96
    }
97
98
    public function onPreDeleteResource(DeleteResourceEvent $event)
99
    {
100
    }
101
102
    public function onPostDeleteResource(DeleteResourceEvent $event)
103
    {
104
    }
105
106
    public function onPreRetrieveResource(RetrieveSingleResourceEvent $event)
107
    {
108
    }
109
110
    public function onPostRetrieveResource(RetrieveSingleResourceEvent $event)
111
    {
112
    }
113
114
    public function onPreRetrieveAllResources(RetrievePaginatedResourcesEvent $event)
115
    {
116
    }
117
118
    public function onPostRetrieveAllResources(RetrievePaginatedResourcesEvent $event)
119
    {
120
    }
121
122
    public function onPrePersistExistingResource(StoreExistingResourceEvent $event)
123
    {
124
    }
125
126
    public function onPostPersistExistingResource(StoreExistingResourceEvent $event)
127
    {
128
    }
129
130
    public function onPreDecodeRequestBody(DecodeEvent $event)
131
    {
132
    }
133
134
    public function onPostDecodeRequestBody(DecodeEvent $event)
135
    {
136
    }
137
138
    public function onPreModifyResource(ModifySingleResourceEvent $event)
139
    {
140
    }
141
142
    public function onPostModifyResource(ModifySingleResourceEvent $event)
143
    {
144
    }
145
146
    public function onPreCreateResource(StoreNewResourceEvent $event)
147
    {
148
    }
149
150
    public function onPostCreateResource(StoreNewResourceEvent $event)
151
    {
152
    }
153
154
    public function onPrePersistNewResource(StoreExistingResourceEvent $event)
155
    {
156
    }
157
158
    public function onPostPersistNewResource(StoreExistingResourceEvent $event)
159
    {
160
    }
161
162
    public function onPreCreateResponse(ResponseEvent $event)
163
    {
164
    }
165
166
    public function onPostCreateResponse(ResponseEvent $event)
167
    {
168
        $response = $event->getResponse();
169
        $locale = $this->application->getLocale();
170
        if ($locale && !$response->hasHeader('Content-Language')) {
171
            $event->setResponse(
172
                $response
0 ignored issues
show
Bug introduced by
It seems like $response->withAddedHead...ry', 'Accept-Language') can also be of type null; however, parameter $response of W2w\Lib\Apie\Events\ResponseEvent::setResponse() does only seem to accept Psr\Http\Message\ResponseInterface, 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

172
                /** @scrutinizer ignore-type */ $response
Loading history...
173
                    ->withAddedHeader('Content-Language', $this->application->getLocale())
174
                    ->withAddedHeader('Vary', 'Accept-Language')
175
            );
176
        }
177
178
    }
179
180
    public function onPreCreateNormalizedData(NormalizeEvent $event)
181
    {
182
    }
183
184
    public function onPostCreateNormalizedData(NormalizeEvent $event)
185
    {
186
    }
187
188
    public function getSubActions()
189
    {
190
        return [
191
            'withPlaceholders' => [new TransChoiceSubAction($this->translator)]
192
        ];
193
    }
194
195
    public function getNormalizers(): array
196
    {
197
        $normalizer = new LocationableExceptionNormalizer(
198
            new ExceptionNormalizer($this->getApie()->isDebug()),
199
            $this->application->make(Translator::class)
200
        );
201
        return [
0 ignored issues
show
Bug Best Practice introduced by
The expression return array(new W2w\Lar...::class)), $normalizer) returns the type array<integer,W2w\Larave...ionExceptionNormalizer> which is incompatible with the return type mandated by W2w\Lib\Apie\PluginInter...rface::getNormalizers() of Symfony\Component\Serial...DenormalizerInterface[].

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
202
            new ValidationExceptionNormalizer($normalizer, $this->application->make(Translator::class)),
203
            $normalizer,
204
        ];
205
    }
206
}
207