GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 65564e...78887b )
by Jonny
03:37
created

testCanLoadCookiesFromPersistentCookieFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the php-phantomjs.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
namespace JonnyW\PhantomJs\Tests\Integration;
10
11
use JonnyW\PhantomJs\Test\TestCase;
12
use JonnyW\PhantomJs\Client;
13
use JonnyW\PhantomJs\DependencyInjection\ServiceContainer;
14
15
/**
16
 * PHP PhantomJs
17
 *
18
 * @author Jon Wenmoth <[email protected]>
19
 */
20
class ClientTest extends TestCase
21
{
22
    /**
23
     * Test filename
24
     *
25
     * @var string
26
     * @access protected
27
     */
28
    protected $filename;
29
30
    /**
31
     * Test directory
32
     *
33
     * @var string
34
     * @access protected
35
     */
36
    protected $directory;
37
38
/** +++++++++++++++++++++++++++++++++++ **/
39
/** ++++++++++++++ TESTS ++++++++++++++ **/
40
/** +++++++++++++++++++++++++++++++++++ **/
41
42
    /**
43
     * Test additional procedures can be loaded
44
     * through chain loader.
45
     *
46
     * @access public
47
     * @return void
48
     */
49
    public function testAdditionalProceduresCanBeLoadedThroughChainLoader()
50
    {
51
        $content = 'TEST_PROCEDURE';
52
53
        $procedure = <<<EOF
54
    console.log(JSON.stringify({"content": "$content"}, undefined, 4));
55
    phantom.exit(1);
56
EOF;
57
58
        $this->writeProcedure($procedure);
59
60
        $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory');
61
        $procedureLoader        = $procedureLoaderFactory->createProcedureLoader($this->directory);
62
63
        $client = $this->getClient();
64
        $client->setProcedure('test');
65
        $client->getProcedureLoader()->addLoader($procedureLoader);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JonnyW\PhantomJs\Procedu...rocedureLoaderInterface as the method addLoader() does only exist in the following implementations of said interface: JonnyW\PhantomJs\Procedure\ChainProcedureLoader.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
66
67
        $request  = $client->getMessageFactory()->createRequest();
68
        $response = $client->getMessageFactory()->createResponse();
69
70
        $client->send($request, $response);
71
72
        $this->assertSame($content, $response->getContent());
73
    }
74
75
    /**
76
     * Test additional procedures can be loaded
77
     * through chain loader if procedures
78
     * contain comments
79
     *
80
     * @access public
81
     * @return void
82
     */
83
    public function testAdditionalProceduresCanBeLoadedThroughChainLoaderIfProceduresContainComments()
84
    {
85
        $content = 'TEST_PROCEDURE';
86
87
        $procedure = <<<EOF
88
    console.log(JSON.stringify({"content": "$content"}, undefined, 4));
89
    phantom.exit(1);
90
    var test = function () {
91
        // Test comment
92
        console.log('test');
93
    };
94
EOF;
95
96
        $this->writeProcedure($procedure);
97
98
        $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory');
99
        $procedureLoader        = $procedureLoaderFactory->createProcedureLoader($this->directory);
100
101
        $client = $this->getClient();
102
        $client->setProcedure('test');
103
        $client->getProcedureLoader()->addLoader($procedureLoader);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JonnyW\PhantomJs\Procedu...rocedureLoaderInterface as the method addLoader() does only exist in the following implementations of said interface: JonnyW\PhantomJs\Procedure\ChainProcedureLoader.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
104
105
        $request  = $client->getMessageFactory()->createRequest();
106
        $response = $client->getMessageFactory()->createResponse();
107
108
        $client->send($request, $response);
109
110
        $this->assertSame($content, $response->getContent());
111
    }
112
113
    /**
114
     * Test syntax exception is thrown if request
115
     * procedure contains syntax error.
116
     *
117
     * @access public
118
     * @return void
119
     */
120
    public function testSyntaxExceptionIsThrownIfRequestProcedureContainsSyntaxError()
121
    {
122
        $this->setExpectedException('\JonnyW\PhantomJs\Exception\SyntaxException');
123
124
        $content = 'TEST_PROCEDURE';
0 ignored issues
show
Unused Code introduced by
$content is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
125
126
        $procedure = <<<EOF
127
    console.log(;
128
EOF;
129
130
        $this->writeProcedure($procedure);
131
132
        $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory');
133
        $procedureLoader        = $procedureLoaderFactory->createProcedureLoader($this->directory);
134
135
        $client = $this->getClient();
136
        $client->setProcedure('test');
137
        $client->getProcedureLoader()->addLoader($procedureLoader);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JonnyW\PhantomJs\Procedu...rocedureLoaderInterface as the method addLoader() does only exist in the following implementations of said interface: JonnyW\PhantomJs\Procedure\ChainProcedureLoader.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
138
139
        $request  = $client->getMessageFactory()->createRequest();
140
        $response = $client->getMessageFactory()->createResponse();
141
142
        $client->send($request, $response);
143
    }
144
145
    /**
146
     * Test response contains 200 status code if page
147
     * is successfully loaded.
148
     *
149
     * @access public
150
     * @return void
151
     */
152
    public function testResponseContains200StatusCodeIfPageIsSuccessfullyLoaded()
153
    {
154
        $client = $this->getClient();
155
156
        $request  = $client->getMessageFactory()->createRequest();
157
        $response = $client->getMessageFactory()->createResponse();
158
159
        $request->setMethod('GET');
160
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
161
162
        $client->send($request, $response);
163
164
        $this->assertEquals(200, $response->getStatus());
165
    }
166
167
    /**
168
     * Test response contains 200 status code if
169
     * request URL contains reserved characters.
170
     *
171
     * @access public
172
     * @return void
173
     */
174
    public function testResponseContains200StatusCodeIfRequestUrlContainsReservedCharacters()
175
    {
176
        $client = $this->getClient();
177
178
        $request  = $client->getMessageFactory()->createRequest();
179
        $response = $client->getMessageFactory()->createResponse();
180
181
        $request->setMethod('GET');
182
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
183
        $request->setRequestData(array(
184
            'test1' => 'http://test.com',
185
            'test2' => 'A string with an \' ) / # some other invalid [ characters.'
186
        ));
187
188
        $client->send($request, $response);
189
190
        $this->assertEquals(200, $response->getStatus());
191
    }
192
193
    /**
194
     * Test response contains valid body if page is
195
     * successfully loaded.
196
     *
197
     * @access public
198
     * @return void
199
     */
200
    public function testResponseContainsValidBodyIfPageIsSuccessfullyLoaded()
201
    {
202
        $client = $this->getClient();
203
204
        $request  = $client->getMessageFactory()->createRequest();
205
        $response = $client->getMessageFactory()->createResponse();
206
207
        $request->setMethod('GET');
208
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
209
210
        $client->send($request, $response);
211
212
        $this->assertContains('PHANTOMJS_DEFAULT_TEST', $response->getContent());
213
    }
214
215
    /**
216
     * Test can set user agent in settings
217
     *
218
     * @access public
219
     * @return void
220
     */
221
    public function testCanSetUserAgentInSettings()
222
    {
223
        $client = $this->getClient();
224
225
        $request  = $client->getMessageFactory()->createRequest();
226
        $response = $client->getMessageFactory()->createResponse();
227
228
        $request->setMethod('GET');
229
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
230
        $request->addSetting('userAgent', 'PhantomJS TEST');
231
232
        $client->send($request, $response);
233
234
        $this->assertContains('userAgent=PhantomJS TEST', $response->getContent());
235
    }
236
237
    /**
238
     * Test can add cookies to request
239
     *
240
     * @access public
241
     * @return void
242
     */
243
    public function testCanAddCookiesToRequest()
244
    {
245
        $client = $this->getClient();
246
247
        $request  = $client->getMessageFactory()->createRequest();
248
        $response = $client->getMessageFactory()->createResponse();
249
250
        $request->setMethod('GET');
251
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
252
        $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi');
253
254
        $client->send($request, $response);
255
256
        $this->assertContains('cookie_test_cookie=TESTING_COOKIES', $response->getContent());
257
    }
258
259
    /**
260
     * Test can load cookies from
261
     * persistent cookie file
262
     *
263
     * @access public
264
     * @return void
265
     */
266
    public function testCanLoadCookiesFromPersistentCookieFile()
267
    {
268
        $this->filename = 'cookies.txt';
269
        $file = ($this->directory . '/' . $this->filename);
270
271
        $client = $this->getClient();
272
        $client->getEngine()->addOption('--cookies-file=' . $file);
273
274
        $request  = $client->getMessageFactory()->createRequest();
275
        $response = $client->getMessageFactory()->createResponse();
276
277
        $request->setMethod('GET');
278
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
279
        $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000));
280
281
        $client->send($request, $response);
282
283
        $this->assertContains('test_cookie=TESTING_COOKIES; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file));
284
    }
285
286
    /**
287
     * Test can delete cookie from
288
     * persistent cookie file
289
     *
290
     * @access public
291
     * @return void
292
     */
293
    public function testCanDeleteCookieFromPersistentCookieFile()
294
    {
295
        $this->filename = 'cookies.txt';
296
        $file = ($this->directory . '/' . $this->filename);
297
298
        $client = $this->getClient();
299
        $client->getEngine()->addOption('--cookies-file=' . $file);
300
301
        $request  = $client->getMessageFactory()->createRequest();
302
        $response = $client->getMessageFactory()->createResponse();
303
304
        $request->setMethod('GET');
305
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
306
        $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000));
307
308
        $client->send($request, $response);
309
310
        $request = $client->getMessageFactory()->createRequest();
311
        $request->setMethod('GET');
312
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
313
        $request->deleteCookie('test_cookie');
314
315
        $client->send($request, $response);
316
317
        $this->assertNotContains('test_cookie=TESTING_COOKIES; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file));
318
    }
319
320
    /**
321
     * Test can delete all cookies from
322
     * persistent cookie file
323
     *
324
     * @access public
325
     * @return void
326
     */
327
    public function testCanDeleteAllCookiesFromPersistentCookieFile()
328
    {
329
        $this->filename = 'cookies.txt';
330
        $file = ($this->directory . '/' . $this->filename);
331
332
        $client = $this->getClient();
333
        $client->getEngine()->addOption('--cookies-file=' . $file);
334
335
        $request  = $client->getMessageFactory()->createRequest();
336
        $response = $client->getMessageFactory()->createResponse();
337
338
        $request->setMethod('GET');
339
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
340
        $request->addCookie('test_cookie_1', 'TESTING_COOKIES_1', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000));
341
        $request->addCookie('test_cookie_2', 'TESTING_COOKIES_2', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000));
342
343
        $client->send($request, $response);
344
345
        $request = $client->getMessageFactory()->createRequest();
346
        $request->setMethod('GET');
347
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
348
        $request->deleteCookie('*');
349
350
        $client->send($request, $response);
351
352
        $this->assertNotContains('test_cookie_1=TESTING_COOKIES_1; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file));
353
        $this->assertNotContains('test_cookie_2=TESTING_COOKIES_2; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file));
354
    }
355
356
    /**
357
     * Test response contains console error if a
358
     * javascript error exists on the page.
359
     *
360
     * @access public
361
     * @return void
362
     */
363
    public function testResponseContainsConsoleErrorIfAJavascriptErrorExistsOnThePage()
364
    {
365
        $client = $this->getClient();
366
367
        $request  = $client->getMessageFactory()->createRequest();
368
        $response = $client->getMessageFactory()->createResponse();
369
370
        $request->setMethod('GET');
371
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php');
372
373
        $client->send($request, $response);
374
375
        $console = $response->getConsole();
376
377
        $this->assertCount(1, $console);
378
        $this->assertContains('ReferenceError: Can\'t find variable: invalid', $console[0]['message']);
379
    }
380
381
    /**
382
     * Test response contains console trace if a
383
     * javascript error exists on the page.
384
     *
385
     * @access public
386
     * @return void
387
     */
388
    public function testResponseContainsConsoleTraceIfAJavascriptErrorExistsOnThePage()
389
    {
390
        $client = $this->getClient();
391
392
        $request  = $client->getMessageFactory()->createRequest();
393
        $response = $client->getMessageFactory()->createResponse();
394
395
        $request->setMethod('GET');
396
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php');
397
398
        $client->send($request, $response);
399
400
        $console = $response->getConsole();
401
402
        $this->assertCount(1, $console[0]['trace']);
403
    }
404
405
    /**
406
     * Test response contains headers.
407
     *
408
     * @access public
409
     * @return void
410
     */
411
    public function testResponseContainsHeaders()
412
    {
413
        $client = $this->getClient();
414
415
        $request  = $client->getMessageFactory()->createRequest();
416
        $response = $client->getMessageFactory()->createResponse();
417
418
        $request->setMethod('GET');
419
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php');
420
421
        $client->send($request, $response);
422
423
        $this->assertNotEmpty($response->getHeaders());
424
    }
425
426
    /**
427
     * Test redirect URL is set in response
428
     * if request is redirected.
429
     *
430
     * @access public
431
     * @return void
432
     */
433
    public function testRedirectUrlIsSetInResponseIfRequestIsRedirected()
434
    {
435
        $client = $this->getClient();
436
437
        $request  = $client->getMessageFactory()->createRequest();
438
        $response = $client->getMessageFactory()->createResponse();
439
440
        $request->setMethod('GET');
441
        $request->setUrl('https://jigsaw.w3.org/HTTP/300/302.html');
442
443
        $client->send($request, $response);
444
445
        $this->assertNotEmpty($response->getRedirectUrl());
446
    }
447
448
    /**
449
     * Test POST request sends request data.
450
     *
451
     * @access public
452
     * @return void
453
     */
454
    public function testPostRequestSendsRequestData()
455
    {
456
        $client = $this->getClient();
457
458
        $request  = $client->getMessageFactory()->createRequest();
459
        $response = $client->getMessageFactory()->createResponse();
460
461
        $request->setMethod('POST');
462
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-post.php');
463
        $request->setRequestData(array(
464
            'test1' => 'http://test.com',
465
            'test2' => 'A string with an \' ) / # some other invalid [ characters.'
466
        ));
467
468
        $client->send($request, $response);
469
470
        $this->assertContains(sprintf('<li>test1=%s</li>', 'http://test.com'), $response->getContent());
471
        $this->assertContains(sprintf('<li>test2=%s</li>', 'A string with an \' ) / # some other invalid [ characters.'), $response->getContent());
472
    }
473
474
    /**
475
     * Test capture request saves file to
476
     * to local disk.
477
     *
478
     * @access public
479
     * @return void
480
     */
481
    public function testCaptureRequestSavesFileToLocalDisk()
482
    {
483
        $this->filename = 'test.jpg';
484
        $file = ($this->directory . '/' . $this->filename);
485
486
        $client = $this->getClient();
487
488
        $request  = $client->getMessageFactory()->createCaptureRequest();
489
        $response = $client->getMessageFactory()->createResponse();
490
491
        $request->setMethod('GET');
492
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
493
        $request->setOutputFile($file);
494
495
        $client->send($request, $response);
496
497
        $this->assertTrue(file_exists($file));
498
    }
499
500
    /**
501
     * Test capture request saves file to
502
     * disk with correct capture dimensions.
503
     *
504
     * @access public
505
     * @return void
506
     */
507
    public function testCaptureRequestSavesFileToDiskWithCorrectCaptureDimensions()
508
    {
509
        $this->filename = 'test.jpg';
510
        $file = ($this->directory . '/' . $this->filename);
511
512
        $width  = 200;
513
        $height = 400;
514
515
        $client = $this->getClient();
516
517
        $request  = $client->getMessageFactory()->createCaptureRequest();
518
        $response = $client->getMessageFactory()->createResponse();
519
520
        $request->setMethod('GET');
521
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
522
        $request->setOutputFile($file);
523
        $request->setCaptureDimensions($width, $height);
524
525
        $client->send($request, $response);
526
527
        $imageInfo = getimagesize($file);
528
529
        $this->assertEquals($width, $imageInfo[0]);
530
        $this->assertEquals($height, $imageInfo[1]);
531
    }
532
533
    /**
534
     * Test PDF request saves pdf to
535
     * to local disk.
536
     *
537
     * @access public
538
     * @return void
539
     */
540
    public function testPdfRequestSavesPdfToLocalDisk()
541
    {
542
        $this->filename = 'test.pdf';
543
        $file = ($this->directory . '/' . $this->filename);
544
545
        $client = $this->getClient();
546
547
        $request  = $client->getMessageFactory()->createPdfRequest();
548
        $response = $client->getMessageFactory()->createResponse();
549
550
        $request->setMethod('GET');
551
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
552
        $request->setOutputFile($file);
553
554
        $client->send($request, $response);
555
556
        $this->assertTrue(file_exists($file));
557
    }
558
559
    /**
560
     * Test PDF request saves file to
561
     * disk with correct paper size.
562
     *
563
     * @access public
564
     * @return void
565
     */
566
    public function testPdfRequestSavesFileToDiskWithCorrectPaperSize()
567
    {
568
        $this->filename = 'test.pdf';
569
        $file = ($this->directory . '/' . $this->filename);
570
571
        $width  = 20;
572
        $height = 30;
573
574
        $client = $this->getClient();
575
576
        $request  = $client->getMessageFactory()->createPdfRequest();
577
        $response = $client->getMessageFactory()->createResponse();
578
579
        $request->setMethod('GET');
580
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
581
        $request->setOutputFile($file);
582
        $request->setPaperSize(sprintf('%scm', $width), sprintf('%scm', $height));
583
        $request->setMargin('0cm');
584
585
        $client->send($request, $response);
586
587
        $pdf = \ZendPdf\PdfDocument::load($file);
588
589
        $pdfWidth  = round(($pdf->pages[0]->getWidth() * 0.0352777778));
590
        $pdfHeight = round(($pdf->pages[0]->getHeight()  * 0.0352777778));
591
592
        $this->assertEquals($width, $pdfWidth);
593
        $this->assertEquals($height, $pdfHeight);
594
    }
595
596
    /**
597
     * Test PDF request saves file to
598
     * disk with correct format size.
599
     *
600
     * @access public
601
     * @return void
602
     */
603
    public function testPdfRequestSavesFileToDiskWithCorrectFormatSize()
604
    {
605
        $this->filename = 'test.pdf';
606
        $file = ($this->directory . '/' . $this->filename);
607
608
        $client = $this->getClient();
609
610
        $request  = $client->getMessageFactory()->createPdfRequest();
611
        $response = $client->getMessageFactory()->createResponse();
612
613
        $request->setMethod('GET');
614
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
615
        $request->setOutputFile($file);
616
        $request->setFormat('A4');
617
        $request->setMargin('0cm');
618
619
        $client->send($request, $response);
620
621
        $pdf = \ZendPdf\PdfDocument::load($file);
622
623
        $pdfWidth  = round(($pdf->pages[0]->getWidth() * 0.0352777778));
624
        $pdfHeight = round(($pdf->pages[0]->getHeight()  * 0.0352777778));
625
626
        $this->assertEquals(21, $pdfWidth);
627
        $this->assertEquals(30, $pdfHeight);
628
    }
629
630
    /**
631
     * Test PDF request saves file to
632
     * disk with correct orientation.
633
     *
634
     * @access public
635
     * @return void
636
     */
637
    public function testPdfRequestSavesFileToDiskWithCorrectOrientation()
638
    {
639
        $this->filename = 'test.pdf';
640
        $file = ($this->directory . '/' . $this->filename);
641
642
        $client = $this->getClient();
643
644
        $request  = $client->getMessageFactory()->createPdfRequest();
645
        $response = $client->getMessageFactory()->createResponse();
646
647
        $request->setMethod('GET');
648
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
649
        $request->setOutputFile($file);
650
        $request->setFormat('A4');
651
        $request->setOrientation('landscape');
652
        $request->setMargin('0cm');
653
654
        $client->send($request, $response);
655
656
        $pdf = \ZendPdf\PdfDocument::load($file);
657
658
        $pdfWidth  = round(($pdf->pages[0]->getWidth() * 0.0352777778));
659
        $pdfHeight = round(($pdf->pages[0]->getHeight()  * 0.0352777778));
660
661
        $this->assertEquals(30, $pdfWidth);
662
        $this->assertEquals(21, $pdfHeight);
663
    }
664
665
    /**
666
     * Test can set repeating header
667
     * for PDF request
668
     *
669
     * @access public
670
     * @return void
671
     */
672
    public function testCanSetRepeatingHeaderForPDFRequest()
673
    {
674
        $this->filename = 'test.pdf';
675
        $file = ($this->directory . '/' . $this->filename);
676
677
        $client = $this->getClient();
678
679
        $request  = $client->getMessageFactory()->createPdfRequest();
680
        $response = $client->getMessageFactory()->createResponse();
681
682
        $request->setMethod('GET');
683
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
684
        $request->setOutputFile($file);
685
        $request->setFormat('A4');
686
        $request->setOrientation('landscape');
687
        $request->setMargin('0cm');
688
        $request->setRepeatingHeader('<h1>Header <span style="float:right">%pageNum% / %pageTotal%</span></h1>', '2cm');
689
        $request->setRepeatingFooter('<footer>Footer <span style="float:right">%pageNum% / %pageTotal%</span></footer>', '2cm');
690
691
        $client->send($request, $response);
692
693
        $parser = new \Smalot\PdfParser\Parser();
694
        $pdf    = $parser->parseFile($file);
695
696
        $text = str_replace(' ', '', $pdf->getText());
697
698
        $this->assertContains('Header', $text);
699
    }
700
701
    /**
702
     * Test can set repeating footer
703
     * for PDF request
704
     *
705
     * @access public
706
     * @return void
707
     */
708
    public function testCanSetRepeatingFooterForPDFRequest()
709
    {
710
        $this->filename = 'test.pdf';
711
        $file = ($this->directory . '/' . $this->filename);
712
713
        $client = $this->getClient();
714
715
        $request  = $client->getMessageFactory()->createPdfRequest();
716
        $response = $client->getMessageFactory()->createResponse();
717
718
        $request->setMethod('GET');
719
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
720
        $request->setOutputFile($file);
721
        $request->setFormat('A4');
722
        $request->setOrientation('landscape');
723
        $request->setMargin('0cm');
724
        $request->setRepeatingHeader('<h1>Header <span style="float:right">%pageNum% / %pageTotal%</span></h1>', '2cm');
725
        $request->setRepeatingFooter('<footer>Footer <span style="float:right">%pageNum% / %pageTotal%</span></footer>', '2cm');
726
727
        $client->send($request, $response);
728
729
        $parser = new \Smalot\PdfParser\Parser();
730
        $pdf    = $parser->parseFile($file);
731
732
        $text = str_replace(' ', '', $pdf->getText());
733
734
        $this->assertContains('Footer', $text);
735
    }
736
737
    /**
738
     * Test set viewport size sets
739
     * size of viewport in default
740
     * request.
741
     *
742
     * @access public
743
     * @return void
744
     */
745
    public function testSetViewportSizeSetsSizeOfViewportInDefaultRequest()
746
    {
747
        $width  = 100;
748
        $height = 200;
749
750
        $client = $this->getClient();
751
752
        $request  = $client->getMessageFactory()->createRequest();
753
        $response = $client->getMessageFactory()->createResponse();
754
755
        $request->setMethod('GET');
756
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
757
        $request->setViewportsize($width, $height);
758
759
        $client->send($request, $response);
760
761
        $logs = explode("\n", $client->getLog());
762
763
        $startIndex = $this->getLogEntryIndex($logs, 'Set viewport size ~ width: 100 height: 200');
764
765
        $this->assertTrue(($startIndex !== false));
766
    }
767
768
    /**
769
     * Test set viewport size sets
770
     * size of viewport in capture
771
     * request.
772
     *
773
     * @access public
774
     * @return void
775
     */
776
    public function testSetViewportSizeSetsSizeOfViewportInCaptureRequest()
777
    {
778
        $width  = 100;
779
        $height = 200;
780
781
        $client = $this->getClient();
782
783
        $request  = $client->getMessageFactory()->createCaptureRequest();
784
        $response = $client->getMessageFactory()->createResponse();
785
786
        $request->setMethod('GET');
787
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
788
        $request->setViewportsize($width, $height);
789
790
        $client->send($request, $response);
791
792
        $logs = explode("\n", $client->getLog());
793
794
        $startIndex = $this->getLogEntryIndex($logs, 'Set viewport size ~ width: 100 height: 200');
795
796
        $this->assertTrue(($startIndex !== false));
797
    }
798
799
    /**
800
     * Test delay logs start time
801
     * in client for default request.
802
     *
803
     * @access public
804
     * @return void
805
     */
806
    public function testDelayLogsStartTimeInClientForDefaultRequest()
807
    {
808
        $delay = 1;
809
810
        $client = $this->getClient();
811
812
        $request  = $client->getMessageFactory()->createRequest();
813
        $response = $client->getMessageFactory()->createResponse();
814
815
        $request->setMethod('GET');
816
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
817
        $request->setDelay($delay);
818
819
        $client->send($request, $response);
820
821
        $logs = explode("\n", $client->getLog());
822
823
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
824
825
        $this->assertTrue(($startIndex !== false));
826
    }
827
828
    /**
829
     * Test delay logs end time
830
     * in client for default request.
831
     *
832
     * @access public
833
     * @return void
834
     */
835
    public function testDelayLogsEndTimeInClientForDefaultRequest()
836
    {
837
        $delay = 1;
838
839
        $client = $this->getClient();
840
841
        $request  = $client->getMessageFactory()->createRequest();
842
        $response = $client->getMessageFactory()->createResponse();
843
844
        $request->setMethod('GET');
845
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
846
        $request->setDelay($delay);
847
848
        $client->send($request, $response);
849
850
        $logs = explode("\n", $client->getLog());
851
852
        $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after');
853
854
        $this->assertTrue(($endIndex !== false));
855
    }
856
857
    /**
858
     * Test delay delays page render for
859
     * specified time for default request.
860
     *
861
     * @access public
862
     * @return void
863
     */
864
    public function testDelayDelaysPageRenderForSpecifiedTimeForDefaultRequest()
865
    {
866
        $delay = 1;
867
868
        $client = $this->getClient();
869
870
        $request  = $client->getMessageFactory()->createRequest();
871
        $response = $client->getMessageFactory()->createResponse();
872
873
        $request->setMethod('GET');
874
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
875
        $request->setDelay($delay);
876
877
        $client->send($request, $response);
878
879
        $logs = explode("\\n", $client->getLog());
880
881
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
882
        $endIndex   = $this->getLogEntryIndex($logs, 'Rendering page after');
883
884
        $startTime = strtotime(substr($logs[$startIndex], 0 , 19));
885
        $endTime   = strtotime(substr($logs[$endIndex], 0 , 19));
886
887
        $this->assertSame(($startTime+$delay), $endTime);
888
    }
889
890
    /**
891
     * Test delay logs start time
892
     * in client for capture request.
893
     *
894
     * @access public
895
     * @return void
896
     */
897
    public function testDelayLogsStartTimeInClientForCaptureRequest()
898
    {
899
        $delay = 1;
900
901
        $client = $this->getClient();
902
903
        $request  = $client->getMessageFactory()->createCaptureRequest();
904
        $response = $client->getMessageFactory()->createResponse();
905
906
        $request->setMethod('GET');
907
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
908
        $request->setDelay($delay);
909
910
        $client->send($request, $response);
911
912
        $logs = explode("\\n", $client->getLog());
913
914
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
915
916
        $this->assertTrue(($startIndex !== false));
917
    }
918
919
    /**
920
     * Test delay logs end time
921
     * in client for capture request.
922
     *
923
     * @access public
924
     * @return void
925
     */
926
    public function testDelayLogsEndTimeInClientForCaptureRequest()
927
    {
928
        $delay = 1;
929
930
        $client = $this->getClient();
931
932
        $request  = $client->getMessageFactory()->createCaptureRequest();
933
        $response = $client->getMessageFactory()->createResponse();
934
935
        $request->setMethod('GET');
936
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
937
        $request->setDelay($delay);
938
939
        $client->send($request, $response);
940
941
        $logs = explode("\\n", $client->getLog());
942
943
        $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after');
944
945
        $this->assertTrue(($endIndex !== false));
946
    }
947
948
    /**
949
     * Test delay delays page render for
950
     * specified time for capture request.
951
     *
952
     * @access public
953
     * @return void
954
     */
955
    public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest()
956
    {
957
        $delay = 1;
958
959
        $client = $this->getClient();
960
961
        $request  = $client->getMessageFactory()->createCaptureRequest();
962
        $response = $client->getMessageFactory()->createResponse();
963
964
        $request->setMethod('GET');
965
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
966
        $request->setDelay($delay);
967
968
        $client->send($request, $response);
969
970
        $logs = explode("\\n", $client->getLog());
971
972
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
973
        $endIndex   = $this->getLogEntryIndex($logs, 'Rendering page after');
974
975
        $startTime = strtotime(substr($logs[$startIndex], 0 , 19));
976
        $endTime   = strtotime(substr($logs[$endIndex], 0 , 19));
977
978
        $this->assertSame(($startTime+$delay), $endTime);
979
    }
980
981
    /**
982
     * Test lazy request returns content after
983
     * all resources are loaded
984
     *
985
     * @access public
986
     * @return void
987
     */
988
    public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded()
989
    {
990
        $client = $this->getClient();
991
        $client->isLazy();
992
993
        $request  = $client->getMessageFactory()->createRequest();
994
        $response = $client->getMessageFactory()->createResponse();
995
996
        $request->setMethod('GET');
997
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php');
998
        $request->setTimeout(5000);
999
1000
        $client->send($request, $response);
1001
1002
        $this->assertContains('<p id="content">loaded</p>', $response->getContent());
1003
    }
1004
1005
    /**
1006
     * Test content is returned for lazy request
1007
     * if timeout is reached before resource is
1008
     * loaded
1009
     *
1010
     * @access public
1011
     * @return void
1012
     */
1013
    public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResourceIsLoaded()
1014
    {
1015
        $client = $this->getClient();
1016
        $client->isLazy();
1017
1018
        $request  = $client->getMessageFactory()->createRequest();
1019
        $response = $client->getMessageFactory()->createResponse();
1020
1021
        $request->setMethod('GET');
1022
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php');
1023
        $request->setTimeout(1000);
1024
1025
        $client->send($request, $response);
1026
1027
        $this->assertContains('<p id="content"></p>', $response->getContent());
1028
    }
1029
1030
    /**
1031
     * Test debug logs debug info to
1032
     * client log.
1033
     *
1034
     * @access public
1035
     * @return void
1036
     */
1037
    public function testDebugLogsDebugInfoToClientLog()
1038
    {
1039
        $client = $this->getClient();
1040
        $client->getEngine()->debug(true);
1041
1042
        $request  = $client->getMessageFactory()->createRequest();
1043
        $response = $client->getMessageFactory()->createResponse();
1044
1045
        $request->setMethod('GET');
1046
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
1047
1048
        $client->send($request, $response);
1049
1050
        $this->assertContains('[DEBUG]', $client->getLog());
1051
    }
1052
1053
    /**
1054
     * Test test can set page
1055
     * background color
1056
     *
1057
     * @access public
1058
     * @return void
1059
     */
1060
    public function testCanSetPageBackgroundColor()
1061
    {
1062
        $this->filename = 'test.jpg';
1063
        $file = ($this->directory . '/' . $this->filename);
1064
1065
        $client = $this->getClient();
1066
1067
        $request  = $client->getMessageFactory()->createCaptureRequest();
1068
        $response = $client->getMessageFactory()->createResponse();
1069
1070
        $request->setMethod('GET');
1071
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
1072
        $request->setBodyStyles(array('backgroundColor' => 'red'));
1073
        $request->setOutputFile($file);
1074
1075
        $client->send($request, $response);
1076
1077
        $this->assertContains('body style="background-color: red;"', $response->getContent());
1078
    }
1079
1080
/** +++++++++++++++++++++++++++++++++++ **/
1081
/** ++++++++++ TEST ENTITIES ++++++++++ **/
1082
/** +++++++++++++++++++++++++++++++++++ **/
1083
1084
    /**
1085
     * Get client instance.
1086
     *
1087
     * @return \JonnyW\PhantomJs\Client
1088
     */
1089
    protected function getClient()
1090
    {
1091
        $serviceContainer = ServiceContainer::getInstance();
1092
1093
        $client = new Client(
1094
            $serviceContainer->get('engine'),
0 ignored issues
show
Documentation introduced by
$serviceContainer->get('engine') is of type object|null, but the function expects a object<JonnyW\PhantomJs\Engine>.

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...
1095
            $serviceContainer->get('procedure_loader'),
0 ignored issues
show
Documentation introduced by
$serviceContainer->get('procedure_loader') is of type object|null, but the function expects a object<JonnyW\PhantomJs\...ocedureLoaderInterface>.

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...
1096
            $serviceContainer->get('procedure_compiler'),
0 ignored issues
show
Documentation introduced by
$serviceContainer->get('procedure_compiler') is of type object|null, but the function expects a object<JonnyW\PhantomJs\...edureCompilerInterface>.

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...
1097
            $serviceContainer->get('message_factory')
0 ignored issues
show
Documentation introduced by
$serviceContainer->get('message_factory') is of type object|null, but the function expects a object<JonnyW\PhantomJs\...essageFactoryInterface>.

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...
1098
        );
1099
1100
        return $client;
1101
    }
1102
1103
/** +++++++++++++++++++++++++++++++++++ **/
1104
/** ++++++++++++ UTILITIES ++++++++++++ **/
1105
/** +++++++++++++++++++++++++++++++++++ **/
1106
1107
    /**
1108
     * Set up test environment.
1109
     *
1110
     * @access public
1111
     * @return void
1112
     */
1113
    public function setUp()
1114
    {
1115
        $this->filename  = 'test.proc';
1116
        $this->directory = sys_get_temp_dir();
1117
1118
        if (!is_writable($this->directory)) {
1119
            throw new \RuntimeException(sprintf('Test directory must be writable: %s', $this->directory));
1120
        }
1121
    }
1122
1123
    /**
1124
     * Tear down test environment.
1125
     *
1126
     * @access public
1127
     * @return void
1128
     */
1129
    public function tearDown()
1130
    {
1131
        $filename = $this->getFilename();
1132
1133
        if (file_exists($filename)) {
1134
            unlink($filename);
1135
        }
1136
    }
1137
1138
    /**
1139
     * Get test filename.
1140
     *
1141
     * @access public
1142
     * @return string
1143
     */
1144
    public function getFilename()
1145
    {
1146
        return sprintf('%1$s/%2$s', $this->directory, $this->filename);
1147
    }
1148
1149
    /**
1150
     * Write procedure body to file.
1151
     *
1152
     * @access public
1153
     * @param  string $data
0 ignored issues
show
Bug introduced by
There is no parameter named $data. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1154
     * @return string
1155
     */
1156
    public function writeProcedure($procedure)
1157
    {
1158
        $filename = $this->getFilename();
1159
1160
        file_put_contents($filename, $procedure);
1161
1162
        return $filename;
1163
    }
1164
1165
    /**
1166
     * Get log entry index.
1167
     *
1168
     * @access public
1169
     * @param  array     $logs
1170
     * @param  string    $search
1171
     * @return int|false
1172
     */
1173
    public function getLogEntryIndex(array $logs, $search)
1174
    {
1175
        foreach ($logs as $index => $log) {
1176
1177
            $pos = stripos($log, $search);
1178
1179
            if ($pos !== false) {
1180
                return $index;
1181
            }
1182
        }
1183
1184
        return false;
1185
    }
1186
}
1187