Completed
Push — master ( 596467...bf19e6 )
by Vítězslav
11:06
created

FlexiBeeROTest::testunifyResponseFormat()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 38
rs 8.8571
cc 1
eloc 18
nc 1
nop 0
1
<?php
2
3
namespace Test\FlexiPeeHP;
4
5
use FlexiPeeHP\FlexiBeeRO;
6
7
/**
8
 * Generated by PHPUnit_SkeletonGenerator on 2016-05-04 at 10:08:36.
9
 */
10
class FlexiBeeROTest extends \Test\Ease\BrickTest
11
{
12
    /**
13
     * @var FlexiBeeRO
14
     */
15
    protected $object;
16
17
    /**
18
     * Sets up the fixture, for example, opens a network connection.
19
     * This method is called before a test is executed.
20
     * @covers FlexiPeeHP\FlexiBeeRO::__construct
21
     */
22
    protected function setUp()
23
    {
24
        $this->object            = new FlexiBeeRO();
25
        $this->object->evidence  = 'c';
26
        $this->object->prefix    = '';
27
        $this->object->company   = '';
28
        $this->object->nameSpace = 'companies';
29
    }
30
31
    /**
32
     * Tears down the fixture, for example, closes a network connection.
33
     * This method is called after a test is executed.
34
     */
35
    protected function tearDown()
36
    {
37
        
38
    }
39
40
    /**
41
     * @covers FlexiPeeHP\FlexiBeeRO::curlInit
42
     */
43
    public function testCurlInit()
44
    {
45
        $this->object->curlInit();
46
        $this->assertTrue(is_resource($this->object->curl));
47
    }
48
49
    /**
50
     * @covers FlexiPeeHP\FlexiBeeRO::processInit
51
     */
52
    public function testProcessInit()
53
    {
54
        $this->object->processInit(['id' => 1]);
55
        $this->assertEquals(1, $this->object->getDataValue('id'));
56
        if (!is_null($this->object->evidence) && $this->object->evidence != 'test') {
57
            $firstID = $this->object->getColumnsFromFlexibee('id',
0 ignored issues
show
Documentation introduced by
'id' is of type string, but the function expects a array<integer,string>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
58
                ['limit' => 1]);
59
            $this->object->processInit((int) current($firstID));
60
            $this->assertNotEmpty($this->object->__toString());
61
        }
62
    }
63
64
    /**
65
     * @covers FlexiPeeHP\FlexiBeeRO::setEvidence
66
     */
67
    public function testSetEvidence()
68
    {
69
        $this->object->setEvidence('nastaveni');
70
        $this->assertEquals('nastaveni', $this->object->evidence);
71
    }
72
73
    /**
74
     * @covers FlexiPeeHP\FlexiBeeRO::object2array
75
     */
76
    public function testObject2array()
77
    {
78
        $this->assertNull($this->object->object2array(new \stdClass()));
79
        $this->assertEquals(
80
            [
81
            'item' => 1,
82
            'arrItem' => ['a', 'b' => 'c']
83
            ]
84
            , $this->object->object2array(new \Test\ObjectForTesting()));
85
    }
86
87
    /**
88
     * @covers FlexiPeeHP\FlexiBeeRO::objectToID
89
     */
90
    public function testObjectToID()
91
    {
92
        $id = \Ease\Sand::randomNumber(1, 9999);
93
        $this->object->setMyKey($id);
0 ignored issues
show
Security Bug introduced by
It seems like $id defined by \Ease\Sand::randomNumber(1, 9999) on line 92 can also be of type false; however, Ease\Brick::setMyKey() does only seem to accept integer|string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
94
        $this->assertEquals([$id], $this->object->objectToID([$this->object]));
95
96
        $this->object->setDataValue('kod', 'TEST');
97
        $this->assertEquals('code:TEST',
98
            $this->object->objectToID($this->object));
99
100
        $this->assertEquals('TEST', $this->object->objectToID('TEST'));
0 ignored issues
show
Documentation introduced by
'TEST' is of type string, but the function expects a object|array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
101
    }
102
103
    /**
104
     * @covers FlexiPeeHP\FlexiBeeRO::performRequest
105
     */
106
    public function testPerformRequest()
107
    {
108
        $evidence = $this->object->getEvidence();
109
        switch ($evidence) {
110
            case null:
111
            case '':
112
            case 'test':
113
            case 'c':
114
                $this->object->evidence  = 'c';
115
                $this->object->prefix    = '';
116
                $this->object->company   = '';
117
                $this->object->nameSpace = 'companies';
118
                $json                    = $this->object->performRequest();
119
                $this->assertArrayHasKey('company', $json);
120
121
                $xml = $this->object->performRequest(null, 'GET', 'xml');
122
                $this->assertArrayHasKey('company', $xml);
123
                break;
124
125
            default:
126
                $json = $this->object->performRequest($evidence.'.json');
127
                if (array_key_exists('message', $json)) {
128
                    $this->assertArrayHasKey('@version', $json);
129
                } else {
130
                    $this->assertArrayHasKey($evidence, $json);
131
                }
132
                break;
133
        }
134
135
136
        $err = $this->object->performRequest('error.json');
137
        $this->assertArrayHasKey('success', $err);
138
        $this->assertEquals('false', $err['success']);
139
    }
140
141
    /**
142
     * @covers FlexiPeeHP\FlexiBeeRO::setAction
143
     */
144
    public function testSetAction()
145
    {
146
        $this->assertTrue($this->object->setAction('none'));
147
        $this->object->actionsAvailable = [];
148
        $this->assertFalse($this->object->setAction('none'));
149
        $this->object->actionsAvailable = ['copy'];
150
        $this->assertFalse($this->object->setAction('none'));
151
    }
152
153
    /**
154
     * @covers FlexiPeeHP\FlexiBeeRO::getEvidence
155
     */
156
    public function testGetEvidence()
157
    {
158
        $this->assertEquals($this->object->evidence,
159
            $this->object->getEvidence());
160
    }
161
162
    /**
163
     * @covers FlexiPeeHP\FlexiBeeRO::getResponseEvidence
164
     */
165
    public function testGetResponseEvidence()
166
    {
167
        $this->assertEquals($this->object->getEvidence(),
168
            $this->object->getResponseEvidence());
169
    }
170
171
    /**
172
     * @covers FlexiPeeHP\FlexiBeeRO::getLastInsertedId
173
     * @depends testInsertToFlexiBee
174
     */
175
    public function testGetLastInsertedId()
176
    {
177
        $this->assertNotEmpty($this->object->getLastInsertedId());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class FlexiPeeHP\FlexiBeeRO as the method getLastInsertedId() does only exist in the following sub-classes of FlexiPeeHP\FlexiBeeRO: FlexiPeeHP\Adresar, FlexiPeeHP\Banka, FlexiPeeHP\Cenik, FlexiPeeHP\FakturaVydana, FlexiPeeHP\FakturaVydanaPolozka, FlexiPeeHP\FlexiBeeRW, FlexiPeeHP\Hooks, FlexiPeeHP\Kontakt, FlexiPeeHP\Pokladna, FlexiPeeHP\PokladniPohyb, FlexiPeeHP\RadaPokladniPohyb, FlexiPeeHP\SkladovyPohyb, FlexiPeeHP\SkladovyPohybPolozka, FlexiPeeHP\SkupinaFirem, FlexiPeeHP\Stitek, FlexiPeeHP\Strom, FlexiPeeHP\StromCenik, FlexiPeeHP\UcetniObdobi, FlexiPeeHP\VyrobniCislo. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
178
    }
179
180
    /**
181
     * @covers FlexiPeeHP\FlexiBeeRO::xml2array
182
     */
183
    public function testXml2array()
184
    {
185
        $xml = '<card xmlns="http://businesscard.org">
186
   <name>John Doe</name>
187
   <title>CEO, Widget Inc.</title>
188
   <email>[email protected]</email>
189
   <phone>(202) 456-1414</phone>
190
   <logo url="widget.gif"/>
191
   <a><b>c</b></a>
192
 </card>';
193
194
        $data = ['name' => 'John Doe', 'title' => 'CEO, Widget Inc.', 'email' => '[email protected]',
195
            'phone' => '(202) 456-1414', 'logo' => '', 'a' => [['b' => 'c']]];
196
197
198
        $this->assertEquals($data, $this->object->xml2array($xml));
199
    }
200
201
    /**
202
     * @covers FlexiPeeHP\FlexiBeeRO::disconnect
203
     *
204
     * @depends testPerformRequest
205
     * @depends testLoadFlexiData
206
     * @depends testGetFlexiRow
207
     * @depends testGetFlexiData
208
     * @depends testLoadFromFlexiBee
209
     * @depends testInsertToFlexiBee
210
     * @depends testIdExists
211
     * @depends testRecordExists
212
     * @depends testGetColumnsFromFlexibee
213
     * @depends testSearchString
214
     */
215
    public function testDisconnect()
216
    {
217
        $this->object->disconnect();
218
        $this->assertNull($this->object->curl);
219
    }
220
221
    /**
222
     * @covers FlexiPeeHP\FlexiBeeRO::__destruct
223
     * @depends testDisconnect
224
     */
225
    public function testdestruct()
226
    {
227
        $this->markTestSkipped();
228
    }
229
230
    /**
231
     * @covers FlexiPeeHP\FlexiBeeRO::getFlexiRow
232
     */
233
    public function testGetFlexiRow()
234
    {
235
        $this->object->getFlexiRow(0);
236
        $this->object->getFlexiRow(1);
237
    }
238
239
    /**
240
     * @covers FlexiPeeHP\FlexiBeeRO::getFlexiData
241
     */
242
    public function testGetFlexiData()
243
    {
244
        $evidence = $this->object->getEvidence();
245
246
        switch ($evidence) {
247
            case null:
248
                $this->markTestSkipped('Unsupported evidence');
249
                break;
250
            case 'c':
251
                $this->object->evidence  = 'c';
252
                $this->object->prefix    = '';
253
                $this->object->company   = '';
254
                $this->object->nameSpace = 'companies';
255
                $flexidata               = $this->object->getFlexiData();
256
                $this->assertArrayHasKey('company', $flexidata);
257
                break;
258
259
            default:
260
                $flexidata = $this->object->getFlexiData();
261 View Code Duplication
                if (is_array($flexidata) && !count($flexidata)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
262
                    $this->markTestSkipped('Empty evidence');
263
                } else {
264
                    $this->assertArrayHasKey(0, $flexidata);
265
                    $this->assertArrayHasKey('id', $flexidata[0]);
266
                    $filtrered = $this->object->getFlexiData(null,
267
                        "id = ".$flexidata[0]['id']);
268
                    $this->assertArrayHasKey(0, $filtrered);
269
                    $this->assertArrayHasKey('id', $filtrered[0]);
270
                }
271
                break;
272
        }
273
    }
274
275
    /**
276
     * @covers FlexiPeeHP\FlexiBeeRO::loadFromFlexiBee
277
     */
278
    public function testLoadFromFlexiBee()
279
    {
280
        $this->object->loadFromFlexiBee();
281
        $this->object->loadFromFlexiBee(222);
282
    }
283
284
    /**
285
     * @covers FlexiPeeHP\FlexiBeeRO::jsonizeData
286
     */
287
    public function testJsonizeData()
288
    {
289
        $this->assertEquals('{"'.$this->object->nameSpace.'":{"@version":"1.0","'.$this->object->evidence.'":{"key":"value"}}}',
290
            $this->object->jsonizeData(['key' => 'value']));
291
        $this->object->setAction('copy');
292
        $this->assertEquals('{"'.$this->object->nameSpace.'":{"@version":"1.0","'.$this->object->evidence.'":{"key":"value"},"'.$this->object->evidence.'@action":"copy"}}',
293
            $this->object->jsonizeData(['key' => 'value']));
294
    }
295
296
    /**
297
     * @covers FlexiPeeHP\FlexiBeeRO::idExists
298
     */
299
    public function testIdExists()
300
    {
301
        // Remove the following lines when you implement this test.
302
        $this->markTestIncomplete(
303
            'This test has not been implemented yet.'
304
        );
305
    }
306
307
    /**
308
     * @covers FlexiPeeHP\FlexiBeeRO::recordExists
309
     */
310
    public function testRecordExists()
311
    {
312
        $evidence = $this->object->getEvidence();
313
314
        switch ($evidence) {
315
            case null:
316
            case 'c':
317
                $this->markTestSkipped('Unsupported evidence');
318
                break;
319
320
            default:
321
                $flexidata = $this->object->getFlexiData(null, ['limit' => 1]);
322
                if (is_array($flexidata) && !count($flexidata)) {
323
                    $this->markTestSkipped('Empty evidence');
324
                } else {
325
                    if (isset($flexidata['success']) && ($flexidata['success'] == 'false')) {
326
                        $this->markTestSkipped($flexidata['message']);
327
                    } else {
328
                        $this->object->setData(['id' => (int) $flexidata[0]['id']]);
329
                        $this->assertTrue($this->object->recordExists());
330
                        $this->assertFalse($this->object->recordExists(['id' => 0]));
331
                        $this->assertFalse($this->object->recordExists(['unexistent' => 1]));
332
                    }
333
                }
334
                break;
335
        }
336
    }
337
338
    /**
339
     * @covers FlexiPeeHP\FlexiBeeRO::getColumnsFromFlexibee
340
     */
341
    public function testGetColumnsFromFlexibee()
342
    {
343
        // Remove the following lines when you implement this test.
344
        $this->markTestIncomplete(
345
            'This test has not been implemented yet.'
346
        );
347
    }
348
349
    /**
350
     * @covers FlexiPeeHP\FlexiBeeRO::getKod
351
     */
352
    public function testGetKod()
353
    {
354
355
        $this->assertEquals('CODE',
356
            $this->object->getKod([$this->object->myKeyColumn => 'code']));
357
358
        $testString[$this->object->nameColumn] = 'Fish clamp -  Úchytka pro instalaci samonosných kabelů '
0 ignored issues
show
Coding Style Comprehensibility introduced by
$testString was never initialized. Although not strictly required by PHP, it is generally a good practice to add $testString = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
359
            .'(3.5 mm)';
360
        $code0                                 = $this->object->getKod($testString);
361
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code0);
362
        $code1                                 = $this->object->getKod($testString,
363
            false);
364
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code1);
365
        $code2                                 = $this->object->getKod($testString);
366
        $this->assertEquals('FISHCLAMPUCHYTKAPR1', $code2);
367
        $this->object->setData($testString);
368
        $code3                                 = $this->object->getKod();
369
        $this->assertEquals('FISHCLAMPUCHYTKAPR2', $code3);
370
371
        $this->assertEquals('TEST',
372
            $this->object->getKod([$this->object->nameColumn => 'test']));
373
374
        $this->assertEquals('TEST1', $this->object->getKod('test'));
375
376
        $this->assertEquals('TEST2', $this->object->getKod(['kod' => 'test']));
377
        $this->assertEquals('NOTSET', $this->object->getKod(['kod' => '']));
378
    }
379
380
    /**
381
     * @covers FlexiPeeHP\FlexiBeeRO::logResult
382
     */
383
    public function testLogResult()
384
    {
385
        $this->object->cleanMessages();
386
        $success = json_decode('{"winstrom":{"@version":"1.0","success":"true",'
387
            .'"stats":{"created":"0","updated":"1","deleted":"0","skipped":"0"'
388
            .',"failed":"0"},"results":[{"id":"1","request-id":"ext:SōkoMan.item'
389
            .':5271","ref":"/c/spoje_net_s_r_o_1/skladovy-pohyb/1.json"}]}}');
390
        $this->object->logResult(current($this->object->object2array($success)),
391
            'http://test');
392
393
        $this->assertArrayHasKey('info', $this->object->getStatusMessages(true));
394
395
        $error                          = json_decode('{"winstrom":{"@version":"1.0","success":"false",'
396
            .'"stats":{"created":"0","updated":"0","deleted":"0","skipped":"0"'
397
            .',"failed":"0"},"results":[{"errors":[{"message":"cz.winstrom.'
398
            .'service.WSBusinessException: Zadaný kód není unikátní.\nZadaný'
399
            .' kód není unikátní."}]}]}}');
400
        $this->object->lastResponseCode = 500;
401
        $this->object->logResult(current($this->object->object2array($error)));
402
        $this->assertArrayHasKey('error', $this->object->getStatusMessages(true));
403
    }
404
405
    /**
406
     * @covers FlexiPeeHP\FlexiBeeRO::flexiUrl
407
     */
408
    public function testFlexiUrl()
409
    {
410
        $this->assertEquals("a eq 1 and b eq 'foo'",
411
            $this->object->flexiUrl(['a' => 1, 'b' => 'foo'], 'and'));
412
        $this->assertEquals("a eq 1 or b eq 'bar'",
413
            $this->object->flexiUrl(['a' => 1, 'b' => 'bar'], 'or'));
414
        $this->assertEquals("a eq true or b eq false",
415
            $this->object->flexiUrl(['a' => true, 'b' => false], 'or'));
416
        $this->assertEquals("a is null and b is not null",
417
            $this->object->flexiUrl(['a' => null, 'b' => '!null'], 'and'));
418
    }
419
420
    /**
421
     * @covers FlexiPeeHP\FlexiBeeRO::unifyResponseFormat
422
     */
423
    public function testunifyResponseFormat()
424
    {
425
        $this->assertNull($this->object->unifyResponseFormat(null));
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
426
        //One Row Test
427
        $test1raw = [$this->object->nameSpace =>
428
            [$this->object->getResponseEvidence() =>
429
                ['id' => 1, 'name' => 'value']
430
            ]
431
        ];
432
433
        $test1expected = [$this->object->getResponseEvidence() =>
434
            [
435
                ['id' => 1, 'name' => 'value']
436
            ]
437
        ];
438
439
        $this->assertEquals($test1expected,
440
            $this->object->unifyResponseFormat($test1raw));
441
442
        //Two Row Test
443
        $test2Raw      = [$this->object->nameSpace =>
444
            [$this->object->getResponseEvidence() =>
445
                [
446
                    ['id' => 1, 'name' => 'value'],
447
                    ['id' => 2, 'name' => 'value2']
448
                ]
449
            ]
450
        ];
451
        $test2expected = [$this->object->getResponseEvidence() =>
452
            [
453
                ['id' => 1, 'name' => 'value'],
454
                ['id' => 2, 'name' => 'value2']
455
            ]
456
        ];
457
458
        $this->assertEquals($test2expected,
459
            $this->object->unifyResponseFormat($test2Raw));
460
    }
461
462
    /**
463
     * @covers FlexiPeeHP\FlexiBeeRO::__toString
464
     */
465
    public function testtoString()
466
    {
467
468
        $identifer = 'ext:test:123';
469
        $this->object->setDataValue('id', $identifer);
470
        $this->assertEquals($identifer, (string) $this->object);
471
472
        $code = 'test';
473
        $this->object->setDataValue('kod', $code);
474
        $this->assertEquals('code:'.$code, (string) $this->object);
475
476
        $this->object->dataReset();
477
        $this->assertNull($this->object->__toString());
478
    }
479
480
    /**
481
     * @covers FlexiPeeHP\FlexiBeeRO::draw
482
     */
483
    public function testDraw($whatWant = NULL)
484
    {
485
        $this->object->setDataValue('kod', 'test');
486
        $this->assertEquals('code:test', $this->object->draw());
487
    }
488
489
}
490