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 ( 50bc19...384b6d )
by Jonny
05:20
created

testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResourceIsLoaded()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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