Completed
Push — master ( 923447...d5d70a )
by Vítězslav
03:36
created

FlexiBeeROTest::testSetAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 7
c 1
b 0
f 1
nc 1
nop 0
dl 0
loc 9
rs 9.6666
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   = '';
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   = '';
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::setAction
161
     */
162
    public function testSetAction()
163
    {
164
        $this->assertTrue($this->object->setAction('none'));
165
        $this->object->actionsAvailable = [];
0 ignored issues
show
Bug introduced by
The property actionsAvailable cannot be accessed from this context as it is declared private in class FlexiPeeHP\FlexiBeeRO.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
166
        $this->assertFalse($this->object->setAction('none'));
167
        $this->object->actionsAvailable = ['copy'];
0 ignored issues
show
Bug introduced by
The property actionsAvailable cannot be accessed from this context as it is declared private in class FlexiPeeHP\FlexiBeeRO.

This check looks for access to properties that are not accessible from the current context.

If you need to make a property accessible to another context you can either raise its visibility level or provide an accessible getter in the defining class.

Loading history...
168
        $this->assertFalse($this->object->setAction('none'));
169
        $this->assertTrue($this->object->setAction('copy'));
170
    }
171
172
    /**
173
     * @covers FlexiPeeHP\FlexiBeeRO::getLastInsertedId
174
     * @depends testInsertToFlexiBee
175
     */
176
    public function testGetLastInsertedId()
177
    {
178
        $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...
179
    }
180
181
    /**
182
     * @covers FlexiPeeHP\FlexiBeeRO::xml2array
183
     */
184
    public function testXml2array()
185
    {
186
        $xml = '<card xmlns="http://businesscard.org">
187
   <name>John Doe</name>
188
   <title>CEO, Widget Inc.</title>
189
   <email>[email protected]</email>
190
   <phone>(202) 456-1414</phone>
191
   <logo url="widget.gif"/>
192
   <a><b>c</b></a>
193
 </card>';
194
195
        $data = ['name' => 'John Doe', 'title' => 'CEO, Widget Inc.', 'email' => '[email protected]',
196
            'phone' => '(202) 456-1414', 'logo' => '', 'a' => [['b' => 'c']]];
197
198
199
        $this->assertEquals($data, $this->object->xml2array($xml));
200
    }
201
202
    /**
203
     * @covers FlexiPeeHP\FlexiBeeRO::disconnect
204
     *
205
     * @depends testPerformRequest
206
     * @depends testLoadFlexiData
207
     * @depends testGetFlexiRow
208
     * @depends testGetFlexiData
209
     * @depends testLoadFromFlexiBee
210
     * @depends testInsertToFlexiBee
211
     * @depends testIdExists
212
     * @depends testRecordExists
213
     * @depends testGetColumnsFromFlexibee
214
     * @depends testSearchString
215
     */
216
    public function testDisconnect()
217
    {
218
        $this->object->disconnect();
219
        $this->assertNull($this->object->curl);
220
    }
221
222
    /**
223
     * @covers FlexiPeeHP\FlexiBeeRO::__destruct
224
     * @depends testDisconnect
225
     */
226
    public function test__destruct()
227
    {
228
        $this->markTestSkipped();
229
    }
230
231
    /**
232
     * @covers FlexiPeeHP\FlexiBeeRO::loadFlexiData
233
     * @todo   Implement testLoadFlexiData().
234
     */
235
    public function testLoadFlexiData()
236
    {
237
        // Remove the following lines when you implement this test.
238
        $this->markTestIncomplete(
239
            'This test has not been implemented yet.'
240
        );
241
    }
242
243
    /**
244
     * @covers FlexiPeeHP\FlexiBeeRO::getFlexiRow
245
     */
246
    public function testGetFlexiRow()
247
    {
248
        $this->object->getFlexiRow(0);
249
        $this->object->getFlexiRow(1);
250
    }
251
252
    /**
253
     * @covers FlexiPeeHP\FlexiBeeRO::getFlexiData
254
     */
255
    public function testGetFlexiData()
256
    {
257
        if (is_null($this->object->evidence) || ($this->object->evidence == 'test')) {
258
            $this->object->evidence  = 'c';
259
            $this->object->prefix    = '';
260
            $this->object->company   = '';
261
            $this->object->nameSpace = 'companies';
262
            $flexidata               = $this->object->getFlexiData();
263
            $this->assertArrayHasKey('company', $flexidata);
264 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...
265
            $flexidata = $this->object->getFlexiData();
266
            $this->assertArrayHasKey(0, $flexidata);
267
            $this->assertArrayHasKey('id', $flexidata[0]);
268
            $filtrered = $this->object->getFlexiData(null,
269
                key($flexidata[0])." = ".current($flexidata[0]));
270
            $this->assertArrayHasKey(0, $filtrered);
271
            $this->assertArrayHasKey('id', $filtrered[0]);
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"}},"companies@action":"copy"}',
293
            $this->object->jsonizeData(['key' => 'value']));
294
    }
295
296
    /**
297
     * @covers FlexiPeeHP\FlexiBeeRO::idExists
298
     * @todo   Implement testIdExists().
299
     */
300
    public function testIdExists()
301
    {
302
        // Remove the following lines when you implement this test.
303
        $this->markTestIncomplete(
304
            'This test has not been implemented yet.'
305
        );
306
    }
307
308
    /**
309
     * @covers FlexiPeeHP\FlexiBeeRO::recordExists
310
     */
311
    public function testRecordExists()
312
    {
313
//        $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...
314
//        $this->assertFalse($this->object->recordExists([]));
315
    }
316
317
    /**
318
     * @covers FlexiPeeHP\FlexiBeeRO::getColumnsFromFlexibee
319
     * @todo   Implement testGetColumnsFromFlexibee().
320
     */
321
    public function testGetColumnsFromFlexibee()
322
    {
323
        // Remove the following lines when you implement this test.
324
        $this->markTestIncomplete(
325
            'This test has not been implemented yet.'
326
        );
327
    }
328
329
    /**
330
     * @covers FlexiPeeHP\FlexiBeeRO::getKod
331
     */
332
    public function testGetKod()
333
    {
334
335
        $this->assertEquals('CODE',
336
            $this->object->getKod([$this->object->myKeyColumn => 'code']));
337
338
        $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...
339
            .'(3.5 mm)';
340
        $code0                                 = $this->object->getKod($testString);
341
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code0);
342
        $code1                                 = $this->object->getKod($testString,
343
            false);
344
        $this->assertEquals('FISHCLAMPUCHYTKAPR', $code1);
345
        $code2                                 = $this->object->getKod($testString);
346
        $this->assertEquals('FISHCLAMPUCHYTKAPR1', $code2);
347
        $this->object->setData($testString);
348
        $code3                                 = $this->object->getKod();
349
        $this->assertEquals('FISHCLAMPUCHYTKAPR2', $code3);
350
351
        $this->assertEquals('TEST',
352
            $this->object->getKod([$this->object->nameColumn => 'test']));
353
354
        $this->assertEquals('TEST1', $this->object->getKod('test'));
355
356
        $this->assertEquals('TEST2', $this->object->getKod(['kod' => 'test']));
357
        $this->assertEquals('NOTSET', $this->object->getKod(['kod' => '']));
358
    }
359
360
    /**
361
     * @covers FlexiPeeHP\FlexiBeeRO::logResult
362
     */
363
    public function testLogResult()
364
    {
365
        $this->object->cleanMessages();
366
        $success = json_decode('{"winstrom":{"@version":"1.0","success":"true",'
367
            .'"stats":{"created":"0","updated":"1","deleted":"0","skipped":"0"'
368
            .',"failed":"0"},"results":[{"id":"1","request-id":"ext:SōkoMan.item'
369
            .':5271","ref":"/c/spoje_net_s_r_o_1/skladovy-pohyb/1.json"}]}}');
370
        $this->object->logResult(current($this->object->object2array($success)),
371
            'http://test');
372
373
        $this->assertArrayHasKey('info', $this->object->getStatusMessages(true));
374
375
        $error = json_decode('{"winstrom":{"@version":"1.0","success":"false",'
376
            .'"stats":{"created":"0","updated":"0","deleted":"0","skipped":"0"'
377
            .',"failed":"0"},"results":[{"errors":[{"message":"cz.winstrom.'
378
            .'service.WSBusinessException: Zadaný kód není unikátní.\nZadaný'
379
            .' kód není unikátní."}]}]}}');
380
        $this->object->logResult(current($this->object->object2array($error)));
381
        $this->assertArrayHasKey('error', $this->object->getStatusMessages(true));
382
    }
383
384
    /**
385
     * @covers FlexiPeeHP\FlexiBeeRO::flexiUrl
386
     */
387
    public function testFlexiUrl()
388
    {
389
        $this->assertEquals("a eq 1 and b eq 'foo'",
390
            $this->object->flexiUrl(['a' => 1, 'b' => 'foo'], 'and'));
391
        $this->assertEquals("a eq 1 or b eq 'bar'",
392
            $this->object->flexiUrl(['a' => 1, 'b' => 'bar'], 'or'));
393
        $this->assertEquals("a eq true or b eq false",
394
            $this->object->flexiUrl(['a' => true, 'b' => false], 'or'));
395
        $this->assertEquals("a is null and b is not null",
396
            $this->object->flexiUrl(['a' => null, 'b' => '!null'], 'and'));
397
    }
398
399
    /**
400
     * @covers FlexiPeeHP\FlexiBeeRO::__toString
401
     * @expectedException \Exception
402
     */
403
    public function test__toString()
404
    {
405
406
        $identifer = 'ext:test:123';
407
        $this->object->setDataValue('id', $identifer);
408
        $this->assertEquals($identifer, (string) $this->object);
409
410
        $code = 'test';
411
        $this->object->setDataValue('kod', $code);
412
        $this->assertEquals('code:'.$code, (string) $this->object);
413
414
        $this->object->dataReset();
415
        $this->object->__toString();
416
    }
417
418
    /**
419
     * @covers FlexiPeeHP\FlexiBeeRO::draw
420
     */
421
    public function testDraw()
422
    {
423
        $this->object->setDataValue('kod', 'test');
424
        $this->assertEquals('code:test', $this->object->draw());
425
    }
426
}