Passed
Pull Request — master (#13)
by Sergey
03:05
created

CrudTest::assertDocumentDeleted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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