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 ( 0baec8...65564e )
by Jonny
04:04
created

ClientTest::testCanSetUserAgentInSettings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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