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 ( c773f9...604f05 )
by Jonny
24:15 queued 06:25
created

testPdfRequestSavesFileToDiskWithCorrectOrientation()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
c 0
b 0
f 0
rs 8.8571
cc 1
eloc 18
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
        $expireAt = strtotime('16-Nov-2020 00:00:00');
278
279
        $request->setMethod('GET');
280
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
281
        $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000));
282
283
        $client->send($request, $response);
284
285
        $this->assertContains('test_cookie=TESTING_COOKIES; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file));
286
    }
287
288
    /**
289
     * Test can delete cookie from
290
     * persistent cookie file
291
     *
292
     * @access public
293
     * @return void
294
     */
295
    public function testCanDeleteCookieFromPersistentCookieFile()
296
    {
297
        $this->filename = 'cookies.txt';
298
        $file = ($this->directory . '/' . $this->filename);
299
300
        $client = $this->getClient();
301
        $client->getEngine()->addOption('--cookies-file=' . $file);
302
303
        $request  = $client->getMessageFactory()->createRequest();
304
        $response = $client->getMessageFactory()->createResponse();
305
306
        $expireAt = strtotime('16-Nov-2020 00:00:00');
307
308
        $request->setMethod('GET');
309
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
310
        $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000));
311
312
        $client->send($request, $response);
313
314
        $request = $client->getMessageFactory()->createRequest();
315
        $request->setMethod('GET');
316
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
317
        $request->deleteCookie('test_cookie');
318
319
        $client->send($request, $response);
320
321
        $this->assertNotContains('test_cookie=TESTING_COOKIES; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file));
322
    }
323
324
    /**
325
     * Test can delete all cookies from
326
     * persistent cookie file
327
     *
328
     * @access public
329
     * @return void
330
     */
331
    public function testCanDeleteAllCookiesFromPersistentCookieFile()
332
    {
333
        $this->filename = 'cookies.txt';
334
        $file = ($this->directory . '/' . $this->filename);
335
336
        $client = $this->getClient();
337
        $client->getEngine()->addOption('--cookies-file=' . $file);
338
339
        $request  = $client->getMessageFactory()->createRequest();
340
        $response = $client->getMessageFactory()->createResponse();
341
342
        $expireAt = strtotime('16-Nov-2020 00:00:00');
343
344
        $request->setMethod('GET');
345
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
346
        $request->addCookie('test_cookie_1', 'TESTING_COOKIES_1', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000));
347
        $request->addCookie('test_cookie_2', 'TESTING_COOKIES_2', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000));
348
349
        $client->send($request, $response);
350
351
        $request = $client->getMessageFactory()->createRequest();
352
        $request->setMethod('GET');
353
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
354
        $request->deleteCookie('*');
355
356
        $client->send($request, $response);
357
358
        $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));
359
        $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));
360
    }
361
362
363
    /**
364
     * Test can load cookies from
365
     * persistent cookie file
366
     *
367
     * @access public
368
     * @return void
369
     */
370
    public function testCookiesPresentInResponse()
371
    {
372
        $client = $this->getClient();
373
374
        $request  = $client->getMessageFactory()->createRequest();
375
        $response = $client->getMessageFactory()->createResponse();
376
377
        $expireAt = strtotime('16-Nov-2020 00:00:00');
378
379
        $request->setMethod('GET');
380
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
381
        $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000));
382
383
        $client->send($request, $response);
384
385
        $cookies = $response->getCookies();
386
        $this->assertEquals(array(
387
            'domain' => '.jonnyw.kiwi',
388
            'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT',
389
            'expiry' => '1605484800',
390
            'httponly' => true,
391
            'name' => 'test_cookie',
392
            'path' => '/',
393
            'secure' => false,
394
            'value' => 'TESTING_COOKIES',
395
        ), $cookies[0]);
396
    }
397
398
    /**
399
     * Test response contains console error if a
400
     * javascript error exists on the page.
401
     *
402
     * @access public
403
     * @return void
404
     */
405
    public function testResponseContainsConsoleErrorIfAJavascriptErrorExistsOnThePage()
406
    {
407
        $client = $this->getClient();
408
409
        $request  = $client->getMessageFactory()->createRequest();
410
        $response = $client->getMessageFactory()->createResponse();
411
412
        $request->setMethod('GET');
413
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php');
414
415
        $client->send($request, $response);
416
417
        $console = $response->getConsole();
418
419
        $this->assertCount(1, $console);
420
        $this->assertContains('ReferenceError: Can\'t find variable: invalid', $console[0]['message']);
421
    }
422
423
    /**
424
     * Test response contains console trace if a
425
     * javascript error exists on the page.
426
     *
427
     * @access public
428
     * @return void
429
     */
430
    public function testResponseContainsConsoleTraceIfAJavascriptErrorExistsOnThePage()
431
    {
432
        $client = $this->getClient();
433
434
        $request  = $client->getMessageFactory()->createRequest();
435
        $response = $client->getMessageFactory()->createResponse();
436
437
        $request->setMethod('GET');
438
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php');
439
440
        $client->send($request, $response);
441
442
        $console = $response->getConsole();
443
444
        $this->assertCount(1, $console[0]['trace']);
445
    }
446
447
    /**
448
     * Test response contains headers.
449
     *
450
     * @access public
451
     * @return void
452
     */
453
    public function testResponseContainsHeaders()
454
    {
455
        $client = $this->getClient();
456
457
        $request  = $client->getMessageFactory()->createRequest();
458
        $response = $client->getMessageFactory()->createResponse();
459
460
        $request->setMethod('GET');
461
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php');
462
463
        $client->send($request, $response);
464
465
        $this->assertNotEmpty($response->getHeaders());
466
    }
467
468
    /**
469
     * Test redirect URL is set in response
470
     * if request is redirected.
471
     *
472
     * @access public
473
     * @return void
474
     */
475
    public function testRedirectUrlIsSetInResponseIfRequestIsRedirected()
476
    {
477
        $client = $this->getClient();
478
479
        $request  = $client->getMessageFactory()->createRequest();
480
        $response = $client->getMessageFactory()->createResponse();
481
482
        $request->setMethod('GET');
483
        $request->setUrl('https://jigsaw.w3.org/HTTP/300/302.html');
484
485
        $client->send($request, $response);
486
487
        $this->assertNotEmpty($response->getRedirectUrl());
488
    }
489
490
    /**
491
     * Test POST request sends request data.
492
     *
493
     * @access public
494
     * @return void
495
     */
496
    public function testPostRequestSendsRequestData()
497
    {
498
        $client = $this->getClient();
499
500
        $request  = $client->getMessageFactory()->createRequest();
501
        $response = $client->getMessageFactory()->createResponse();
502
503
        $request->setMethod('POST');
504
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-post.php');
505
        $request->setRequestData(array(
506
            'test1' => 'http://test.com',
507
            'test2' => 'A string with an \' ) / # some other invalid [ characters.'
508
        ));
509
510
        $client->send($request, $response);
511
512
        $this->assertContains(sprintf('<li>test1=%s</li>', 'http://test.com'), $response->getContent());
513
        $this->assertContains(sprintf('<li>test2=%s</li>', 'A string with an \' ) / # some other invalid [ characters.'), $response->getContent());
514
    }
515
516
    /**
517
     * Test capture request saves file to
518
     * to local disk.
519
     *
520
     * @access public
521
     * @return void
522
     */
523
    public function testCaptureRequestSavesFileToLocalDisk()
524
    {
525
        $this->filename = 'test.jpg';
526
        $file = ($this->directory . '/' . $this->filename);
527
528
        $client = $this->getClient();
529
530
        $request  = $client->getMessageFactory()->createCaptureRequest();
531
        $response = $client->getMessageFactory()->createResponse();
532
533
        $request->setMethod('GET');
534
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
535
        $request->setOutputFile($file);
536
537
        $client->send($request, $response);
538
539
        $this->assertTrue(file_exists($file));
540
    }
541
542
    /**
543
     * Test capture request saves file to
544
     * disk with correct capture dimensions.
545
     *
546
     * @access public
547
     * @return void
548
     */
549
    public function testCaptureRequestSavesFileToDiskWithCorrectCaptureDimensions()
550
    {
551
        $this->filename = 'test.jpg';
552
        $file = ($this->directory . '/' . $this->filename);
553
554
        $width  = 200;
555
        $height = 400;
556
557
        $client = $this->getClient();
558
559
        $request  = $client->getMessageFactory()->createCaptureRequest();
560
        $response = $client->getMessageFactory()->createResponse();
561
562
        $request->setMethod('GET');
563
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
564
        $request->setOutputFile($file);
565
        $request->setCaptureDimensions($width, $height);
566
567
        $client->send($request, $response);
568
569
        $imageInfo = getimagesize($file);
570
571
        $this->assertEquals($width, $imageInfo[0]);
572
        $this->assertEquals($height, $imageInfo[1]);
573
    }
574
575
    /**
576
     * Test PDF request saves pdf to
577
     * to local disk.
578
     *
579
     * @access public
580
     * @return void
581
     */
582
    public function testPdfRequestSavesPdfToLocalDisk()
583
    {
584
        $this->filename = 'test.pdf';
585
        $file = ($this->directory . '/' . $this->filename);
586
587
        $client = $this->getClient();
588
589
        $request  = $client->getMessageFactory()->createPdfRequest();
590
        $response = $client->getMessageFactory()->createResponse();
591
592
        $request->setMethod('GET');
593
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
594
        $request->setOutputFile($file);
595
596
        $client->send($request, $response);
597
598
        $this->assertTrue(file_exists($file));
599
    }
600
601
    /**
602
     * Test PDF request saves file to
603
     * disk with correct paper size.
604
     *
605
     * @access public
606
     * @return void
607
     */
608
    public function testPdfRequestSavesFileToDiskWithCorrectPaperSize()
609
    {
610
        $this->filename = 'test.pdf';
611
        $file = ($this->directory . '/' . $this->filename);
612
613
        $width  = 20;
614
        $height = 30;
615
616
        $client = $this->getClient();
617
618
        $request  = $client->getMessageFactory()->createPdfRequest();
619
        $response = $client->getMessageFactory()->createResponse();
620
621
        $request->setMethod('GET');
622
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
623
        $request->setOutputFile($file);
624
        $request->setPaperSize(sprintf('%scm', $width), sprintf('%scm', $height));
625
        $request->setMargin('0cm');
626
627
        $client->send($request, $response);
628
629
        $pdf = \ZendPdf\PdfDocument::load($file);
630
631
        $pdfWidth  = round(($pdf->pages[0]->getWidth() * 0.0352777778));
632
        $pdfHeight = round(($pdf->pages[0]->getHeight()  * 0.0352777778));
633
634
        $this->assertEquals($width, $pdfWidth);
635
        $this->assertEquals($height, $pdfHeight);
636
    }
637
638
    /**
639
     * Test PDF request saves file to
640
     * disk with correct format size.
641
     *
642
     * @access public
643
     * @return void
644
     */
645
    public function testPdfRequestSavesFileToDiskWithCorrectFormatSize()
646
    {
647
        $this->filename = 'test.pdf';
648
        $file = ($this->directory . '/' . $this->filename);
649
650
        $client = $this->getClient();
651
652
        $request  = $client->getMessageFactory()->createPdfRequest();
653
        $response = $client->getMessageFactory()->createResponse();
654
655
        $request->setMethod('GET');
656
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
657
        $request->setOutputFile($file);
658
        $request->setFormat('A4');
659
        $request->setMargin('0cm');
660
661
        $client->send($request, $response);
662
663
        $pdf = \ZendPdf\PdfDocument::load($file);
664
665
        $pdfWidth  = round(($pdf->pages[0]->getWidth() * 0.0352777778));
666
        $pdfHeight = round(($pdf->pages[0]->getHeight()  * 0.0352777778));
667
668
        $this->assertEquals(21, $pdfWidth);
669
        $this->assertEquals(30, $pdfHeight);
670
    }
671
672
    /**
673
     * Test PDF request saves file to
674
     * disk with correct orientation.
675
     *
676
     * @access public
677
     * @return void
678
     */
679
    public function testPdfRequestSavesFileToDiskWithCorrectOrientation()
680
    {
681
        $this->filename = 'test.pdf';
682
        $file = ($this->directory . '/' . $this->filename);
683
684
        $client = $this->getClient();
685
686
        $request  = $client->getMessageFactory()->createPdfRequest();
687
        $response = $client->getMessageFactory()->createResponse();
688
689
        $request->setMethod('GET');
690
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
691
        $request->setOutputFile($file);
692
        $request->setFormat('A4');
693
        $request->setOrientation('landscape');
694
        $request->setMargin('0cm');
695
696
        $client->send($request, $response);
697
698
        $pdf = \ZendPdf\PdfDocument::load($file);
699
700
        $pdfWidth  = round(($pdf->pages[0]->getWidth() * 0.0352777778));
701
        $pdfHeight = round(($pdf->pages[0]->getHeight()  * 0.0352777778));
702
703
        $this->assertEquals(30, $pdfWidth);
704
        $this->assertEquals(21, $pdfHeight);
705
    }
706
707
    /**
708
     * Test can set repeating header
709
     * for PDF request
710
     *
711
     * @access public
712
     * @return void
713
     */
714
    public function testCanSetRepeatingHeaderForPDFRequest()
715
    {
716
        $this->filename = 'test.pdf';
717
        $file = ($this->directory . '/' . $this->filename);
718
719
        $client = $this->getClient();
720
721
        $request  = $client->getMessageFactory()->createPdfRequest();
722
        $response = $client->getMessageFactory()->createResponse();
723
724
        $request->setMethod('GET');
725
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
726
        $request->setOutputFile($file);
727
        $request->setFormat('A4');
728
        $request->setOrientation('landscape');
729
        $request->setMargin('0cm');
730
        $request->setRepeatingHeader('<h1>Header <span style="float:right">%pageNum% / %pageTotal%</span></h1>', '2cm');
731
        $request->setRepeatingFooter('<footer>Footer <span style="float:right">%pageNum% / %pageTotal%</span></footer>', '2cm');
732
733
        $client->send($request, $response);
734
735
        $parser = new \Smalot\PdfParser\Parser();
736
        $pdf    = $parser->parseFile($file);
737
738
        $text = str_replace(' ', '', $pdf->getText());
739
740
        $this->assertContains('Header', $text);
741
    }
742
743
    /**
744
     * Test can set repeating footer
745
     * for PDF request
746
     *
747
     * @access public
748
     * @return void
749
     */
750
    public function testCanSetRepeatingFooterForPDFRequest()
751
    {
752
        $this->filename = 'test.pdf';
753
        $file = ($this->directory . '/' . $this->filename);
754
755
        $client = $this->getClient();
756
757
        $request  = $client->getMessageFactory()->createPdfRequest();
758
        $response = $client->getMessageFactory()->createResponse();
759
760
        $request->setMethod('GET');
761
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
762
        $request->setOutputFile($file);
763
        $request->setFormat('A4');
764
        $request->setOrientation('landscape');
765
        $request->setMargin('0cm');
766
        $request->setRepeatingHeader('<h1>Header <span style="float:right">%pageNum% / %pageTotal%</span></h1>', '2cm');
767
        $request->setRepeatingFooter('<footer>Footer <span style="float:right">%pageNum% / %pageTotal%</span></footer>', '2cm');
768
769
        $client->send($request, $response);
770
771
        $parser = new \Smalot\PdfParser\Parser();
772
        $pdf    = $parser->parseFile($file);
773
774
        $text = str_replace(' ', '', $pdf->getText());
775
776
        $this->assertContains('Footer', $text);
777
    }
778
779
    /**
780
     * Test set viewport size sets
781
     * size of viewport in default
782
     * request.
783
     *
784
     * @access public
785
     * @return void
786
     */
787
    public function testSetViewportSizeSetsSizeOfViewportInDefaultRequest()
788
    {
789
        $width  = 100;
790
        $height = 200;
791
792
        $client = $this->getClient();
793
794
        $request  = $client->getMessageFactory()->createRequest();
795
        $response = $client->getMessageFactory()->createResponse();
796
797
        $request->setMethod('GET');
798
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
799
        $request->setViewportsize($width, $height);
800
801
        $client->send($request, $response);
802
803
        $logs = explode("\n", $client->getLog());
804
805
        $startIndex = $this->getLogEntryIndex($logs, 'Set viewport size ~ width: 100 height: 200');
806
807
        $this->assertTrue(($startIndex !== false));
808
    }
809
810
    /**
811
     * Test set viewport size sets
812
     * size of viewport in capture
813
     * request.
814
     *
815
     * @access public
816
     * @return void
817
     */
818
    public function testSetViewportSizeSetsSizeOfViewportInCaptureRequest()
819
    {
820
        $width  = 100;
821
        $height = 200;
822
823
        $client = $this->getClient();
824
825
        $request  = $client->getMessageFactory()->createCaptureRequest();
826
        $response = $client->getMessageFactory()->createResponse();
827
828
        $request->setMethod('GET');
829
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
830
        $request->setViewportsize($width, $height);
831
832
        $client->send($request, $response);
833
834
        $logs = explode("\n", $client->getLog());
835
836
        $startIndex = $this->getLogEntryIndex($logs, 'Set viewport size ~ width: 100 height: 200');
837
838
        $this->assertTrue(($startIndex !== false));
839
    }
840
841
    /**
842
     * Test delay logs start time
843
     * in client for default request.
844
     *
845
     * @access public
846
     * @return void
847
     */
848
    public function testDelayLogsStartTimeInClientForDefaultRequest()
849
    {
850
        $delay = 1;
851
852
        $client = $this->getClient();
853
854
        $request  = $client->getMessageFactory()->createRequest();
855
        $response = $client->getMessageFactory()->createResponse();
856
857
        $request->setMethod('GET');
858
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
859
        $request->setDelay($delay);
860
861
        $client->send($request, $response);
862
863
        $logs = explode("\n", $client->getLog());
864
865
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
866
867
        $this->assertTrue(($startIndex !== false));
868
    }
869
870
    /**
871
     * Test delay logs end time
872
     * in client for default request.
873
     *
874
     * @access public
875
     * @return void
876
     */
877
    public function testDelayLogsEndTimeInClientForDefaultRequest()
878
    {
879
        $delay = 1;
880
881
        $client = $this->getClient();
882
883
        $request  = $client->getMessageFactory()->createRequest();
884
        $response = $client->getMessageFactory()->createResponse();
885
886
        $request->setMethod('GET');
887
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
888
        $request->setDelay($delay);
889
890
        $client->send($request, $response);
891
892
        $logs = explode("\n", $client->getLog());
893
894
        $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after');
895
896
        $this->assertTrue(($endIndex !== false));
897
    }
898
899
    /**
900
     * Test delay delays page render for
901
     * specified time for default request.
902
     *
903
     * @access public
904
     * @return void
905
     */
906
    public function testDelayDelaysPageRenderForSpecifiedTimeForDefaultRequest()
907
    {
908
        $delay = 1;
909
910
        $client = $this->getClient();
911
912
        $request  = $client->getMessageFactory()->createRequest();
913
        $response = $client->getMessageFactory()->createResponse();
914
915
        $request->setMethod('GET');
916
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
917
        $request->setDelay($delay);
918
919
        $client->send($request, $response);
920
921
        $logs = explode("\\n", $client->getLog());
922
923
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
924
        $endIndex   = $this->getLogEntryIndex($logs, 'Rendering page after');
925
926
        $startTime = strtotime(substr($logs[$startIndex], 0 , 19));
927
        $endTime   = strtotime(substr($logs[$endIndex], 0 , 19));
928
929
        $this->assertSame(($startTime+$delay), $endTime);
930
    }
931
932
    /**
933
     * Test delay logs start time
934
     * in client for capture request.
935
     *
936
     * @access public
937
     * @return void
938
     */
939
    public function testDelayLogsStartTimeInClientForCaptureRequest()
940
    {
941
        $delay = 1;
942
943
        $client = $this->getClient();
944
945
        $request  = $client->getMessageFactory()->createCaptureRequest();
946
        $response = $client->getMessageFactory()->createResponse();
947
948
        $request->setMethod('GET');
949
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
950
        $request->setDelay($delay);
951
952
        $client->send($request, $response);
953
954
        $logs = explode("\\n", $client->getLog());
955
956
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
957
958
        $this->assertTrue(($startIndex !== false));
959
    }
960
961
    /**
962
     * Test delay logs end time
963
     * in client for capture request.
964
     *
965
     * @access public
966
     * @return void
967
     */
968
    public function testDelayLogsEndTimeInClientForCaptureRequest()
969
    {
970
        $delay = 1;
971
972
        $client = $this->getClient();
973
974
        $request  = $client->getMessageFactory()->createCaptureRequest();
975
        $response = $client->getMessageFactory()->createResponse();
976
977
        $request->setMethod('GET');
978
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
979
        $request->setDelay($delay);
980
981
        $client->send($request, $response);
982
983
        $logs = explode("\\n", $client->getLog());
984
985
        $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after');
986
987
        $this->assertTrue(($endIndex !== false));
988
    }
989
990
    /**
991
     * Test delay delays page render for
992
     * specified time for capture request.
993
     *
994
     * @access public
995
     * @return void
996
     */
997
    public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest()
998
    {
999
        $delay = 1;
1000
1001
        $client = $this->getClient();
1002
1003
        $request  = $client->getMessageFactory()->createCaptureRequest();
1004
        $response = $client->getMessageFactory()->createResponse();
1005
1006
        $request->setMethod('GET');
1007
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
1008
        $request->setDelay($delay);
1009
1010
        $client->send($request, $response);
1011
1012
        $logs = explode("\\n", $client->getLog());
1013
1014
        $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for');
1015
        $endIndex   = $this->getLogEntryIndex($logs, 'Rendering page after');
1016
1017
        $startTime = strtotime(substr($logs[$startIndex], 0 , 19));
1018
        $endTime   = strtotime(substr($logs[$endIndex], 0 , 19));
1019
1020
        $this->assertSame(($startTime+$delay), $endTime);
1021
    }
1022
1023
    /**
1024
     * Test lazy request returns content after
1025
     * all resources are loaded
1026
     *
1027
     * @access public
1028
     * @return void
1029
     */
1030
    public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded()
1031
    {
1032
        $client = $this->getClient();
1033
        $client->isLazy();
1034
1035
        $request  = $client->getMessageFactory()->createRequest();
1036
        $response = $client->getMessageFactory()->createResponse();
1037
1038
        $request->setMethod('GET');
1039
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php');
1040
        $request->setTimeout(5000);
1041
1042
        $client->send($request, $response);
1043
1044
        $this->assertContains('<p id="content">loaded</p>', $response->getContent());
1045
    }
1046
1047
    /**
1048
     * Test content is returned for lazy request
1049
     * if timeout is reached before resource is
1050
     * loaded
1051
     *
1052
     * @access public
1053
     * @return void
1054
     */
1055
    public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResourceIsLoaded()
1056
    {
1057
        $client = $this->getClient();
1058
        $client->isLazy();
1059
1060
        $request  = $client->getMessageFactory()->createRequest();
1061
        $response = $client->getMessageFactory()->createResponse();
1062
1063
        $request->setMethod('GET');
1064
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php');
1065
        $request->setTimeout(1000);
1066
1067
        $client->send($request, $response);
1068
1069
        $this->assertContains('<p id="content"></p>', $response->getContent());
1070
    }
1071
1072
    /**
1073
     * Test debug logs debug info to
1074
     * client log.
1075
     *
1076
     * @access public
1077
     * @return void
1078
     */
1079
    public function testDebugLogsDebugInfoToClientLog()
1080
    {
1081
        $client = $this->getClient();
1082
        $client->getEngine()->debug(true);
1083
1084
        $request  = $client->getMessageFactory()->createRequest();
1085
        $response = $client->getMessageFactory()->createResponse();
1086
1087
        $request->setMethod('GET');
1088
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php');
1089
1090
        $client->send($request, $response);
1091
1092
        $this->assertContains('[DEBUG]', $client->getLog());
1093
    }
1094
1095
    /**
1096
     * Test test can set page
1097
     * background color
1098
     *
1099
     * @access public
1100
     * @return void
1101
     */
1102
    public function testCanSetPageBackgroundColor()
1103
    {
1104
        $this->filename = 'test.jpg';
1105
        $file = ($this->directory . '/' . $this->filename);
1106
1107
        $client = $this->getClient();
1108
1109
        $request  = $client->getMessageFactory()->createCaptureRequest();
1110
        $response = $client->getMessageFactory()->createResponse();
1111
1112
        $request->setMethod('GET');
1113
        $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php');
1114
        $request->setBodyStyles(array('backgroundColor' => 'red'));
1115
        $request->setOutputFile($file);
1116
1117
        $client->send($request, $response);
1118
1119
        $this->assertContains('body style="background-color: red;"', $response->getContent());
1120
    }
1121
1122
/** +++++++++++++++++++++++++++++++++++ **/
1123
/** ++++++++++ TEST ENTITIES ++++++++++ **/
1124
/** +++++++++++++++++++++++++++++++++++ **/
1125
1126
    /**
1127
     * Get client instance.
1128
     *
1129
     * @return \JonnyW\PhantomJs\Client
1130
     */
1131
    protected function getClient()
1132
    {
1133
        $serviceContainer = ServiceContainer::getInstance();
1134
1135
        $client = new Client(
1136
            $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...
1137
            $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...
1138
            $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...
1139
            $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...
1140
        );
1141
1142
        return $client;
1143
    }
1144
1145
/** +++++++++++++++++++++++++++++++++++ **/
1146
/** ++++++++++++ UTILITIES ++++++++++++ **/
1147
/** +++++++++++++++++++++++++++++++++++ **/
1148
1149
    /**
1150
     * Set up test environment.
1151
     *
1152
     * @access public
1153
     * @return void
1154
     */
1155
    public function setUp()
1156
    {
1157
        $this->filename  = 'test.proc';
1158
        $this->directory = sys_get_temp_dir();
1159
1160
        if (!is_writable($this->directory)) {
1161
            throw new \RuntimeException(sprintf('Test directory must be writable: %s', $this->directory));
1162
        }
1163
    }
1164
1165
    /**
1166
     * Tear down test environment.
1167
     *
1168
     * @access public
1169
     * @return void
1170
     */
1171
    public function tearDown()
1172
    {
1173
        $filename = $this->getFilename();
1174
1175
        if (file_exists($filename)) {
1176
            unlink($filename);
1177
        }
1178
    }
1179
1180
    /**
1181
     * Get test filename.
1182
     *
1183
     * @access public
1184
     * @return string
1185
     */
1186
    public function getFilename()
1187
    {
1188
        return sprintf('%1$s/%2$s', $this->directory, $this->filename);
1189
    }
1190
1191
    /**
1192
     * Write procedure body to file.
1193
     *
1194
     * @access public
1195
     * @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...
1196
     * @return string
1197
     */
1198
    public function writeProcedure($procedure)
1199
    {
1200
        $filename = $this->getFilename();
1201
1202
        file_put_contents($filename, $procedure);
1203
1204
        return $filename;
1205
    }
1206
1207
    /**
1208
     * Get log entry index.
1209
     *
1210
     * @access public
1211
     * @param  array     $logs
1212
     * @param  string    $search
1213
     * @return int|false
1214
     */
1215
    public function getLogEntryIndex(array $logs, $search)
1216
    {
1217
        foreach ($logs as $index => $log) {
1218
1219
            $pos = stripos($log, $search);
1220
1221
            if ($pos !== false) {
1222
                return $index;
1223
            }
1224
        }
1225
1226
        return false;
1227
    }
1228
}
1229