Passed
Push — master ( c97c4f...cfd6ca )
by Luiz Kim
02:17
created

PeopleService::postPersist()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 21
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 5
nop 1
dl 0
loc 21
rs 9.0444
c 0
b 0
f 0
1
<?php
2
3
namespace ControleOnline\Service;
4
5
use ControleOnline\Entity\Document;
6
use ControleOnline\Entity\DocumentType;
7
use ControleOnline\Entity\Email;
8
use ControleOnline\Entity\ExtraData;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\ExtraData 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...
9
use ControleOnline\Entity\ExtraFields;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\ExtraFields 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...
10
use ControleOnline\Entity\Language;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\Language 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 ControleOnline\Entity\People;
12
use ControleOnline\Entity\PeopleLink;
13
use ControleOnline\Entity\Phone;
14
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...
15
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...
16
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Securi...e\TokenStorageInterface 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...
17
as Security;
18
use Doctrine\ORM\QueryBuilder;
0 ignored issues
show
Bug introduced by
The type Doctrine\ORM\QueryBuilder 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...
19
use Exception;
20
21
class PeopleService
22
{
23
  private $request;
24
25
  public function __construct(
26
    private EntityManagerInterface $manager,
27
    private Security               $security,
28
    private RequestStack $requestStack,
29
  ) {
30
    $this->request  = $requestStack->getCurrentRequest();
31
  }
32
33
  public function prePersist(People $people)
34
  {
35
    $language = $this->manager->getRepository(Language::class)->findOneBy(['language' => 'pt-br']);
36
    $people->setLanguage($language);
37
    return $people;
38
  }
39
40
  public function addClient() {}
41
42
43
  public function discoveryClient(People $provider, People $client) {}
0 ignored issues
show
Unused Code introduced by
The parameter $provider is not used and could be removed. ( Ignorable by Annotation )

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

43
  public function discoveryClient(/** @scrutinizer ignore-unused */ People $provider, People $client) {}

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $client is not used and could be removed. ( Ignorable by Annotation )

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

43
  public function discoveryClient(People $provider, /** @scrutinizer ignore-unused */ People $client) {}

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
44
45
  public function discoveryPeople(?string $document = null, ?string  $email = null, ?array $phone = [], ?string $name = null, ?string $peopleType = null): People
46
  {
47
48
    $people = $this->getDocument($document)?->getPeople();
0 ignored issues
show
Bug introduced by
It seems like $document can also be of type null; however, parameter $document_number of ControleOnline\Service\P...eService::getDocument() does only seem to accept string, 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

48
    $people = $this->getDocument(/** @scrutinizer ignore-type */ $document)?->getPeople();
Loading history...
49
50
    if (!$people)
0 ignored issues
show
introduced by
$people is of type ControleOnline\Entity\People, thus it always evaluated to true.
Loading history...
51
      $people = $this->getEmail($email)?->getPeople();
52
53
    if (!$people)
0 ignored issues
show
introduced by
$people is of type ControleOnline\Entity\People, thus it always evaluated to true.
Loading history...
54
      $people = $this->getPhone($phone['ddd'], $phone['phone'])?->getPeople();
55
56
    if (!$people) {
0 ignored issues
show
introduced by
$people is of type ControleOnline\Entity\People, thus it always evaluated to true.
Loading history...
57
      $people = new People();
58
      $people->setName($name ?? 'Name not given');
59
      $people->setLanguage($this->manager->getRepository(Language::class)->findOneBy(['language' => 'pt-br']));
60
      $people->setPeopleType($peopleType);
61
      $this->manager->persist($people);
62
      $this->manager->flush();
63
    }
64
65
    if ($document)
66
      $this->addDocument($people, $document);
67
    if ($email)
68
      $this->addEmail($people, $email);
69
    if ($phone)
0 ignored issues
show
Bug Best Practice introduced by
The expression $phone of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
70
      $this->addPhone($people, $phone);
71
72
73
    return $people;
74
  }
75
76
  public function addPhone(People $people, array $phone_number): Phone
77
  {
78
    $phone = $this->getPhone($phone_number['ddd'], $phone_number['phone']);
79
    if ($phone && $phone->getPeople()) {
80
      if ($phone->getPeople()->getId() != $people->getId())
81
        throw new Exception("Phone is in use by people " . $people->getId(), 1);
82
    } else {
83
      $phone = new Phone();
84
      $phone->setDdd($phone_number['ddd']);
85
      $phone->setPhone($phone_number['phone']);
86
      $phone->setPeople($people);
87
      $this->manager->persist($phone);
88
      $this->manager->flush();
89
    }
90
91
    return  $phone;
92
  }
93
  public function addDocument(People $people, string $document_number, ?string $document_type = null): Document
94
  {
95
    $document = $this->getDocument($document_number, $document_type);
96
    if ($document) {
97
      if ($document->getPeople()->getId() != $people->getId())
98
        throw new Exception("Document is in use by people " . $people->getId(), 1);
99
    } else {
100
      $document = new Document();
101
      $document->setDocument($document_number);
0 ignored issues
show
Bug introduced by
$document_number of type string is incompatible with the type integer expected by parameter $document of ControleOnline\Entity\Document::setDocument(). ( Ignorable by Annotation )

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

101
      $document->setDocument(/** @scrutinizer ignore-type */ $document_number);
Loading history...
102
      $document->setDocumentType($this->manager->getRepository(DocumentType::class)->findOneBy(['document_type' => $document_type]));
103
      $document->setPeople($people);
104
      $this->manager->persist($document);
105
      $this->manager->flush();
106
    }
107
108
    return  $document;
109
  }
110
111
  public function addEmail(People $people, string $email_str): Email
112
  {
113
    $email = $this->getEmail($email_str);
114
    if ($email && $email->getPeople()) {
115
      if ($email->getPeople()->getId() != $people->getId())
116
        throw new Exception("Email is in use by people " . $people->getId(), 1);
117
    } else {
118
      $email = new Email();
119
      $email->setEmail($email_str);
120
      $email->setPeople($people);
121
      $this->manager->persist($email);
122
      $this->manager->flush();
123
    }
124
125
    return  $email;
126
  }
127
128
  public function getEmail(string $email): ?Email
129
  {
130
    return $this->manager->getRepository(Email::class)->findOneBy(['email' => $email]);
131
  }
132
133
  public function getPhone(string $ddd, string $phone): ?Phone
134
  {
135
    return $this->manager->getRepository(Phone::class)->findOneBy(['ddd' => $ddd, 'ddd' => $phone]);
136
  }
137
138
139
  public function discoveryDocumentType(string $document_type): DocumentType
140
  {
141
    $documentType =  $this->manager->getRepository(DocumentType::class)->findOneBy(['document_type' => $document_type]);
142
143
    if (!$documentType) {
144
      $documentType = new DocumentType();
145
      $documentType->setDocumentType($document_type);
146
      $this->manager->persist($documentType);
147
      $this->manager->flush();
148
    }
149
150
    return $documentType;
151
  }
152
153
  public function getDocument(string $document_number, ?string $document_type = null): ?Document
154
  {
155
    if (!$document_type)
156
      $document_type = $this->getDocumentTypeByDocumentLen($document_number);
157
    return $this->manager->getRepository(Document::class)->findOneBy([
158
      'document' => $document_number,
159
      'documentType' =>
160
      $this->discoveryDocumentType($document_type)
161
    ]);
162
  }
163
164
  public function getDocumentTypeByDocumentLen($document_number)
165
  {
166
    return strlen($document_number) > 11 ? 'CNPJ' : 'CPF';
167
  }
168
169
  public function postPersist(People $people)
170
  {
171
    $request = $this->requestStack->getCurrentRequest();
172
    $payload   = json_decode($request->getContent());
173
    if (isset($payload->link_type)) {
174
      $company = $this->manager->getRepository(People::class)->find(preg_replace('/\D/', '', $payload->company));
175
      if ($company)
176
        $this->addLink($company, $people, $payload->link_type);
177
      else {
178
        $link = $this->manager->getRepository(People::class)->find(preg_replace('/\D/', '', $payload->link));
179
        if ($payload->link_type == 'employee' && $link) {
180
          $this->addLink($people, $link, $payload->link_type);
181
          if ($payload->people_document) {
182
            $document_type = $this->manager->getRepository(DocumentType::class)->findOneBy(['document_type' => 'cnpj']);
183
184
            $document = new Document();
185
            $document->setPeople($people);
186
            $document->setDocumentType($document_type);
187
            $document->setDocument($payload->people_document);
188
            $this->manager->persist($document);
189
            $this->manager->flush();
190
          }
191
        }
192
      }
193
    }
194
  }
195
196
  public function addLink(People $company, People $people, $link_type)
197
  {
198
199
    $peopleLink = $this->manager->getRepository(PeopleLink::class)->findOneBy([
200
      'company' => $company,
201
      'people' => $people,
202
      'link_type' => $link_type
203
    ]);
204
205
    if (!$peopleLink)
206
      $peopleLink = new PeopleLink();
207
208
    $peopleLink->setCompany($company);
209
    $peopleLink->setPeople($people);
210
    $peopleLink->setLinkType($link_type);
211
212
    $this->manager->persist($peopleLink);
213
    $this->manager->flush();
214
    return  $peopleLink;
215
  }
216
217
  public function securityFilter(QueryBuilder $queryBuilder, $resourceClass = null, $applyTo = null, $rootAlias = null): void
218
  {
219
    $this->checkLink($queryBuilder, $resourceClass, $applyTo, $rootAlias);
220
  }
221
222
  public function checkLink(QueryBuilder $queryBuilder, $resourceClass = null, $applyTo = null, $rootAlias = null): void
0 ignored issues
show
Unused Code introduced by
The parameter $resourceClass is not used and could be removed. ( Ignorable by Annotation )

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

222
  public function checkLink(QueryBuilder $queryBuilder, /** @scrutinizer ignore-unused */ $resourceClass = null, $applyTo = null, $rootAlias = null): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $applyTo is not used and could be removed. ( Ignorable by Annotation )

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

222
  public function checkLink(QueryBuilder $queryBuilder, $resourceClass = null, /** @scrutinizer ignore-unused */ $applyTo = null, $rootAlias = null): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
223
  {
224
225
    $link   = $this->request->query->get('link',   null);
226
    $company = $this->request->query->get('company', null);
227
    $link_type = $this->request->query->get('link_type', null);
228
229
    if ($link_type) {
230
      $queryBuilder->join(sprintf('%s.' . ($link ? 'company' : 'link'), $rootAlias), 'PeopleLink');
231
      $queryBuilder->andWhere('PeopleLink.link_type IN(:link_type)');
232
      $queryBuilder->setParameter('link_type', $link_type);
233
    }
234
235
    if ($company || $link) {
236
      $queryBuilder->andWhere('PeopleLink.' . ($link ? 'people' : 'company') . ' IN(:people)');
237
      $queryBuilder->setParameter('people', preg_replace("/[^0-9]/", "", ($link ?: $company)));
238
    }
239
  }
240
  public function checkCompany($type, QueryBuilder $queryBuilder, $resourceClass = null, $applyTo = null, $rootAlias = null): void
0 ignored issues
show
Unused Code introduced by
The parameter $applyTo is not used and could be removed. ( Ignorable by Annotation )

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

240
  public function checkCompany($type, QueryBuilder $queryBuilder, $resourceClass = null, /** @scrutinizer ignore-unused */ $applyTo = null, $rootAlias = null): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $resourceClass is not used and could be removed. ( Ignorable by Annotation )

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

240
  public function checkCompany($type, QueryBuilder $queryBuilder, /** @scrutinizer ignore-unused */ $resourceClass = null, $applyTo = null, $rootAlias = null): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
241
  {
242
    $companies   = $this->getMyCompanies();
243
    $queryBuilder->andWhere(sprintf('%s.' . $type . ' IN(:companies)', $rootAlias, $rootAlias));
244
    $queryBuilder->setParameter('companies', $companies);
245
246
    if ($payer = $this->request->query->get('company', null)) {
247
      $queryBuilder->andWhere(sprintf('%s.' . $type . ' IN(:people)', $rootAlias));
248
      $queryBuilder->setParameter('people', preg_replace("/[^0-9]/", "", $payer));
249
    }
250
  }
251
252
  public function getMyCompanies(): array
253
  {
254
    /**
255
     * @var \ControleOnline\Entity\User $currentUser
256
     */
257
    $token = $this->security->getToken();
258
    if (!$token) return [];
259
    $currentUser  =  $token->getUser();
260
    $companies    = [];
261
    if (!$currentUser) return [];
262
263
    if (!$currentUser->getPeople()->getLink()->isEmpty()) {
264
      foreach ($currentUser->getPeople()->getLink() as $company) {
265
        $companies[] = $company->getCompany();
266
      }
267
    }
268
    return $companies;
269
  }
270
}
271