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.

testCanSetRepeatingFooterForPDFRequest()   B
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

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