Failed Conditions
Push — master ( a427b2...509ea4 )
by Adrien
16:44
created

OpenDoor::build()   B

Complexity

Conditions 8
Paths 1

Size

Total Lines 67
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 45.6357

Importance

Changes 0
Metric Value
cc 8
eloc 41
nc 1
nop 0
dl 0
loc 67
ccs 6
cts 37
cp 0.1622
crap 45.6357
rs 8.0195
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Api\Field\Mutation;
6
7
use Application\Api\Enum\DoorType;
8
use Application\Api\Output\OpenDoorType;
9
use Application\Model\User;
10
use Application\Repository\LogRepository;
11
use Ecodev\Felix\Api\Exception;
12
use Ecodev\Felix\Api\Field\FieldInterface;
13
use GraphQL\Type\Definition\Type;
14
use Laminas\Http\Client;
15
use Laminas\Http\Request;
16
use Laminas\Http\Response;
17
use Mezzio\Session\SessionInterface;
18
19
abstract class OpenDoor implements FieldInterface
20
{
21 1
    public static function build(): array
22
    {
23
        return [
24 1
            'name' => 'openDoor',
25 1
            'type' => Type::nonNull(_types()->get(OpenDoorType::class)),
26 1
            'description' => 'Open a door at the premises',
27
            'args' => [
28 1
                'door' => Type::nonNull(_types()->get(DoorType::class)),
29
            ],
30 1
            'resolve' => function ($root, array $args, SessionInterface $session): array {
31
                global $container;
32
33
                if (!preg_match('/door([1-4])/', (string) $args['door'], $m)) {
34
                    throw new Exception("La porte demandée n'existe pas");
35
                }
36
                $doorIndex = $m[1];
37
38
                $user = User::getCurrent();
39
                if (!$user || !$user->getCanOpenDoor($args['door'])) {
40
                    throw new Exception("Tu n'as pas le droit d'ouvrir cette porte");
41
                }
42
43
                $apiConfig = $container->get('config')['doorsApi'];
44
                $attrs = [
45
                    'door' => $doorIndex,
46
                    'token' => $apiConfig['token'],
47
                ];
48
49
                $request = new Request();
50
                $request->getHeaders()->addHeaders(['Content-Type' => 'application/json']);
51
                $request->setUri($apiConfig['endpoint'] . '/open');
52
                $request->setMethod(Request::METHOD_POST);
53
                $request->setContent(json_encode($attrs));
54
55
                $client = new Client();
56
57
                try {
58
                    /** @var Response $response */
59
                    $response = $client->dispatch($request);
60
                } catch (\Laminas\Http\Client\Exception\RuntimeException $e) {
61
                    // No answer from the websocket
62
                    _log()->err($e->getMessage(), $attrs);
63
64
                    throw new Exception('Commande de porte temporairement inaccessible, essaie plus tard ou contacte un administrateur');
65
                }
66
67
                $content = json_decode($response->getContent(), true);
68
69
                if ($response->getStatusCode() === 200) {
70
                    _log()->info(LogRepository::DOOR_OPENED . $doorIndex, $attrs);
71
72
                    return $content;
73
                }
74
75
                if (preg_match('/^5[0-9]{2}/', (string) $response->getStatusCode())) {
76
                    $errorMsg = "Commande de porte inaccessible en raison d'une erreur serveur, essaie plus tard ou contacte un administrateur";
77
                } else {
78
                    $errorMsg = $content['message'] ?? 'Erreur de commande de porte, essaie plus tard ou contacte un administrateur';
79
                }
80
81
                // Log body if we have anything
82
                $body = trim($response->getBody());
83
                if ($body) {
84
                    _log()->err($response->getBody(), $attrs);
85
                }
86
87
                throw new Exception($errorMsg);
88
            },
89
        ];
90
    }
91
}
92