Passed
Push — master ( 597eeb...295a68 )
by Luiz Kim
02:21
created

HydratorService::getSearch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 29
rs 9.6333
cc 2
nc 2
nop 1
1
<?php
2
3
namespace ControleOnline\Service;
4
5
use Symfony\Component\Security\Core\Security;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Security\Core\Security was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Symfony\Component\Serializer\SerializerInterface;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Serializer\SerializerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Symfony\Component\HttpFoundation\RequestStack;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\HttpFoundation\RequestStack was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
10
use Doctrine\ORM\EntityManagerInterface;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\EntityManagerInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Exception;
12
13
class HydratorService
14
{
15
16
    private $request;
17
    private $uri;
18
19
    public function __construct(
20
        private  EntityManagerInterface $manager,
21
        private   SerializerInterface $serializer,
22
        RequestStack $requestStack
23
    ) {
24
25
        $this->serializer = $serializer;
26
        $this->request = $requestStack->getCurrentRequest();
27
        $this->uri = $this->request ? $this->request->getPathInfo() : '';
28
    }
29
    public function error(Exception $e)
30
    {
31
        return $e;
32
    }
33
    
34
    public function collection($class, $groups,  mixed $arguments = [], int $limit = 0, int $page = 1, array $orderby = [])
35
    {
36
        $response = $this->getBasicResponse($class);
37
38
        $response['hydra:member']      =   $this->getMembers($class, $groups, $arguments, $limit, $page, $orderby);
39
        $response['hydra:search']       =   $this->getSearch($class);
40
        $response['hydra:totalItems']   =   $this->getCount($class, $arguments);
41
42
        return $response;
43
    }
44
45
    public function result($result)
46
    {
47
        //$response = $this->getBasicResponse($class);
48
        //$response['hydra:search']       =   $this->getSearch($class);
49
50
        $response['hydra:member']      =  $result;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.
Loading history...
51
        $response['hydra:totalItems']   =   count($response['hydra:member']);
52
53
        return $response;
54
    }
55
56
    public function item($class, $id, $groups)
57
    {
58
        $data =     $this->manager->getRepository($class)->find(preg_replace("/[^0-9]/", "", $id));
59
        $analisesSerialized = $this->serializer->serialize($data, 'jsonld', ['groups' => $groups]);
60
        return json_decode($analisesSerialized);
61
    }
62
63
    private function getBasicResponse($class)
64
    {
65
        $className = substr($class, strrpos($class, '\\') + 1);
66
67
        $response['@id']        = '/' . strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $className)) . 's';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$response was never initialized. Although not strictly required by PHP, it is generally a good practice to add $response = array(); before regardless.
Loading history...
68
        $response['@context']   =   "/contexts/" . $className;
69
        $response['@type']      =   "hydra:Collection";
70
71
        $response['hydra:view'] = [
72
            '@id' =>   $this->uri,
73
            '@type' => 'hydra:PartialCollectionView'
74
        ];
75
        return $response;
76
    }
77
78
    private function getMembers($class, $groups, mixed $arguments = [], int $limit = 0, int $page = 1, array $orderby = [])
79
    {
80
81
        if ($limit < 1)
82
            $limit = $this->request->get('itemsPerPage') ?: 50;
83
84
        if ($page == 1)
85
            $offset = (($page = $this->request->get('page') ?: 1) - 1) * $limit;
0 ignored issues
show
Unused Code introduced by
The assignment to $page is dead and can be removed.
Loading history...
86
87
        $data =     $this->manager->getRepository($class)->findBy($arguments, $orderby, $limit, $offset);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $offset does not seem to be defined for all execution paths leading up to this point.
Loading history...
88
89
        return $this->serialize($data, ['groups' => $groups]);
90
    }
91
92
    private function serialize($data, array $groups = [])
93
    {
94
        $analisesSerialized = $this->serializer->serialize($data, 'jsonld', $groups);
95
        return json_decode($analisesSerialized);
96
    }
97
98
99
    private function getCount($class, $arguments)
100
    {
101
        return $this->manager->getRepository($class)->count($arguments);
102
    }
103
104
    private function getSearch($class)
105
    {
106
107
        $metadata = $this->manager->getClassMetadata($class);
108
        $arguments = $metadata->getFieldNames();
109
        $search = [
110
            '@type' => 'hydra:IriTemplate',
111
            'hydra:template' =>   $this->uri . '{?' . implode(',', array_values($arguments)) . '}',
112
            'hydra:variableRepresentation' => 'BasicRepresentation',
113
            'hydra:mapping' => []
114
        ];
115
116
        foreach ($metadata->getFieldNames() as $field) {
117
118
            $search['hydra:mapping'][] = [
119
                '@type' => 'IriTemplateMapping',
120
                'variable' => $field,
121
                'property' => $field,
122
                'required' => false
123
            ];
124
            $search['hydra:mapping'][] = [
125
                '@type' => 'IriTemplateMapping',
126
                'variable' => $field . '[]',
127
                'property' => $field,
128
                'required' => false
129
            ];
130
        }
131
132
        return $search;
133
    }
134
}
135