Completed
Push — master ( a2b445...923447 )
by Vítězslav
05:20
created

FlexiBeeROTest::testObjectToID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 7
c 1
b 1
f 0
nc 1
nop 0
dl 0
loc 10
rs 9.4285
1
<?php
2
3
namespace Test\FlexiPeeHP;
4
5
use FlexiPeeHP\FlexiBeeRO;
6
7
/**
8
 * Class used to test Object To Array Conversion
9
 */
10
class objTest extends \stdClass
11
{
12
    /**
13
     * Simple Item
14
     * @var integer
15
     */
16
    public $item = 1;
17
18
    /**
19
     * Array item
20
     * @var array
21
     */
22
    public $arrItem = ['a', 'b' => 'c'];
23
24
    /**
25
     * Simple method
26
     * 
27
     * @return boolean
28
     */
29
    public function method()
30
    {
31
        return true;
32
    }
33
}
34
35
/**
36
 * Generated by PHPUnit_SkeletonGenerator on 2016-05-04 at 10:08:36.
37
 */
38
class FlexiBeeROTest extends \Test\Ease\BrickTest
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
39
{
40
    /**
41
     * @var FlexiBeeRO
42
     */
43
    protected $object;
44
45
    /**
46
     * Sets up the fixture, for example, opens a network connection.
47
     * This method is called before a test is executed.
48
     * @covers FlexiPeeHP\FlexiBeeRO::__construct
49
     */
50
    protected function setUp()
51
    {
52
        $this->object            = new FlexiBeeRO();
53
        $this->object->evidence  = 'c';
54
        $this->object->prefix    = '';
55
        $this->object->company   = '';
0 ignored issues
show
Documentation Bug introduced by
It seems like '' of type string is incompatible with the declared type object<FlexiPeeHP\type> of property $company.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
56
        $this->object->nameSpace = 'companies';
57
    }
58
59
    /**
60
     * Tears down the fixture, for example, closes a network connection.
61
     * This method is called after a test is executed.
62
     */
63
    protected function tearDown()
64
    {
65
        
66
    }
67
68
    /**
69
     * @covers FlexiPeeHP\FlexiBeeRO::curlInit
70
     */
71
    public function testCurlInit()
72
    {
73
        $this->object->curlInit();
74
        $this->assertTrue(is_resource($this->object->curl));
75
    }
76
77
    /**
78
     * @covers FlexiPeeHP\FlexiBeeRO::processInit
79
     */
80
    public function testProcessInit()
81
    {
82
        $this->object->processInit(['id' => 1]);
83
        $this->assertEquals(1, $this->object->getDataValue('id'));
84
        if (!is_null($this->object->evidence) && $this->object->evidence != 'test') {
85
            $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...
86
                ['limit' => 1]);
87
            $this->object->processInit((int) current($firstID));
88
            $this->assertNotEmpty((string) $this->object);
89
        }
90
    }
91
92
    /**
93
     * @covers FlexiPeeHP\FlexiBeeRO::setEvidence
94
     */
95
    public function testSetEvidence()
96
    {
97
        $this->object->setEvidence('nastaveni');
98
        $this->assertEquals('nastaveni', $this->object->evidence);
99
    }
100
101
    /**
102
     * @covers FlexiPeeHP\FlexiBeeRO::object2array
103
     */
104
    public function testObject2array()
105
    {
106
        $this->assertNull($this->object->object2array(new \stdClass()));
107
        $this->assertEquals(
108
            [
109
            'item' => 1,
110
            'arrItem' => ['a', 'b' => 'c']
111
            ]
112
            , $this->object->object2array(new objTest()));
113
    }
114
115
    /**
116
     * @covers FlexiPeeHP\FlexiBeeRO::objectToID
117
     */
118
    public function testObjectToID()
119
    {
120
        $id = \Ease\Sand::randomNumber(1, 9999);
121
        $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 120 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...
122
        $this->assertEquals($id, $this->object->objectToID([$this->object]));
123
124
        $this->object->setDataValue('kod', 'TEST');
125
        $this->assertEquals('code:TEST',
126
            $this->object->objectToID($this->object));
127
    }
128
129
    /**
130
     * @covers FlexiPeeHP\FlexiBeeRO::performRequest
131
     */
132
    public function testPerformRequest()
133
    {
134
135
        if (!is_null($this->object->evidence) && $this->object->evidence != 'test') {
136
            $json = $this->object->performRequest($this->object->evidence.'.json');
137
            if (array_key_exists('message', $json)) {
138
                $this->assertArrayHasKey('@version', $json);
139
            } else {
140
                $this->assertArrayHasKey($this->object->evidence, $json);
141
            }
142
        } else {
143
            $this->object->evidence  = 'c';
144
            $this->object->prefix    = '';
145
            $this->object->company   = '';
0 ignored issues
show
Documentation Bug introduced by
It seems like '' of type string is incompatible with the declared type object<FlexiPeeHP\type> of property $company.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
146
            $this->object->nameSpace = 'companies';
147
            $json                    = $this->object->performRequest();
148
            $this->assertArrayHasKey('company', $json);
149
150
            $xml = $this->object->performRequest(null, 'GET', 'xml');
151
            $this->assertArrayHasKey('company', $xml);
152
        }
153
154
        $err = $this->object->performRequest('error.json');
155
        $this->assertArrayHasKey('success', $err);
156
        $this->assertEquals('false', $err['success']);
157
    }
158
159
    /**
160
     * @covers FlexiPeeHP\FlexiBeeRO::getLastInsertedId
161
     * @depends testInsertToFlexiBee
162
     */
163
    public function testGetLastInsertedId()
164
    {
165
        $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\FakturaVydana, 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...
166
    }
167
168
    /**
169
     * @covers FlexiPeeHP\FlexiBeeRO::xml2array
170
     */
171
    public function testXml2array()
172
    {
173
        $xml = '<card xmlns="http://businesscard.org">
174
   <name>John Doe</name>
175
   <title>CEO, Widget Inc.</title>
176
   <email>[email protected]</email>
177
   <phone>(202) 456-1414</phone>
178
   <logo url="widget.gif"/>
179
   <a><b>c</b></a>
180
 </card>';
181
182
        $data = ['name' => 'John Doe', 'title' => 'CEO, Widget Inc.', 'email' => '[email protected]',
183
            'phone' => '(202) 456-1414', 'logo' => '', 'a' => [['b' => 'c']]];
184
185
186
        $this->assertEquals($data, $this->object->xml2array($xml));
187
    }
188
189
    /**
190
     * @covers FlexiPeeHP\FlexiBeeRO::disconnect
191
     *
192
     * @depends testPerformRequest
193
     * @depends testLoadFlexiData
194
     * @depends testGetFlexiRow
195
     * @depends testGetFlexiData
196
     * @depends testLoadFromFlexiBee
197
     * @depends testInsertToFlexiBee
198
     * @depends testIdExists
199
     * @depends testRecordExists
200
     * @depends testGetColumnsFromFlexibee
201
     * @depends testSearchString
202
     */
203
    public function testDisconnect()
204
    {
205
        $this->object->disconnect();
206
        $this->assertNull($this->object->curl);
207
    }
208
209
    /**
210
     * @covers FlexiPeeHP\FlexiBeeRO::__destruct
211
     * @depends testDisconnect
212
     */
213
    public function test__destruct()
214
    {
215
        $this->markTestSkipped();
216
    }
217
218
    /**
219
     * @covers FlexiPeeHP\FlexiBeeRO::loadFlexiData
220
     * @todo   Implement testLoadFlexiData().
221
     */
222
    public function testLoadFlexiData()
223
    {
224
        // Remove the following lines when you implement this test.
225
        $this->markTestIncomplete(
226
            'This test has not been implemented yet.'
227
        );
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
        if (is_null($this->object->evidence) || ($this->object->evidence == 'test')) {
245
            $this->object->evidence  = 'c';
246
            $this->object->prefix    = '';
247
            $this->object->company   = '';
0 ignored issues
show
Documentation Bug introduced by
It seems like '' of type string is incompatible with the declared type object<FlexiPeeHP\type> of property $company.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
248
            $this->object->nameSpace = 'companies';
249
            $flexidata               = $this->object->getFlexiData();
250
            $this->assertArrayHasKey('company', $flexidata);
251 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...
252
            $flexidata = $this->object->getFlexiData();
253
            $this->assertArrayHasKey(0, $flexidata);
254
            $this->assertArrayHasKey('id', $flexidata[0]);
255
            $filtrered = $this->object->getFlexiData(null,
256
                key($flexidata[0])." = ".current($flexidata[0]));
257
            $this->assertArrayHasKey(0, $filtrered);
258
            $this->assertArrayHasKey('id', $filtrered[0]);
259
        }
260
    }
261
262
    /**
263
     * @covers FlexiPeeHP\FlexiBeeRO::loadFromFlexiBee
264
     */
265
    public function testLoadFromFlexiBee()
266
    {
267
        $this->object->loadFromFlexiBee();
268
        $this->object->loadFromFlexiBee(222);
269
    }
270
271
    /**
272
     * @covers FlexiPeeHP\FlexiBeeRO::jsonizeData
273
     */
274
    public function testJsonizeData()
275
    {
276
        $this->assertEquals('{"'.$this->object->nameSpace.'":{"@version":"1.0","'.$this->object->evidence.'":{"key":"value"}}}',
277
            $this->object->jsonizeData(['key' => 'value']));
278
    }
279
280
    /**
281
     * @covers FlexiPeeHP\FlexiBeeRO::idExists
282
     * @todo   Implement testIdExists().
283
     */
284
    public function testIdExists()
285
    {
286
        // Remove the following lines when you implement this test.
287
        $this->markTestIncomplete(
288
            'This test has not been implemented yet.'
289
        );
290
    }
291
292
    /**
293
     * @covers FlexiPeeHP\FlexiBeeRO::recordExists
294
     */
295
    public function testRecordExists()
296
    {
297
//        $this->assertTrue($this->object->recordExists([]));
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
298
//        $this->assertFalse($this->object->recordExists([]));
299
    }
300
301
    /**
302
     * @covers FlexiPeeHP\FlexiBeeRO::getColumnsFromFlexibee
303
     * @todo   Implement testGetColumnsFromFlexibee().
304
     */
305
    public function testGetColumnsFromFlexibee()
306
    {
307
        // Remove the following lines when you implement this test.
308
        $this->markTestIncomplete(
309
            'This test has not been implemented yet.'
310
        );
311
    }
312
313
    /**
314
     * @covers FlexiPeeHP\FlexiBeeRO::getKod
315
     */
316
    public function testGetKod()
317
    {
318
319
        $this->assertEquals('CODE',
320
            $this->object->getKod([$this->object->myKeyColumn => 'code']));
321
322
        $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...
323
            .'(3.5 mm)';
324
        $code0                                 = $this->object->getKod($testString);
325
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code0);
326
        $code1                                 = $this->object->getKod($testString,
327
            false);
328
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code1);
329
        $code2                                 = $this->object->getKod($testString);
330
        $this->assertEquals('FISHCLAMPUCHYTKAPR1', $code2);
331
        $this->object->setData($testString);
332
        $code3                                 = $this->object->getKod();
333
        $this->assertEquals('FISHCLAMPUCHYTKAPR2', $code3);
334
335
        $this->assertEquals('TEST',
336
            $this->object->getKod([$this->object->nameColumn => 'test']));
337
338
        $this->assertEquals('TEST1', $this->object->getKod('test'));
339
340
        $this->assertEquals('TEST2', $this->object->getKod(['kod' => 'test']));
341
        $this->assertEquals('NOTSET', $this->object->getKod(['kod' => '']));
342
    }
343
344
    /**
345
     * @covers FlexiPeeHP\FlexiBeeRO::searchString
346
     * @todo   Implement testSearchString().
347
     */
348
    public function testSearchString()
349
    {
350
        // Remove the following lines when you implement this test.
351
        $this->markTestIncomplete(
352
            'This test has not been implemented yet.'
353
        );
354
    }
355
356
    /**
357
     * @covers FlexiPeeHP\FlexiBeeRO::logResult
358
     */
359
    public function testLogResult()
360
    {
361
        $this->object->cleanMessages();
362
        $success = json_decode('{"winstrom":{"@version":"1.0","success":"true",'
363
            .'"stats":{"created":"0","updated":"1","deleted":"0","skipped":"0"'
364
            .',"failed":"0"},"results":[{"id":"1","request-id":"ext:SōkoMan.item'
365
            .':5271","ref":"/c/spoje_net_s_r_o_1/skladovy-pohyb/1.json"}]}}');
366
        $this->object->logResult(current($this->object->object2array($success)),
367
            'http://test');
368
369
        $this->assertArrayHasKey('info', $this->object->getStatusMessages(true));
370
371
        $error = json_decode('{"winstrom":{"@version":"1.0","success":"false",'
372
            .'"stats":{"created":"0","updated":"0","deleted":"0","skipped":"0"'
373
            .',"failed":"0"},"results":[{"errors":[{"message":"cz.winstrom.'
374
            .'service.WSBusinessException: Zadaný kód není unikátní.\nZadaný'
375
            .' kód není unikátní."}]}]}}');
376
        $this->object->logResult(current($this->object->object2array($error)));
377
        $this->assertArrayHasKey('error', $this->object->getStatusMessages(true));
378
    }
379
380
    /**
381
     * @covers FlexiPeeHP\FlexiBeeRO::flexiUrl
382
     */
383
    public function testFlexiUrl()
384
    {
385
        $this->assertEquals("a eq 1 and b eq 'foo'",
386
            $this->object->flexiUrl(['a' => 1, 'b' => 'foo'], 'and'));
387
        $this->assertEquals("a eq 1 or b eq 'bar'",
388
            $this->object->flexiUrl(['a' => 1, 'b' => 'bar'], 'or'));
389
        $this->assertEquals("a eq true or b eq false",
390
            $this->object->flexiUrl(['a' => true, 'b' => false], 'or'));
391
        $this->assertEquals("a is null and b is not null",
392
            $this->object->flexiUrl(['a' => null, 'b' => '!null'], 'and'));
393
    }
394
395
    /**
396
     * @covers FlexiPeeHP\FlexiBeeRO::__toString
397
     * @expectedException \Exception
398
     */
399
    public function test__toString()
400
    {
401
402
        $identifer = 'ext:test:123';
403
        $this->object->setDataValue('id', $identifer);
404
        $this->assertEquals($identifer, (string) $this->object);
405
406
        $code = 'test';
407
        $this->object->setDataValue('kod', $code);
408
        $this->assertEquals('code:'.$code, (string) $this->object);
409
410
        $this->object->dataReset();
411
        $this->object->__toString();
412
    }
413
414
    /**
415
     * @covers FlexiPeeHP\FlexiBeeRO::draw
416
     */
417
    public function testDraw()
418
    {
419
        $this->object->setDataValue('kod', 'test');
420
        $this->assertEquals('code:test', $this->object->draw());
421
    }
422
}