Passed
Push — master ( 133ff2...246377 )
by Luiz Kim
02:06
created

SignatureService::getContractPDFContent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 14
rs 10
1
<?php
2
3
namespace Controleonline\Service;
4
5
use ControleOnline\Entity\People;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\People 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 ControleOnline\Entity\Contract as ContractEntity;
7
use App\Library\Provider\Signature\Document;
0 ignored issues
show
Bug introduced by
The type App\Library\Provider\Signature\Document 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
use App\Library\Provider\Signature\Signer;
0 ignored issues
show
Bug introduced by
The type App\Library\Provider\Signature\Signer 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 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...
10
use App\Library\Provider\Signature\Exception\InvalidParameterException;
0 ignored issues
show
Bug introduced by
The type App\Library\Provider\Sig...validParameterException 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 App\Library\Provider\Signature\Exception\ProviderRequestException;
0 ignored issues
show
Bug introduced by
The type App\Library\Provider\Sig...roviderRequestException 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...
12
use App\Library\Exception\MissingDataException;
0 ignored issues
show
Bug introduced by
The type App\Library\Exception\MissingDataException 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...
13
use App\Library\Provider\Signature\SignatureFactory;
0 ignored issues
show
Bug introduced by
The type App\Library\Provider\Signature\SignatureFactory 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...
14
use ControleOnline\Entity\Config;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Entity\Config 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 ControleOnline\Service\PeopleRoleService;
0 ignored issues
show
Bug introduced by
The type ControleOnline\Service\PeopleRoleService 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
17
class SignatureService
18
{
19
    protected $request;
20
    protected $signatureProvider;
21
    public function __construct(
22
        private EntityManagerInterface $manager,
23
        private PeopleRoleService $peopleRoleService,
24
25
    ) {}
26
27
28
    public function sign(ContractEntity $data)
29
    {
30
31
        $this->signatureProvider = $this->getFactory();
32
33
        if ($this->signatureProvider === null) {
34
            $data->setContractStatus('Waiting approval');
0 ignored issues
show
Bug introduced by
The method setContractStatus() does not exist on ControleOnline\Entity\Contract. Did you maybe mean setContractFile()? ( Ignorable by Annotation )

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

34
            $data->/** @scrutinizer ignore-call */ 
35
                   setContractStatus('Waiting approval');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
35
        } else {
36
37
            try {
38
39
                $document = ($this->signatureProvider->createDocument())
40
                    ->setFileName(
41
                        sprintf('Contrato-%s', $this->getContractContractorSignerName($data))
42
                    )
43
                    ->setContent($data->getContractFile()->getContent())
44
                    ->setDeadlineAt(
45
                        (new \DateTime('now'))
46
                            ->add(new \DateInterval('P7D'))
47
                            ->format('c')
48
                    );
49
50
                // config signers
51
52
                $this->addDocumentSignersFromContract($document, $data);
53
54
                // create document in cloud service
55
56
                $this->signatureProvider->saveDocument($document);
57
58
                // update contract status
59
60
                $data->setContractStatus('Waiting signatures');
61
                $data->setDocKey($document->getKey());
62
63
                $this->manager->persist($data);
64
                $this->manager->flush($data);
65
            } catch (InvalidParameterException $e) {
66
                throw new \Exception($e->getMessage());
67
            } catch (ProviderRequestException $e) {
68
                throw new \Exception($e->getMessage());
69
            } catch (MissingDataException $e) {
70
                throw new \Exception($e->getMessage());
71
            } catch (\Exception $e) {
72
                throw new \Exception($e->getMessage());
73
            }
74
        }
75
        return $data;
76
    }
77
78
79
    private function getProviderConfig(string $providerName): ?array
80
    {
81
82
        $myCompany = $this->peopleRoleService->getMainCompany();
83
        if ($myCompany instanceof People) {
84
85
            return $this->manager->getRepository(Config::class)
86
                ->getKeyValuesByPeople(
87
                    $myCompany,
88
                    strtolower($providerName)
89
                );
90
        }
91
92
        throw new \Exception('Company not found');
93
    }
94
95
    private function getDefaultProviderFromConfig(): ?string
96
    {
97
        $myCompany = $this->peopleRoleService->getMainCompany();
98
        if ($myCompany instanceof People) {
99
            $configs = $this->manager->getRepository(Config::class)
100
                ->getKeyValuesByPeople(
101
                    $myCompany,
102
                    'provider'
103
                );
104
105
            if ($configs === null) {
106
                return null;
107
            }
108
109
            return isset($configs['provider-signature']) ?
110
                $configs['provider-signature'] : null;
111
        }
112
113
        throw new \Exception('Company not found');
114
    }
115
    
116
    private function getFactory(?string $factoryName = null): ?SignatureFactory
117
    {
118
        $providerName = $factoryName === null ?
119
            $this->getDefaultProviderFromConfig() : $factoryName;
120
121
        if ($providerName === null) {
122
            return null;
123
        }
124
125
        $provider = sprintf(
126
            '\\App\\Library\\Provider\\Signature\\%s\\Factory',
127
            ucfirst(strtolower($providerName))
128
        );
129
130
        if (!class_exists($provider)) {
131
            throw new \Exception('Signature provider factory not found');
132
        }
133
134
        return new $provider(
135
            $this->getProviderConfig($providerName)
136
        );
137
    }
138
139
    protected function addDocumentSignersFromContract(Document $document, ContractEntity $contract)
140
    {
141
        if ($contract->getContractPeople()->isEmpty()) {
0 ignored issues
show
Bug introduced by
The method getContractPeople() does not exist on ControleOnline\Entity\Contract. Did you maybe mean getContractModel()? ( Ignorable by Annotation )

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

141
        if ($contract->/** @scrutinizer ignore-call */ getContractPeople()->isEmpty()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
142
            throw new MissingDataException('Este contrato não tem assinantes');
143
        }
144
145
        // add providers
146
147
148
        $contractProviders = $contract->getContractPeople()
149
            ->filter(function ($contractPeople) {
150
                return $contractPeople->getPeopleType() == 'Provider';
151
            });
152
        if ($contractProviders->isEmpty()) {
153
            throw new MissingDataException('O prestador de serviços não foi definido');
154
        }
155
156
        foreach ($contractProviders as $provider) {
157
            $document->addSigner(
158
                $this->getSignerFromPeople($provider->getPeople(), 'prestador de serviços')
159
            );
160
        }
161
162
        // add the rest
163
164
        $contractParticipants = $contract->getContractPeople()
165
            ->filter(function ($contractPeople) {
166
                return $contractPeople->getPeopleType() != 'Provider';
167
            });
168
        if ($contractParticipants->isEmpty()) {
169
            throw new MissingDataException(
170
                'Devem existir pelo menos 1 assinante no contrato'
171
            );
172
        }
173
174
        foreach ($contractParticipants as $participant) {
175
            $document->addSigner(
176
                $this->getSignerFromPeople($participant->getPeople(), 'assinante')
177
            );
178
        }
179
    }
180
181
    protected function getContractContractorSignerName(ContractEntity $contract): string
182
    {
183
        $contractPayers = $contract->getContractPeople()
184
            ->filter(function ($contractPeople) {
185
                return $contractPeople->getPeopleType() == 'Payer';
186
            });
187
        if ($contractPayers->isEmpty()) {
188
            throw new MissingDataException(
189
                'Devem existir pelo menos 1 assinante como contratante'
190
            );
191
        }
192
193
        return $contractPayers->first()->getPeople()->getFullName();
194
    }
195
196
197
    protected function getSignerFromPeople(People $people, string $role): Signer
198
    {
199
        $signer = $this->signatureProvider->createSigner();
200
201
        $signer->setKey($people->getId());
202
        $signer->setName($people->getFullName());
203
204
        if (($email = $people->getOneEmail()) === null) {
205
            throw new MissingDataException(
206
                sprintf('O %s "%s" não possui um email', $role, $people->getFullName())
207
            );
208
        }
209
210
        $signer->setEmail($email->getEmail());
211
212
        if ($people->isPeople()) {
213
            $signer->setHasCPF(true);
214
215
            if (($document = $people->getOneDocument()) === null) {
216
                throw new MissingDataException(
217
                    sprintf('O %s "%s" não possui um CPF/CNPJ', $role, $people->getFullName())
218
                );
219
            }
220
221
            $signer->setCPF($document->getDocument());
222
            if (($birthday = $people->getBirthdayAsString()) === null) {
223
                throw new MissingDataException(
224
                    sprintf(
225
                        'O %s "%s" não tem data de nascimento definida',
226
                        $role,
227
                        $people->getFullName()
228
                    )
229
                );
230
            }
231
232
            $signer->setBirthday($birthday);
233
        }
234
235
        return $signer;
236
    }
237
}
238