Completed
Push — master ( 72fe28...14dc45 )
by Vítězslav
34:29
created

FlexiBeeROTest::testObject2array()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 1
eloc 6
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 \objTest()));
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
109
        if (!is_null($this->object->evidence) && $this->object->evidence != 'test') {
110
            $json = $this->object->performRequest($this->object->evidence.'.json');
111
            if (array_key_exists('message', $json)) {
112
                $this->assertArrayHasKey('@version', $json);
113
            } else {
114
                $this->assertArrayHasKey('company', $json);
115
            }
116
        } else {
117
            $this->object->evidence  = 'c';
118
            $this->object->prefix    = '';
119
            $this->object->company   = '';
120
            $this->object->nameSpace = 'companies';
121
            $json                    = $this->object->performRequest();
122
            $this->assertArrayHasKey('company', $json);
123
124
            $xml = $this->object->performRequest(null, 'GET', 'xml');
125
            $this->assertArrayHasKey('company', $xml);
126
        }
127
128
        $err = $this->object->performRequest('error.json');
129
        $this->assertArrayHasKey('success', $err);
130
        $this->assertEquals('false', $err['success']);
131
    }
132
133
    /**
134
     * @covers FlexiPeeHP\FlexiBeeRO::setAction
135
     */
136
    public function testSetAction()
137
    {
138
        $this->assertTrue($this->object->setAction('none'));
139
        $this->object->actionsAvailable = [];
140
        $this->assertFalse($this->object->setAction('none'));
141
        $this->object->actionsAvailable = ['copy'];
142
        $this->assertFalse($this->object->setAction('none'));
143
    }
144
145
    /**
146
     * @covers FlexiPeeHP\FlexiBeeRO::getLastInsertedId
147
     * @depends testInsertToFlexiBee
148
     */
149
    public function testGetLastInsertedId()
150
    {
151
        $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...
152
    }
153
154
    /**
155
     * @covers FlexiPeeHP\FlexiBeeRO::xml2array
156
     */
157
    public function testXml2array()
158
    {
159
        $xml = '<card xmlns="http://businesscard.org">
160
   <name>John Doe</name>
161
   <title>CEO, Widget Inc.</title>
162
   <email>[email protected]</email>
163
   <phone>(202) 456-1414</phone>
164
   <logo url="widget.gif"/>
165
   <a><b>c</b></a>
166
 </card>';
167
168
        $data = ['name' => 'John Doe', 'title' => 'CEO, Widget Inc.', 'email' => '[email protected]',
169
            'phone' => '(202) 456-1414', 'logo' => '', 'a' => [['b' => 'c']]];
170
171
172
        $this->assertEquals($data, $this->object->xml2array($xml));
173
    }
174
175
    /**
176
     * @covers FlexiPeeHP\FlexiBeeRO::disconnect
177
     *
178
     * @depends testPerformRequest
179
     * @depends testLoadFlexiData
180
     * @depends testGetFlexiRow
181
     * @depends testGetFlexiData
182
     * @depends testLoadFromFlexiBee
183
     * @depends testInsertToFlexiBee
184
     * @depends testIdExists
185
     * @depends testRecordExists
186
     * @depends testGetColumnsFromFlexibee
187
     * @depends testSearchString
188
     */
189
    public function testDisconnect()
190
    {
191
        $this->object->disconnect();
192
        $this->assertNull($this->object->curl);
193
    }
194
195
    /**
196
     * @covers FlexiPeeHP\FlexiBeeRO::__destruct
197
     * @depends testDisconnect
198
     */
199
    public function test__destruct()
200
    {
201
        $this->markTestSkipped();
202
    }
203
204
    /**
205
     * @covers FlexiPeeHP\FlexiBeeRO::loadFlexiData
206
     * @todo   Implement testLoadFlexiData().
207
     */
208
    public function testLoadFlexiData()
209
    {
210
        // Remove the following lines when you implement this test.
211
        $this->markTestIncomplete(
212
            'This test has not been implemented yet.'
213
        );
214
    }
215
216
    /**
217
     * @covers FlexiPeeHP\FlexiBeeRO::getFlexiRow
218
     */
219
    public function testGetFlexiRow()
220
    {
221
        $this->object->getFlexiRow(0);
222
        $this->object->getFlexiRow(1);
223
    }
224
225
    /**
226
     * @covers FlexiPeeHP\FlexiBeeRO::getFlexiData
227
     */
228
    public function testGetFlexiData()
229
    {
230
        if (is_null($this->object->evidence) || ($this->object->evidence == 'test')
231
            || ($this->object->evidence == 'c')) {
232
            $this->object->evidence  = 'c';
233
            $this->object->prefix    = '';
234
            $this->object->company   = '';
235
            $this->object->nameSpace = 'companies';
236
            $flexidata               = $this->object->getFlexiData();
237
            $this->assertArrayHasKey('company', $flexidata);
238 View Code Duplication
        } else {
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...
239
            $flexidata = $this->object->getFlexiData();
240
            $this->assertArrayHasKey(0, $flexidata);
241
            $this->assertArrayHasKey('id', $flexidata[0]);
242
            $filtrered = $this->object->getFlexiData(null,
243
                key($flexidata[0])." = ".current($flexidata[0]));
244
            $this->assertArrayHasKey(0, $filtrered);
245
            $this->assertArrayHasKey('id', $filtrered[0]);
246
        }
247
    }
248
249
    /**
250
     * @covers FlexiPeeHP\FlexiBeeRO::loadFromFlexiBee
251
     */
252
    public function testLoadFromFlexiBee()
253
    {
254
        $this->object->loadFromFlexiBee();
255
        $this->object->loadFromFlexiBee(222);
256
    }
257
258
    /**
259
     * @covers FlexiPeeHP\FlexiBeeRO::jsonizeData
260
     */
261
    public function testJsonizeData()
262
    {
263
        $this->assertEquals('{"'.$this->object->nameSpace.'":{"@version":"1.0","'.$this->object->evidence.'":{"key":"value"}}}',
264
            $this->object->jsonizeData(['key' => 'value']));
265
        $this->object->setAction('copy');
266
        $this->assertEquals('{"'.$this->object->nameSpace.'":{"@version":"1.0","'.$this->object->evidence.'":{"key":"value"},"'.$this->object->evidence.'@action":"copy"}}',
267
            $this->object->jsonizeData(['key' => 'value']));
268
    }
269
270
    /**
271
     * @covers FlexiPeeHP\FlexiBeeRO::idExists
272
     * @todo   Implement testIdExists().
273
     */
274
    public function testIdExists()
275
    {
276
        // Remove the following lines when you implement this test.
277
        $this->markTestIncomplete(
278
            'This test has not been implemented yet.'
279
        );
280
    }
281
282
    /**
283
     * @covers FlexiPeeHP\FlexiBeeRO::recordExists
284
     */
285
    public function testRecordExists()
286
    {
287
        $evidence = $this->object->getEvidence();
288
        if ($evidence == 'c') {
289
            $this->markTestSkipped('Evidence is c');
290
        }
291
        $flexidata = $this->object->getFlexiData(null, ['limit' => 1]);
292
        $this->object->setData(['id' => (int) $flexidata[$evidence][0]['id']]);
293
        $this->assertTrue($this->object->recordExists());
294
        $this->assertFalse($this->object->recordExists(['unexistent' => 1]));
295
    }
296
297
    /**
298
     * @covers FlexiPeeHP\FlexiBeeRO::getColumnsFromFlexibee
299
     * @todo   Implement testGetColumnsFromFlexibee().
300
     */
301
    public function testGetColumnsFromFlexibee()
302
    {
303
        // Remove the following lines when you implement this test.
304
        $this->markTestIncomplete(
305
            'This test has not been implemented yet.'
306
        );
307
    }
308
309
    /**
310
     * @covers FlexiPeeHP\FlexiBeeRO::getKod
311
     */
312
    public function testGetKod()
313
    {
314
315
        $this->assertEquals('CODE',
316
            $this->object->getKod([$this->object->myKeyColumn => 'code']));
317
318
        $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...
319
            .'(3.5 mm)';
320
        $code0                                 = $this->object->getKod($testString);
321
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code0);
322
        $code1                                 = $this->object->getKod($testString,
323
            false);
324
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code1);
325
        $code2                                 = $this->object->getKod($testString);
326
        $this->assertEquals('FISHCLAMPUCHYTKAPR1', $code2);
327
        $this->object->setData($testString);
328
        $code3                                 = $this->object->getKod();
329
        $this->assertEquals('FISHCLAMPUCHYTKAPR2', $code3);
330
331
        $this->assertEquals('TEST',
332
            $this->object->getKod([$this->object->nameColumn => 'test']));
333
334
        $this->assertEquals('TEST1', $this->object->getKod('test'));
335
336
        $this->assertEquals('TEST2', $this->object->getKod(['kod' => 'test']));
337
        $this->assertEquals('NOTSET', $this->object->getKod(['kod' => '']));
338
    }
339
340
    /**
341
     * @covers FlexiPeeHP\FlexiBeeRO::logResult
342
     */
343
    public function testLogResult()
344
    {
345
        $this->object->cleanMessages();
346
        $success = json_decode('{"winstrom":{"@version":"1.0","success":"true",'
347
            .'"stats":{"created":"0","updated":"1","deleted":"0","skipped":"0"'
348
            .',"failed":"0"},"results":[{"id":"1","request-id":"ext:SōkoMan.item'
349
            .':5271","ref":"/c/spoje_net_s_r_o_1/skladovy-pohyb/1.json"}]}}');
350
        $this->object->logResult(current($this->object->object2array($success)),
351
            'http://test');
352
353
        $this->assertArrayHasKey('info', $this->object->getStatusMessages(true));
354
355
        $error = json_decode('{"winstrom":{"@version":"1.0","success":"false",'
356
            .'"stats":{"created":"0","updated":"0","deleted":"0","skipped":"0"'
357
            .',"failed":"0"},"results":[{"errors":[{"message":"cz.winstrom.'
358
            .'service.WSBusinessException: Zadaný kód není unikátní.\nZadaný'
359
            .' kód není unikátní."}]}]}}');
360
        $this->object->logResult(current($this->object->object2array($error)));
361
        $this->assertArrayHasKey('error', $this->object->getStatusMessages(true));
362
    }
363
364
    /**
365
     * @covers FlexiPeeHP\FlexiBeeRO::flexiUrl
366
     */
367
    public function testFlexiUrl()
368
    {
369
        $this->assertEquals("a eq 1 and b eq 'foo'",
370
            $this->object->flexiUrl(['a' => 1, 'b' => 'foo'], 'and'));
371
        $this->assertEquals("a eq 1 or b eq 'bar'",
372
            $this->object->flexiUrl(['a' => 1, 'b' => 'bar'], 'or'));
373
        $this->assertEquals("a eq true or b eq false",
374
            $this->object->flexiUrl(['a' => true, 'b' => false], 'or'));
375
        $this->assertEquals("a is null and b is not null",
376
            $this->object->flexiUrl(['a' => null, 'b' => '!null'], 'and'));
377
    }
378
379
    /**
380
     * @covers FlexiPeeHP\FlexiBeeRO::__toString
381
     * @expectedException \Exception
382
     */
383
    public function test__toString()
384
    {
385
386
        $identifer = 'ext:test:123';
387
        $this->object->setDataValue('id', $identifer);
388
        $this->assertEquals($identifer, (string) $this->object);
389
390
        $code = 'test';
391
        $this->object->setDataValue('kod', $code);
392
        $this->assertEquals('code:'.$code, (string) $this->object);
393
394
        $this->object->dataReset();
395
        $this->object->__toString();
396
    }
397
398
    /**
399
     * @covers FlexiPeeHP\FlexiBeeRO::draw
400
     */
401
    public function testDraw($whatWant = NULL)
0 ignored issues
show
Unused Code introduced by
The parameter $whatWant is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
402
    {
403
        $this->object->setDataValue('kod', 'test');
404
        $this->assertEquals('code:test', $this->object->draw());
405
    }
406
407
}
408