Passed
Push — master ( 61d39f...24b8d0 )
by Nikita
08:55
created

MockClient.php (4 issues)

1
<?php
2
3
namespace nikserg\CRMCertificateAPI;
4
5
6
use nikserg\CRMCertificateAPI\models\request\PartnerStores as PartnerStoresRequest;
7
use nikserg\CRMCertificateAPI\models\response\models\Store;
8
use nikserg\CRMCertificateAPI\models\response\PartnerStores as PartnerStoresResponse;
0 ignored issues
show
The type nikserg\CRMCertificateAP...\response\PartnerStores 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 nikserg\CRMCertificateAPI\models\Semantic;
10
use nikserg\CRMCertificateAPI\models\data\Status;
11
use nikserg\CRMCertificateAPI\models\PaymentModes;
12
use nikserg\CRMCertificateAPI\models\request\ChangeStatus;
13
use nikserg\CRMCertificateAPI\models\request\CheckPassport;
14
use nikserg\CRMCertificateAPI\models\request\CheckSnils;
15
use nikserg\CRMCertificateAPI\models\request\CustomerFormDocuments;
16
use nikserg\CRMCertificateAPI\models\request\Egrul as EgrulRequest;
17
use nikserg\CRMCertificateAPI\models\request\PartnerFullPrice as PartnerFullPriceRequest;
18
use nikserg\CRMCertificateAPI\models\request\PartnerPlatforms as PartnerPlatformsRequest;
19
use nikserg\CRMCertificateAPI\models\request\DetectPlatforms as DetectPlatformsRequest;
20
use nikserg\CRMCertificateAPI\models\response\DetectPlatformVariant;
21
use nikserg\CRMCertificateAPI\models\request\PartnerProducts as PartnerProductsRequest;
22
use nikserg\CRMCertificateAPI\models\request\SendCheckRef;
23
use nikserg\CRMCertificateAPI\models\request\SendCustomerForm as SendCustomerFormRequest;
24
use nikserg\CRMCertificateAPI\models\request\SendCustomerFormData;
25
use nikserg\CRMCertificateAPI\models\response\BooleanResponse;
26
use nikserg\CRMCertificateAPI\models\response\GetCustomerForm;
27
use nikserg\CRMCertificateAPI\models\response\GetOpportunity;
28
use nikserg\CRMCertificateAPI\models\response\PassportCheck;
29
use nikserg\CRMCertificateAPI\models\response\SnilsCheck;
30
use nikserg\CRMCertificateAPI\models\response\models\DetectPlatformVariantPlatform;
31
use nikserg\CRMCertificateAPI\models\response\models\PartnerPlatform;
32
use nikserg\CRMCertificateAPI\models\response\models\PartnerProduct;
33
use nikserg\CRMCertificateAPI\models\response\ReferralUser;
34
use nikserg\CRMCertificateAPI\models\response\SendCustomerForm as SendCustomerFormResponse;
35
use nikserg\CRMCertificateAPI\models\request\SendCustomerForm;
36
use nikserg\CRMCertificateAPI\models\response\Esia\Egrul as EgrulResponse;
37
38
/**
39
 * Тестовый клиент для связи с API CRM
40
 *
41
 * @package nikserg\CRMCertificateAPI
42
 */
43
class MockClient extends Client
44
{
45
    // "Правильные" паспорта
46
    public const PASSPORTCHECK_VALID_SERIES = '1111';
47
    public const PASSPORTCHECK_VALID_NUMBER = '111111';
48
    // "Неправильные" паспорта
49
    public const PASSPORTCHECK_INVALID_SERIES = '2222';
50
    public const PASSPORTCHECK_INVALID_NUMBER = '222222';
51
52
    // Данные для запроса ЕГРЮЛ
53
    public const EGRUL_IP_KULSH = PHP_INT_MAX - 2; // Выписка для ИП Кулиш Янина Викторовна
54
    public const EGRUL_LEGAL_ITK = PHP_INT_MAX - 1; // Пыписка для юридического лица ООО "ИТК"
55
56
    private static $data;
57
58
    private static function getData()
59
    {
60
        if (!empty(self::$data)) {
61
            return self::$data;
62
        }
63
        if (file_exists(__DIR__ . '/mock.runtime')) {
64
            self::$data = unserialize(file_get_contents(__DIR__ . '/mock.runtime'));
65
        } else {
66
            self::$data = [
67
                'currentId'     => 1,
68
                'currentStatus' => [
69
                    1 => 0,
70
                ],
71
            ];
72
        }
73
        return self::$data;
74
    }
75
76
    private static function flushData($data)
77
    {
78
        self::$data = $data;
79
        file_put_contents(__DIR__ . '/mock.runtime', serialize(self::$data));
80
    }
81
82
    public function egrul(EgrulRequest $request)
83
    {
84
        if ($request->customerForm == self::EGRUL_IP_KULSH) {
85
            return new EgrulResponse(json_decode('{ "id": 695854, "status": 2, "comment": "ok","data": { "organizationShortName": "ИП КУЛИШ ЯНИНА ВИКТОРОВНА", "OGRNIP": "306232719200028", "INN": "232702943100", "headLastName": "Кулиш", "headFirstName": "Янина", "headMiddleName": "Викторовна", "ownerGender": 2 }, "customerFormId": "559196" }'));
86
        } elseif ($request->customerForm == self::EGRUL_LEGAL_ITK) {
87
            return new EgrulResponse(json_decode('{ "id": 689373, "status": 2, "comment": "ok", "data": { "organizationShortName": "ООО \"ИТК\"", "organizationFullName": "ОБЩЕСТВО С ОГРАНИЧЕННОЙ ОТВЕТСТВЕННОСТЬЮ \"ИНТЕРНЕТ ТЕХНОЛОГИИ И КОММУНИКАЦИИ\"", "OGRN": "1112310000220", "INN": "2310152134", "KPP": "230801001", "fiasAddress": "КРАЙ КРАСНОДАРСКИЙ, ГОРОД КРАСНОДАР, УЛИЦА ДАЛЬНЯЯ, ДОМ 39\/3, ПОМЕЩЕНИЕ 140", "rawParticipators": [ " ", " ", " " ], "rawRegion": "КРАЙ КРАСНОДАРСКИЙ", "rawCity": "КРАСНОДАР", "rawOffice": "ПОМЕЩЕНИЕ 140", "rawHouse": "ДОМ 39\/3", "rawStreet": "УЛИЦА ДАЛЬНЯЯ", "postcode": "350051", "region": "23 Краснодарский край", "city": "Краснодар", "street": "УЛИЦА ДАЛЬНЯЯ, ДОМ 39\/3, ПОМЕЩЕНИЕ 140", "headLastName": "Сорокин", "headFirstName": "Дмитрий", "headMiddleName": "Викторович", "headPosition": "Генеральный директор" }, "customerFormId": "557436" }'));
88
        }
89
        return new EgrulResponse(json_decode('{"id":1,"status":2,"comment":"ok","data":{"organizationShortName":"ООО \"ИТК\"","organizationFullName":"ООО \"ИТК\"","OGRN":"1112310000220","INN":"2310152134","KPP":"12345678","region":"KRD","city":"Krasnodar","street":"One way st.","fiasAddress":"Krasnodar, One way st. 1337","headFirstName":"Дмитрий","headMiddleName":"Викторович","headLastName":"Сорокин","headPosition":"Генеральный директор"}}'));
90
    }
91
92
    public function getCustomerFormCertificateBlank($customerFormCrmId, $format = 'pdf')
93
    {
94
        return base64_encode(file_get_contents(__DIR__ . '/data/blank.pdf'));
95
    }
96
97
    public function getCustomerFormClaim($customerFormCrmId, $format = 'pdf')
98
    {
99
        return base64_encode(file_get_contents(__DIR__ . '/data/claim.pdf'));
100
    }
101
102
    public function sendCustomerForm(SendCustomerFormRequest $customerForm)
103
    {
104
        $response = new SendCustomerFormResponse();
105
        if ($customerForm->id) {
106
            $response->id = $customerForm->id;
107
        } else {
108
            $data = self::getData();
109
            $response->id = $data['currentId'];
110
            $data['currentStatus'][$response->id] = Status::INIT;
111
            $data['currentId'] = $response->id + 1;
112
            self::flushData($data);
113
        }
114
        $response->token = 'crmToken';
115
        $response->generationToken = 'crmGenerateToken';
116
        return $response;
117
    }
118
119
    public function getCustomerForm($customerFormCrmId)
120
    {
121
        $response = new GetCustomerForm();
122
        $data = self::getData();
123
        $response->status = $data['currentStatus'][$customerFormCrmId];
124
        $response->tokenCertificate = 'crmToken';
0 ignored issues
show
The property tokenCertificate does not seem to exist on nikserg\CRMCertificateAP...esponse\GetCustomerForm.
Loading history...
125
        $response->opportunityId = 1;
126
        return $response;
127
    }
128
129
    public function getOpportunity($opportunityCrmId)
130
    {
131
        $response = new GetOpportunity();
132
        $response->isPay = true;
0 ignored issues
show
Documentation Bug introduced by
The property $isPay was declared of type integer, but true is of type true. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
133
        $response->accountId = 1;
134
        $response->paymentToken = 'paymentToken';
0 ignored issues
show
Documentation Bug introduced by
The property $paymentToken was declared of type integer, but 'paymentToken' is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
135
        return $response;
136
    }
137
138
    public function changeStatus(ChangeStatus $changeStatus)
139
    {
140
        $data = self::getData();
141
        $data['currentStatus'][$changeStatus->id] = $changeStatus->status;
142
        self::flushData($data);
143
        $response = new BooleanResponse();
144
        $response->status = true;
145
        return $response;
146
    }
147
148
    public function deleteCustomerForm($customerFormCrmId)
149
    {
150
        $response = new BooleanResponse();
151
        $response->status = true;
152
        return $response;
153
    }
154
155
    public function sendCustomerFormData($crmCustomerFormId, SendCustomerFormData $customerFormData)
156
    {
157
        $response = new SendCustomerFormResponse();
158
        $response->id = $crmCustomerFormId;
159
        $response->token = 'crmToken';
160
        $response->generationToken = 'crmGenerateToken';
161
        return $response;
162
    }
163
164
    public function checkPassport(CheckPassport $request)
165
    {
166
        $response = new PassportCheck();
167
        if ($request->number == self::PASSPORTCHECK_INVALID_NUMBER) {
168
            $response->comment = 'Паспорт не существует (тест)';
169
            $response->status = Semantic::NEGATIVE;
170
        } else {
171
            $response->comment = '';
172
            $response->status = Semantic::POSITIVE;
173
        }
174
        return $response;
175
    }
176
177
    public function checkSnils(CheckSnils $request)
178
    {
179
        $response = new SnilsCheck();
180
        $response->id = 1;
181
        $response->status = Semantic::POSITIVE;
182
        $response->comment = '';
183
        $response->created = date("Y-m-d H:i:s");
184
        return $response;
185
    }
186
187
    public function getReferralUser(SendCheckRef $sendCheckRef)
188
    {
189
        $response = new ReferralUser();
190
        $response->id = 1;
191
        $response->paymentMode = PaymentModes::PAYMENT_UNLIMITED;
192
        $response->userName = 'username';
193
        $response->email = '[email protected]';
194
        $response->phone = 'hi :)';
195
        $response->isOfd = true;
196
        $response->enablePlatformSelection = true;
197
        return $response;
198
    }
199
200
    public function pushCustomerFormDocuments(CustomerFormDocuments $documents)
201
    {
202
        return true;
203
    }
204
205
    public function detectPlatforms(DetectPlatformsRequest $request)
206
    {
207
        $known = [
208
            "1.3.6.1.5.5.7.3.2",
209
            "1.3.6.1.5.5.7.3.4",
210
            "1.2.643.6.3.1.4.1",
211
            "1.2.643.6.3",
212
            "1.2.643.6.7",
213
            "1.2.643.6.3.1.1",
214
            "1.2.643.3.8.100.1.42",
215
            "1.2.643.100.113.1",
216
            "1.2.643.100.113.2",
217
            "1.2.643.2.2.34.6",
218
            "1.2.643.6.19.3",
219
            "1.2.643.6.3.1.4.3",
220
            "1.2.643.6.3.1.4.2",
221
            "1.2.643.6.3.1.3.1",
222
            "1.2.643.6.3.1.2.1",
223
        ];
224
        $unknown = array_diff($request->oids, $known);
225
        $variant = new DetectPlatformVariant();
226
        $platform1 = new DetectPlatformVariantPlatform();
227
        $platform1->value = 'AETP';
228
        $platform1->name = 'АЭТП';
229
        $platform2 = new DetectPlatformVariantPlatform();
230
        $platform2->value = 'PROLONGATION_BIDDING_COMPLECT';
231
        $platform2->name = 'Тариф «ЭП Торги-комплект»';
232
        $variant->platforms = [$platform1, $platform2];
233
        $variant->price = 5000;
234
        $variant->excluded = $unknown;
235
        return [$variant];
236
    }
237
238
    public function getPartnerPlatformsAll(PartnerPlatformsRequest $request)
239
    {
240
        $json = /** @lang JSON */
241
            '{
242
            "platforms": [
243
                {
244
                    "price": 2500,
245
                    "description": "Описание EPGU",
246
                    "name": "Имя EPGU",
247
                    "platform": "EPGU"
248
                },
249
                {
250
                    "price": 17600,
251
                    "description": "Описание FABRIKANT",
252
                    "name": "Имя FABRIKANT",
253
                    "platform": "FABRIKANT"
254
                },
255
                {
256
                    "price": 3500,
257
                    "description": "Описание AETP_NEW_BASE",
258
                    "name": "Имя AETP_NEW_BASE",
259
                    "platform": "AETP_NEW_BASE"
260
                },
261
                {
262
                    "price": 6900,
263
                    "description": "Имя Описание B2B",
264
                    "name": "Имя B2B",
265
                    "platform": "B2B"
266
                },
267
                {
268
                    "price": 1777,
269
                    "description": "АЭТП",
270
                    "name": "АЭТП",
271
                    "platform": "AETP"
272
                },
273
                {
274
                    "price": 1333,
275
                    "description": "Тариф «ЭП Торги-комплект»",
276
                    "name": "Тариф «ЭП Торги-комплект»",
277
                    "platform": "PROLONGATION_BIDDING_COMPLECT"
278
                }
279
            ]
280
        }';
281
        $result = json_decode($json);
282
        $response = [];
283
        foreach ($result->platforms as $platform) {
284
            $partnerPlatform = new PartnerPlatform;
285
            $partnerPlatform->name = $platform->name;
286
            $partnerPlatform->group = "Группа";
287
            $partnerPlatform->description = $platform->description;
288
            $partnerPlatform->platform = $platform->platform;
289
            $partnerPlatform->price = $platform->price;
290
            $response[] = $partnerPlatform;
291
        }
292
        return $response;
293
    }
294
295
    public function getPartnerProductsAll(PartnerProductsRequest $request)
296
    {
297
        $json = /** @lang JSON */
298
            '{
299
            "productInfo": [
300
                {
301
                    "id": 981,
302
                    "price": 1500,
303
                    "name": "Сертифицированный защищенный носитель (Рутокен)",
304
                    "description": "Рутокен — специальное сертифицированное защищённое USB-устройство, внешне похожее на флешку. Предназначено для хранения и использования электронной подписи (КЭП)."
305
                },
306
                {
307
                    "id": 511,
308
                    "price": 700,
309
                    "name": "Лицензия на право использования СКЗИ КриптоПро CSP в составе сертификата ключа",
310
                    "description": "КриптоПро - специальная программа криптозащиты.\\nОна используется для генерации ключа электронной подписи и работы с сертификатами. Без действующей лицензии СКЗИ КриптоПро CSP электронная подпись на вашем компьютере не сможет работать."
311
                },
312
                {
313
                    "id": 127,
314
                    "price": 1000,
315
                    "name": "Установка СКЗИ КриптоПро CSP и КЭП",
316
                    "description": "Процесс установки СКЗИ «КриптоПро» и настройки рабочего места для корректной работы электронной подписи — весьма трудоёмкий и требует специальных знаний. Чтобы облегчить и ускорить этот процесс, закажите его у специалистов технической поддержки."
317
                }
318
            ]
319
        }';
320
        $result = json_decode($json);
321
        $response = [];
322
        foreach ($result->productInfo as $product) {
323
            $partnerPlatform = new PartnerProduct();
324
            $partnerPlatform->name = $product->name;
325
            $partnerPlatform->description = $product->description;
326
            $partnerPlatform->id = $product->id;
327
            $partnerPlatform->price = $product->price;
328
            $response[] = $partnerPlatform;
329
        }
330
        return $response;
331
    }
332
333
    public function getPartnerFullPrice(PartnerFullPriceRequest $fullPriceRequest)
334
    {
335
        return 666;
336
    }
337
338
    public function getPartnerStores(PartnerStoresRequest $partnerStores)
339
    {
340
        $json = /** @lang JSON */
341
            '{
342
              "stores": [
343
                {
344
                    "id": 3195,
345
                    "title": "ИП Глумова Татьяна Борисовна",
346
                    "address": "656002, Алтайский край, Барнаул г, Сизова ул, дом № 14Б",
347
                    "phone": "",
348
                    "lat": "53.280205",
349
                    "lng": "83.761495"
350
                },
351
                {
352
                    "id": 3225,
353
                    "title": "ООО БРАВО",
354
                    "address": "659319, Алтайский край, Бийск г, Петра Мерлина ул, дом № 58, кв 311",
355
                    "phone": "",
356
                    "lat": "52.530544",
357
                    "lng": "85.16064800000004"
358
                },
359
                {
360
                    "id": 3049,
361
                    "title": "ИП Лапина Ирина Анатольевна",
362
                    "address": "453431, Башкортостан респ, Благовещенский р-н, Благовещенск г, Седова ул, дом № 110",
363
                    "phone": "",
364
                    "lat": "55.049091",
365
                    "lng": "55.95632899999998"
366
                }
367
              ]
368
            }';
369
        $result = json_decode($json);
370
        return $this->fillList(Store::class, $result->stores);
371
    }
372
}