Passed
Pull Request — master (#13)
by Sergey
03:59 queued 01:10
created

CrudTest::testCrudDocument()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 66
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
eloc 32
c 2
b 0
f 2
dl 0
loc 66
rs 9.408
cc 1
nc 1
nop 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 SergeyNezbritskiy\NovaPoshta\Tests\Integration\Models\InternetDocument;
6
7
use PHPUnit\Framework\TestCase;
8
use SergeyNezbritskiy\NovaPoshta\Models\InternetDocument;
9
use SergeyNezbritskiy\NovaPoshta\NovaPoshtaApiException;
10
use SergeyNezbritskiy\NovaPoshta\Tests\AssertEntityByPropertiesTrait;
11
use SergeyNezbritskiy\NovaPoshta\Tests\ConstantsInterface;
12
use SergeyNezbritskiy\NovaPoshta\Tests\UsesConnectionTrait;
13
14
class CrudTest extends TestCase implements ConstantsInterface
15
{
16
    use AssertEntityByPropertiesTrait;
17
    use UsesConnectionTrait;
18
19
    private InternetDocument $model;
20
21
    protected function setUp(): void
22
    {
23
        date_default_timezone_set('Europe/Kyiv');
24
        $connection = $this->getConnection();
25
        $this->model = new InternetDocument($connection);
26
    }
27
28
    /**
29
     * @return void
30
     * @throws NovaPoshtaApiException
31
     */
32
    protected function tearDown(): void
33
    {
34
        foreach ($this->getAllDocuments() as $document) {
35
            $this->deleteDocument($document['Ref']);
36
        }
37
    }
38
39
    /**
40
     * @throws NovaPoshtaApiException
41
     */
42
    public function testCrudDocument(): void
43
    {
44
//        $counterpartyModel = new \SergeyNezbritskiy\NovaPoshta\Models\Counterparty($this->getConnection());
45
//        $addressModel = new \SergeyNezbritskiy\NovaPoshta\Models\Address($this->getConnection());
46
47
//        $recipient = $counterpartyModel->savePrivatePerson([
48
//            'FirstName' => 'Петро',
49
//            'MiddleName' => 'Григорович',
50
//            'LastName' => 'Порошенко',
51
//            'Phone' => 380501112233,
52
//            'Email' => '[email protected]',
53
//            'CounterpartyProperty' => Counterparty::COUNTERPARTY_PROPERTY_RECIPIENT,
54
//        ]); // 4d21c8c7-b88e-11ed-a60f-48df37b921db
55
        $recipientRef = '4d21c8c7-b88e-11ed-a60f-48df37b921db';
56
57
//        $address = $addressModel->save($recipientRef, [
58
//            'StreetRef' => self::KHRESHCHATYK_STREET_REF,
59
//            'BuildingNumber' => '20',
60
//            'Flat' => '12',
61
//        ]);
62
        $addressRef = 'cecaac32-25bb-11ee-a60f-48df37b921db';
63
64
//        $contactPersons = $counterpartyModel->getCounterpartyContactPersons(self::COUNTERPARTY_REF);
65
        $senderContactRef = '4d06cbac-b88e-11ed-a60f-48df37b921db';
66
67
//        $contactPersons = $counterpartyModel->getCounterpartyContactPersons($recipientRef);
68
        $recipientContactRef = '45b55250-25bb-11ee-a60f-48df37b921db';
69
70
        //create document
71
        $params = [
72
            'Sender' => self::COUNTERPARTY_REF,
73
            'CitySender' => self::CITY_REF_KHARKIV,
74
            'SenderAddress' => self::ADDRESS_REF_KHARKIV,
75
            'ContactSender' => $senderContactRef,
76
            'SendersPhone' => 380505511696,
77
78
            'Recipient' => $recipientRef,
79
            'CityRecipient' => self::CITY_REF_KYIV,
80
            'RecipientAddress' => $addressRef,
81
            'ContactRecipient' => $recipientContactRef,
82
            'RecipientsPhone' => 380505511696,
83
84
            'DateTime' => date('d.m.Y'),
85
            'CargoType' => InternetDocument::CARGO_TYPE_CARGO,
86
            'Weight' => '0.5',
87
            'SeatsAmount' => '1',
88
            'ServiceType' => InternetDocument::SERVICE_TYPE_DOORS_DOORS,
89
            'PayerType' => InternetDocument::PAYER_TYPE_RECIPIENT,
90
            'PaymentMethod' => InternetDocument::PAYMENT_TYPE_CASH,
91
            'Description' => 'Це тестове замовлення, не треба його обробляти'
92
        ];
93
94
        $actualResult = $this->model->save($params);
95
        $this->assertNotEmpty($actualResult['Ref']);
96
97
        $params['PayerType'] = InternetDocument::PAYER_TYPE_SENDER;
98
        $params['Ref'] = $actualResult['Ref'];
99
100
        $actualResult = $this->model->update($params);
101
        $document = $this->getDocumentByRef($actualResult['Ref']);
102
        $this->assertSame($params['PayerType'], $document['PayerType']);
103
104
        //delete document
105
        $this->deleteDocument($actualResult['Ref']);
106
107
        $this->assertDocumentDeleted($actualResult['Ref']);
108
    }
109
110
    /**
111
     * @param string $ref
112
     * @param int $attempt
113
     * @return void
114
     * @throws NovaPoshtaApiException
115
     * @SuppressWarnings(PHPMD.ElseExpression)
116
     */
117
    private function deleteDocument(string $ref, int $attempt = 1): void
118
    {
119
        try {
120
            $this->model->delete($ref);
121
        } catch (NovaPoshtaApiException $e) {
122
            $docNotCreatedYet = str_contains($e->getMessage(), 'No document changed DeletionMark');
123
            if (!$docNotCreatedYet) {
124
                throw $e;
125
            }
126
            $attemptsNotExceeded = $attempt <= 3;
127
            if ($attemptsNotExceeded) {
128
                printf(PHP_EOL . 'Attempt %d to delete document failed.' . PHP_EOL, $attempt);
129
                sleep(5 * $attempt);
130
                $this->deleteDocument($ref, ++$attempt);
131
            } else {
132
                throw $e;
133
            }
134
        }
135
    }
136
137
    /**
138
     * @param string $ref
139
     * @return void
140
     * @throws NovaPoshtaApiException
141
     */
142
    private function assertDocumentDeleted(string $ref): void
143
    {
144
        if ($this->getDocumentByRef($ref)) {
145
            $this->fail('Failed to delete document.');
146
        }
147
        $this->assertTrue(true, 'Just to suppress error that method doesn\'t do any assertions');
148
    }
149
150
    /**
151
     * @param string $ref
152
     * @return array|null
153
     * @throws NovaPoshtaApiException
154
     */
155
    public function getDocumentByRef(string $ref): ?array
156
    {
157
        $documents = $this->getAllDocuments();
158
        foreach ($documents as $document) {
159
            if ($document['Ref'] === $ref) {
160
                return $document;
161
            }
162
        }
163
        return null;
164
    }
165
166
    /**
167
     * @return array
168
     * @throws NovaPoshtaApiException
169
     */
170
    private function getAllDocuments(): array
171
    {
172
        return $this->model->getDocumentList([
173
            'DateTimeFrom' => date('d.m.Y', strtotime('-2 days')),
174
            'DateTimeTo' => date('d.m.Y', strtotime('+2 days')),
175
            'GetFullList' => 1,
176
            'DateTime' => date('d.m.Y'),
177
        ], 1);
178
    }
179
}
180