From ab54e5d87eaee42afd9434a3d65bfef8681d76c3 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 7 Jul 2015 20:19:11 +0100 Subject: [PATCH 01/54] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 1b4b374..da160af 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ PHP PhantomJS ============= +**Please Note:** Version 4.0 of this library is currently waiting on an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with PhantomJS 2.0. + PHP PhantomJS is a flexible PHP library to load pages through the PhantomJS headless browser and return the page response. It is handy for testing websites that demand javascript support and also supports screen captures. From d75c3b50c19590c55716cc46c2425438eaf880bf Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 10:46:30 +0000 Subject: [PATCH 02/54] Updating packages --- composer.json | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 3df86e4..d5c2bbe 100644 --- a/composer.json +++ b/composer.json @@ -19,12 +19,18 @@ "symfony/filesystem": "~2.3", "symfony/yaml": "~2.3", "twig/twig": "~1.16", - "jakoch/phantomjs-installer": "1.9.8" + "jakoch/phantomjs-installer": "2.0.0" }, "require-dev": { "phpunit/phpunit": "~4.0", "zendframework/zendpdf": "~2.0" }, + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/jonnnnyw/phantomjs-installer" + } + ], "autoload": { "psr-0": { "JonnyW\\PhantomJs\\": "src" @@ -34,9 +40,6 @@ "config": { "bin-dir": "bin" }, - "bin": [ - "bin/phantomloader" - ], "scripts": { "post-install-cmd": [ "PhantomInstaller\\Installer::installPhantomJS" From 2cb40e01d846432807a119a5ef8252308490d0b9 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 10:50:07 +0000 Subject: [PATCH 03/54] Adding additional operating systems to travis tests --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index 7e7a327..e6d958f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,10 @@ language: php +os: + - linux + - osx + - windows + php: - 5.3 - 5.4 From b47bbcecd746ba756a8544b3b6d364484e359865 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 10:54:58 +0000 Subject: [PATCH 04/54] Removing OSX from travis tests --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e6d958f..c77fe7a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,7 +2,6 @@ language: php os: - linux - - osx - windows php: From 8ed00db57a1a836664f55dd9165fbdc6dd3877f4 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:00:54 +0000 Subject: [PATCH 05/54] Specifying PHP versions --- .travis.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index c77fe7a..6e0eff3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,9 +5,10 @@ os: - windows php: - - 5.3 - - 5.4 - - 5.5 + - 5.3.29 + - 5.4.45 + - 5.5.29 + - 5.6.13 before_script: - composer self-update From bc0bce303885b6f89d1f8fc72a92d17d4c886876 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:02:25 +0000 Subject: [PATCH 06/54] Removing pyrus from travis --- .travis.yml | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 6e0eff3..c55dcba 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,15 +5,14 @@ os: - windows php: - - 5.3.29 - - 5.4.45 - - 5.5.29 - - 5.6.13 + - 5.3 + - 5.4 + - 5.5 + - 5.6 before_script: - composer self-update - composer install - - pyrus install pear/PHP_CodeSniffer - phpenv rehash script: From e44ccd5e62198a704ed670cd96dfd96fd361e130 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:15:39 +0000 Subject: [PATCH 07/54] Removing php 5.6 --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c55dcba..41e7274 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,6 @@ php: - 5.3 - 5.4 - 5.5 - - 5.6 before_script: - composer self-update From 380cfd3176facf3d7c666fe074b082b02f832431 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:24:13 +0000 Subject: [PATCH 08/54] Updaitng README --- README.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/README.md b/README.md index da160af..941b07d 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ PHP PhantomJS ============= -**Please Note:** Version 4.0 of this library is currently waiting on an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with PhantomJS 2.0. - PHP PhantomJS is a flexible PHP library to load pages through the PhantomJS headless browser and return the page response. It is handy for testing websites that demand javascript support and also supports screen captures. @@ -20,14 +18,9 @@ Feature List * View javascript console errors * View detailed PhantomJS debugged information * Save screen captures to local disk +* Export pages to PDF * Set viewport size * Define screen capture x, y, width and height parameters * Delay page rendering for a specified time * Execute PhantomJS with command line options * Easily build and run custom PhantomJS scripts - - -Upgrading From v2.* ---------------------- - -If you are using a version of PHP PhantomJS prior to version v3.0.0 then you should note that there have been some major changes to the interface. Please view the [Full Documentation](http://jonnnnyw.github.io/php-phantomjs/) as a guide when upgrading your implementation. From d59437ddb394293efdc000c56356547beffcf9da Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:37:15 +0000 Subject: [PATCH 09/54] Updaitng README --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 941b07d..13c3587 100644 --- a/README.md +++ b/README.md @@ -16,11 +16,11 @@ Feature List * View detailed response data including page content, headers, status code etc. * Handle redirects * View javascript console errors -* View detailed PhantomJS debugged information -* Save screen captures to local disk -* Export pages to PDF +* View detailed PhantomJS debuged information +* Save screen captures to local disk +* Output web pages to PDF document * Set viewport size * Define screen capture x, y, width and height parameters * Delay page rendering for a specified time * Execute PhantomJS with command line options -* Easily build and run custom PhantomJS scripts +* Easily build and run custom PhantomJS scripts \ No newline at end of file From 190a113775ce22560b3e0433cb3002b6248f77f8 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:49:26 +0000 Subject: [PATCH 10/54] Removing outdated docs and examples --- doc/advanced.rst | 365 ------------------------ doc/installation.rst | 128 --------- doc/intro.rst | 129 --------- doc/troubleshooting.rst | 372 ------------------------- doc/usage.rst | 315 --------------------- examples/basic-request.php | 17 -- examples/capture-request.php | 31 --- examples/custom-phantomjs-location.php | 8 - examples/custom-script.php | 42 --- examples/debug-request.php | 21 -- examples/delay-page-render.php | 28 -- examples/javascript-console.php | 21 -- examples/post-request.php | 23 -- 13 files changed, 1500 deletions(-) delete mode 100644 doc/advanced.rst delete mode 100644 doc/installation.rst delete mode 100644 doc/intro.rst delete mode 100644 doc/troubleshooting.rst delete mode 100644 doc/usage.rst delete mode 100644 examples/basic-request.php delete mode 100644 examples/capture-request.php delete mode 100644 examples/custom-phantomjs-location.php delete mode 100644 examples/custom-script.php delete mode 100644 examples/debug-request.php delete mode 100644 examples/delay-page-render.php delete mode 100644 examples/javascript-console.php delete mode 100644 examples/post-request.php diff --git a/doc/advanced.rst b/doc/advanced.rst deleted file mode 100644 index f84a4fa..0000000 --- a/doc/advanced.rst +++ /dev/null @@ -1,365 +0,0 @@ -Advanced -======== - -- `PhantomJS command line options <#phantomjs-command-line-options>`__ -- `Custom PhantomJS scripts <#custom-phantom-js-scripts>`__ -- `Writing a custom script <#writing-a-custom-script>`__ -- `Using custom request parameters in your - script <#using-custom-request-parameters-in-your-script>`__ -- `Loading your script <#loading-your-script>`__ - -PhantomJS command line options ------------------------------- - -The PhantomJS API contains a range of command line options that can be -passed when executing the PhantomJS executable. These can also be passed -in via the client before a request: - -.. code:: php - - - addOption('--load-images=true'); - $client->addOption('--ignore-ssl-errors=true'); - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - -You can also set a path to a JSON configuration file that contains -multiple PhantomJS options: - -.. code:: php - - - addOption('--config=/path/to/config.json'); - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - -See the `PhantomJS -Documentation `__ for a full -list of command line options. - -Custom PhantomJS scripts ------------------------- - -In most instances you shouldn't need to worry about the javascript files -that run the PHP PhantomJS library but there may be times when you want -to execute your own custom PhantomJS scripts through the client. This -can be easily achieved by using the built in script loader. - -Script files or 'procedures' as they are referred to in the application -are closely mapped to requests. When you create a default request -instance, you are essentially running the default javascript procedure -that comes bundled with the application. When you create a capture -request you are running the capture procedure. - -.. code:: php - - - getMessageFactory()->createRequest(); // ~/Resources/procedures/default.proc - $client->getMessageFactory()->createCaptureRequest(); // ~/Resources/procedures/capture.proc - -Writing a custom script -~~~~~~~~~~~~~~~~~~~~~~~ - -The first step in creating your script is to create a procedure file -somewhere. For the purpose of this guide we will refer to it as -``my_procedure.proc`` but in reality it can be called anything you like. -The only requirement is that the file extension must be ``.proc``. - -Create the file somewhere and make sure it can be read by your -application. Make a note of the path to the directory where your file is -created as you will need this when loading your script which is -explained later in this guide. - -.. code:: shell - - - $ touch my_procedure.proc - $ chmod 755 my_procedure.proc - - -Next open your procedure file in your text editor and write your -PhantomJS script. The `PhantomJS -documentation `__ has more -detailed information on writing custom scripts. - -.. code:: javascript - - - // my_procedure.proc - - var page = require('webpage').create(); - - page.open ('{{ request.getUrl() }}', '{{ request.getMethod() }}', '{{ request.getBody() }}', function (status) { - - // It is important that you exit PhantomJS - // when your script has run or when you - // encounter an error - phantom.exit(1); - }); - - ... - - -.. important:: - Make sure that ``phantom.exit(1);`` is always called after your script has run or if you encounter an error. This requires you to take care when handling PhantomJS errors to ensure that you exit the PhantomJS script, whether the script was successfully executed or not. If you do not call ``phantom.exit(1);`` then PhantomJS will continue to run until your PHP script times out. If you find that your custom script is hanging then this is most likely the cause. - -It is a good practice to create a global error handler in your script -that exits PhantomJS: - -.. code:: javascript - - - // my_procedure.proc - - phantom.onError = function(msg, trace) { - - phantom.exit(1); - }; - - ... - -Using custom request parameters in your script -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Before a procedure is executed by the application it is parsed through a -template parser. The PHP PhantomJS library uses the popular `Twig -templating engine `__. This gives you -access to all the `Twig -niceness `__ which you -can use in your custom scripts. - -You may have noticed in the example above that we have used some Twig -template tags referencing a request object e.g. -``{{ request.getUrl() }}``. This is in fact the PHP request instance -that you created and passed to the client when sending your request, -which is injected into the Twig template parser. As a result you gain -full access to all the data contained within the request instance, via -the data accessor methods. - -A default request instance contains the following accessors: - -+--------------------------+-----------------------------------------------+------------------------------------+ -| Accessor | Description | Twig example | -+==========================+===============================================+====================================+ -| getMethod() | The request method e.g. GET. | {{ request.getMethod() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getTimeout() | The request timeout period in milliseconds. | {{ request.getTimeout() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getDelay() | The page render delay in seconds. | {{ request.getDelay() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getViewportWidth() | The viewport width. | {{ request.getViewportWidth() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getViewportHeight() | The viewport height. | {{ request.getViewportHeight() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getUrl() | The request URL. | {{ request.getUrl() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getBody() | The request body (POST, PUT). | {{ request.getBody() }} | -+--------------------------+-----------------------------------------------+------------------------------------+ -| getHeaders(\ *format*) | The request headers. | {{ request.getHeaders('json') }} | -+--------------------------+-----------------------------------------------+------------------------------------+ - -A capture request contains a few additional ones: - -+--------------------+-------------------------------------------+----------------------------------+ -| Accessor | Description | Twig example | -+====================+===========================================+==================================+ -| getRectTop() | The x coordinate of the capture region. | {{ request.getRectTop() }} | -+--------------------+-------------------------------------------+----------------------------------+ -| getRectLeft() | The y coordinate of the capture region. | {{ request.getRectLeft() }} | -+--------------------+-------------------------------------------+----------------------------------+ -| getRectWidth() | The width of the capture region. | {{ request.getRectWidth() }} | -+--------------------+-------------------------------------------+----------------------------------+ -| getRectHeight() | The height of the capture region. | {{ request.getRectHeight() }} | -+--------------------+-------------------------------------------+----------------------------------+ -| getCaptureFile() | The file to save the capture to. | {{ request.getCaptureFile() }} | -+--------------------+-------------------------------------------+----------------------------------+ - -If you would like to inject additional data into your script through -custom accessors, simply extend the request class with your own: - -.. code:: php - - - getMessageFactory()->createResponse(); - - $request = new CustomRequest(); - $request->setMethod('GET'); - $request->setUrl('http://www.google.com'); - - $client->send($request, $response); - -Loading your script -~~~~~~~~~~~~~~~~~~~ - -Now that you have your custom script and you've added your custom -request parameters, you may be wondering how to tell the client to -actually load your script. This is done by creating a procedure loader -and telling it where to find your script files. - -The service container has a factory that makes creating a new procedure -loader easy: - -.. code:: php - - - get('procedure_loader_factory') - ->createProcedureLoader($location); - - ... - -The client contains a chain procedure loader which lets you set multiple -loaders at the same time. Ultimately this means that you can load your -custom scripts while still maintaining the ability to load the default -scripts if you choose. - -Now add your procedure loader to the chain loader: - -.. code:: php - - - getProcedureLoader()->addLoader($procedureLoader); - - ... - -The last thing you need to do is to tell the request which script you -want to load for that request. This is done by setting the request type -to the name of your procedure file, minus the extension: - -.. code:: php - - - getMessageFactory()->createRequest(); - $request->setType('my_procedure'); - - ... - -Or if you are using a custom request as outlined in the `custom request -parameters <#using-custom-request-parameters-in-your-script>`__ section, -you can implement a ``getType()`` method which returns the name of your -procedure, eliminating the need to set the request type for each -request: - -.. code:: php - - - get('procedure_loader_factory') - ->createProcedureLoader($location); - - $client = Client::getInstance(); - $client->getProcedureLoader()->addLoader($procedureLoader); - - $request = $client->getMessageFactory()->createRequest(); - $request->setType('my_procedure'); - - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - -.. important:: - If you find that your script isn't running or that you are receiving a status of '0' back in the response, chances are you have a syntax error in you script. It pays to turn debugging on in the client ``$client->debug(true)`` which will then give you access to some log information through ``$client->getLog()``. - -See more detailed information about -`troubleshooting https://github.com/jonnnnyw/php-phantomjs/blob/master/doc/troubleshooting.rst>`__. \ No newline at end of file diff --git a/doc/installation.rst b/doc/installation.rst deleted file mode 100644 index d77932a..0000000 --- a/doc/installation.rst +++ /dev/null @@ -1,128 +0,0 @@ -Installation -============ - -- `Prerequisites <#prerequisites>`__ -- `Installing via Composer <#installing-via-composer>`__ -- `Custom Installation <#custom-installation>`__ -- `Installing from tarball <#installing-from-tarball>`__ - -Prerequisites -------------- - -PHP PhantomJS requires PHP **5.3.0** or greater to run. - -Installing via Composer ------------------------ - -Install `Composer `__ for your project: - -.. code:: shell - - $ curl -s http://getcomposer.org/installer | php - -Create a ``composer.json`` file in the root of your project: - -.. code:: yaml - - { - "require": { - "jonnyw/php-phantomjs": "3.*" - }, - "config": { - "bin-dir": "bin" - }, - "scripts": { - "post-install-cmd": [ - "PhantomInstaller\\Installer::installPhantomJS" - ], - "post-update-cmd": [ - "PhantomInstaller\\Installer::installPhantomJS" - ] - } - } - -It is important that you have the 'scripts' section shown above in your -``composer.json`` file as it will install the latest version of -PhantomJS for your system to your project's bin folder. It is -recommended that you create a bin folder in the root of your project as -this is where the PHP PhantomJS library will look for your PhantomJS -executable. If you would prefer to use a PhantomJS executable in a -custom location, see the `Custom Installation <#custom-installation>`__ -section. - -Finally, install the composer depedencies for your project: - -.. code:: shell - - $ php composer.phar install - -Custom Installation -------------------- - -If you would prefer to use a custom install location for the PhantomJS -executable, you simply need to tell the client where to find the -executable file: - -.. code:: php - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - $client->setPhantomJs('/path/to/phantomjs'); - -.. important:: - The PHP PhantomJS library also requires a `phantomloader` file that comes bundled with the library and is installed to the bin folder defined in your `composer.json` file. If you are setting a custom path to the PhantomJS executable, you need to make sure that the `phantomloader` file can be found in the bin folder it was installed to. - -If you would like composer to install all executable files to a custom bin location when installing dependencies, set the bin dir location in your project's `composer.json` file: - -.. code:: yaml - - { - "config": { - "bin-dir": "/path/to/your/projects/bin/dir" - } - } - -You will need to make sure that this directory exists and is writable by -Composer before running the composer install. - -Once you have updated your bin location run composer install to install -PhantomJS: - -.. code:: shell - - $ php composer.phar install - -This should install the correct PhantomJS executable for your system and the required `phantomloader` file to the bin locaiton you defined in your `composer.json` file. - -Now you need to tell the client where to find your bin folder: - -.. code:: php - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - $client->setBinDir('/path/to/bin/dir'); - -Installing from tarball ------------------------ - -The PHP PhantomJS library contains several depedencies in order to -function so it is recommended that you install it via composer as this -will handle your dependencies for you. If you do wish to install it from -a `tarball release `__ -then you will need to install the dependencies manually. - -The PHP PhantomJS library currently requires the following depdencies: - -- `Symfony Config Component `__ ~2.5 -- `Symfony Dependency Injection - Component `__ ~2.5 -- `Symfony Filesystem - Component `__ ~2.5 -- `Twig templating Component `__ ~1.16 -- `PhantomJS `__ ~1.9 - -Make sure the components are in your include path and that the PhantomJS -executable is installed to your projects bin folder as mentioned in the -`Custom Installation <#custom-installation>`__ section. \ No newline at end of file diff --git a/doc/intro.rst b/doc/intro.rst deleted file mode 100644 index 79ffd1b..0000000 --- a/doc/intro.rst +++ /dev/null @@ -1,129 +0,0 @@ -Introduction -============ - -| PHP PhantomJS is a flexible PHP library to load pages through the -PhantomJS -| headless browser and return the page response. It is handy for testing -| websites that demand javascript support and also supports screen -captures. - -Feature List ------------- - -- Load webpages through the PhantomJS headless browser -- View detailed response data including page content, headers, status - code etc. -- Handle redirects -- View javascript console errors -- View detailed PhantomJS debuged information -- Save screen captures to local disk -- Define screen capture x, y, width and height parameters -- Set viewport size -- Delay page rendering for a specified time -- Execute PhantomJS with command line options -- Easily build and run custom PhantomJS scripts - -Prerequisites -------------- - -PHP PhantomJS requires PHP **5.3.0** or greater to run. - -Installation ------------- - -It is recommended that you use Composer to install PHP PhantomJS. First, -add the following to your project’s ``composer.json`` file: - -.. code:: xml - - "scripts": { - "post-install-cmd": [ - "PhantomInstaller\\Installer::installPhantomJS" - ], - "post-update-cmd": [ - "PhantomInstaller\\Installer::installPhantomJS" - ] - } - -This will ensure the latest version of PhantomJS is installed for your -system, in your bin folder. If you haven’t defined your bin folder in -your composer.json, add the path: - -.. code:: xml - - "config": { - "bin-dir": "bin" - } - -Finally, install PHP PhantomJS from the root of your project: - -.. code:: shell - - $ composer require "jonnyw/php-phantomjs:3.*" - -If you would like to use another installation method or would like to -see more detailed installation instructions, see the `installation `__ -documentation. - -Basic Usage ------------ - -The following illustrates how to make a basic GET request and output the -page content: - -.. code:: php - - getMessageFactory()->createRequest('http://google.com', 'GET'); - - /** - * @see JonnyW\PhantomJs\Message\Response - **/ - $response = $client->getMessageFactory()->createResponse(); - - // Send the request - $client->send($request, $response); - - if($response->getStatus() === 200) { - - // Dump the requested page content - echo $response->getContent(); - } - -And if you would like to save a screen capture to local disk: - -.. code:: php - - getMessageFactory()->createCaptureRequest('http://google.com', 'GET'); - $request->setCaptureFile('/path/to/save/capture/file.jpg'); - - /** - * @see JonnyW\PhantomJs\Message\Response - **/ - $response = $client->getMessageFactory()->createResponse(); - - // Send the request - $client->send($request, $response); - -For more detailed examples see the `usage`_ section, or to create -your own custom scripts check out the `advanced`_ documentation. - -.. _usage: https://github.com/jonnnnyw/php-phantomjs/blob/master/doc/usage.rst -.. _advanced: https://github.com/jonnnnyw/php-phantomjs/blob/master/doc/advanced.rst diff --git a/doc/troubleshooting.rst b/doc/troubleshooting.rst deleted file mode 100644 index 943dfed..0000000 --- a/doc/troubleshooting.rst +++ /dev/null @@ -1,372 +0,0 @@ -Troubleshooting -=============== - -- `It's not installing anything to my bin - directory <#its-not-installing-anything-to-my-bin-directory>`__ -- `I am getting a InvalidExecutableException when making a - request <#i-am-getting-a-invalidexecutableexception-when-making-a-request>`__ -- `I am getting a NotWritableException when making a - request <#i-am-getting-a-notwritableexception-when-making-a-request>`__ -- `Why do I need the phantomloader - file? <#why-do-i-need-the-phantomloader-file>`__ -- `Why am I getting a status code of 0 in the - response? <#why-am-i-getting-a-status-code-of-0-in-the-response>`__ -- `It's not saving my screenshots <#its-not-saving-my-screenshots>`__ -- `Can I set the screenshot size? <#can-i-set-the-screenshot-size>`__ -- `Can I set the viewport size? <#can-i-set-the-viewport-size>`__ -- `How do I debug a request? <#how-do-i-debug-a-request>`__ -- `I am getting SyntaxError: Parse error in the debug - log <#i-am-getting-syntaxerror-parse-error-in-the-debug-log>`__ - -It's not installing anything to my bin directory -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When installing via composer, as outlined in the `installation -guide `__, it is recommended -that you define the location of the bin folder for your project. This -can be done by adding the following to your ``composer.json`` file: - -.. code:: yaml - - #composer.json - - { - "config": { - "bin-dir": "/path/to/your/projects/bin/dir" - } - } - -You need to make sure that this directory exists and is writable before -you install your composer depedencies. - -Once you have defined your bin folder in your ``composer.json`` file, -run composer install from the root of your project: - -.. code:: shell - - #bash - - $ php composer.phar install - -This should install 2 files to your bin folder: ``phantomjs`` and -``phantomloader``. If you do not have these 2 files in your bin folder -then check that the folder is writable and run composer install again. - -.. important:: - If you do not define a bin directory in your ``composer.json`` file - then the default install location will be ``vendor/bin/``. If you - choose to not set a bin folder path then you will need to make sure - that this path is set in the client by calling - ``$client->setBinDir('vendor/bin');`` before making a request. - -I am getting a ``InvalidExecutableException`` when making a request -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -If you have installed via composer, as outlined in the `installation -guide `__, then you should -have 2 files installed in either the ``bin`` or ``vendor/bin/`` -directory, in the root of your project. These files are called -``phantomjs`` and ``phantomloader``. - -Check that these files exist and are executable by your application. If -they do not exist, see `It's not installing anything to my bin -directory <#its-not-installing-anything-to-my-bin-directory>`__. - -If the PHP PhantomJS library cannot locate either of these files then it -will throw a ``InvalidExecutableException``. The message in the -exception should tell you which one it can't execute. If both of these -files exist and they are executable by your application, you may need to -set the path to the directory that these files live in before making a -request: - -.. code:: php - - setBinDir('/path/to/bin/dir'); - -I am getting a ``NotWritableException`` when making a request -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When making a request, the PHP PhantomJS library compiles a temporary -script file to your system's tmp folder. The location of this folder is -determined through the use of the ``sys_get_temp_dir()`` function. If -this directory is not writable by your application then you will receive -this exception. - -Why do I need the ``phantomloader`` file? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A proxy loader file is used get around a quirk that PhantomJS has when -it encounters a syntax error in a script file. By default, if PhantomJS -encounters a syntax error when loading a script file it will not exit -execution. This means that PHP PhantomJS will continue to wait for a -response from PhantomJS until PHP reaches its script execution timeout -period. This also means you won't get any debug information informing -you that the PhantomJS script has a syntax error. - -To get around this, script files are loaded through a loader script. -This handles the event of a syntax error and ensures that PhantomJS -exits when an error is encountered. - -The ``phantomloader`` file is required in order for the PHP PhantomJS -library to run so please make sure that it was installed to your bin -folder and is readable by your application. - -Another reason for getting this exception is when you are trying to save -screenshots. See `It's not saving my -screenshots <#its-not-saving-my-screenshots>`__. - -Why am I getting a status code of 0 in the response? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A status code of 0 in the response object generally means the request -did not complete successfully. This could mean that the URL you are -requesting did not return a response or that something happened when -making the request that did not raise an error in the PHP PhantomJS -library. - -Becuase and exception was not thrown, chances are the issue is with -PhantomJS itself or at the endpoint you are calling. - -One possible reason for this is that your request has timed out before a -response was returned from the endpoint that you are requesting. -Depending on what you are requesting, some websites seem to take a while -to return a response. An example of this is -`myspace.com `__ which, at the time of writing -this, takes a considerable amount of time resolve through PhantomJS. - -To work around this you can try increasing the timeout period in the PHP -PhantomJS client: - -.. code:: php - - getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $timeout = 20000; // 20 seconds - - $request->setTimeout($timeout); - - $client->send($request, $response); - -If you are still having a problem then you should enable debugging, -before you make the request, and check the debug log. This contains a -dump of information from PhantomJS which could help to track down why -you are not getting a response. - -.. code:: php - - debug(true); // Set debug flag - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - - echo $client->getLog(); // Output log - -You can also try running a test script through your PhantomJS -executable, from the command line, to see if you get a valid response -back. Save the following script somewhere: - -.. code:: javascript - - //test-script.js - - var page = require('webpage').create(), - url = 'YOUR REQUEST URL', // Change this to the URL you want to request - response; - - page.onResourceReceived = function (r) { - response = r; - }; - - phantom.onError = function(msg, trace) { - - console.log(msg); - console.log(trace); - phantom.exit(1); - }; - - page.open (url, 'GET', '', function (status) { - - console.log(status); - console.log(JSON.stringify(response)); - phantom.exit(); - }); - -And then, assuming you have saved the script above to ``test-script.js`` -in the root of your project and your PhantomJS executable is located at -``bin/phantomjs``, run the following: - -.. code:: shell - - #bash - - $ bin/phantomjs ./test-script.js - -You should see an output of the response from PhantomJS: - -.. code:: shell - - #bash - - success - {"contentType":"text/javascript; charset=UTF-8", "headers": ... - - -If you don't see ``success`` followed by a JSON encoded response object -then there is something the with the URL you are requesting or your -PhantomJS executable. Try reinstalling PhantomJS. If you see ``fail`` -instead of ``success``, chances are the URL you are requesting is -invalid or not resolving. - -It's not saving my screenshots -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When making a capture request you need to make sure that you are setting -the file location that you want the screenshot saved to, including the -filename: - -.. code:: php - - getMessageFactory()->createCaptureRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $file = '/path/to/save/your/screen/capture/file.jpg'; - - $request->setCaptureFile($file); // Set the capture file - - $client->send($request, $response); - -The file itself does not need to exist but the parent directory must -exist and be writable by your application. Check that your application -has permissions to write files to the directory you are setting for your -screen captures. - -Can I set the screenshot size? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Yes, you can set the width and height of your capture along with the x -and y coordinates of where the capture should start from: - -.. code:: php - - getMessageFactory()->createCaptureRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $file = '/path/to/save/your/screen/capture/file.jpg'; - - $top = 10; - $left = 10; - $width = 200; - $height = 400; - - $request->setCaptureFile($file); - $request->setCaptureDimensions($width, $height, $top, $left); - - $client->send($request, $response); - -Can I set the viewport size? -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Yes, you can set the viewport dimensions on both regular and capture -requests: - -.. code:: php - - getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $width = 200; - $height = 400; - - $request->setViewportSize($width, $height); // Set viewport size - - $client->send($request, $response); - -How do I debug a request? -~~~~~~~~~~~~~~~~~~~~~~~~~ - -By setting the debug flag to ``true`` on the client, you can get a dump -of information output from PhantomJS along with some info events added -by the PHP PhantomJS library: - -.. code:: php - - debug(true); // Set debug flag - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - - echo $client->getLog(); // Output log - -You can also get any javacript console errors along with a stack trace -from the URL you are calling, in the response object: - -.. code:: php - - getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - - var_dump($response->getConsole()); // Outputs array of console errors and stack trace - -I am getting ``SyntaxError: Parse error`` in the debug log -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You will only get this error if the script file that is being run by -PhantomJS has a syntax error. If you are writing your own `custom -scripts `__ -then try setting the `debug flag <#how-do-i-debug-a-request>`__ which -*should* print some more detailed information in the debug log. Also -check that you aren't setting any parameters to ``null`` in your request -object as this could be causing a javascript error due to javascript -variables being set to nothing e.g. ``var width = ,``. \ No newline at end of file diff --git a/doc/usage.rst b/doc/usage.rst deleted file mode 100644 index 5f5d866..0000000 --- a/doc/usage.rst +++ /dev/null @@ -1,315 +0,0 @@ -Usage -===== - -This page contains some common examples of how to use the PHP PhantomJS -library. - -- `Basic Request <#basic-request>`__ -- `POST Request <#post-request>`__ -- `Other Request Methods <#other-request-methods>`__ -- `Response Data <#response-data>`__ -- `Screen Captures <#screen-captures>`__ -- `Set Viewport Size <#set-viewport-size>`__ -- `Custom Timeout <#custom-timeout>`__ -- `Delay Page Render <#delay-page-render>`__ -- `Custom Run Options <#custom-run-options>`__ - -Basic Request -------------- - -A basic GET request: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createRequest(); - $response = $client->getMessageFactory()->createResponse(); - - $request->setMethod('GET'); - $request->setUrl('http://google.com'); - - $client->send($request, $response); - - if($response->getStatus() === 200) { - echo $response->getContent(); - } - -You can also set the URL, request method and timeout period when -creating a new request instance through the message factory: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createRequest('http://google.com', 'GET', 5000); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - - if($response->getStatus() === 200) { - echo $response->getContent(); - } - -POST Request ------------- - -A basic POST request: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createRequest(); - $response = $client->getMessageFactory()->createResponse(); - - $data = array( - 'param1' => 'Param 1', - 'param2' => 'Param 2' - ); - - $request->setMethod('POST'); - $request->setUrl('http://google.com'); - $request->setRequestData($data); // Set post data - - $client->send($request, $response); - -Other Request Methods ---------------------- - -The PHP PhantomJS library supports the following request methods: - -- OPTIONS -- GET -- HEAD -- POST -- PUT -- DELETE -- PATCH - -The request method can be set when creating a new request instance -through the message factory: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createRequest('http://google.com', 'PUT'); - -Or on the request instance itself: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createRequest(); - $request->setMethod('PATCH'); - -Response Data -------------- - -A standard response gives you access to the following interface: - -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| Accessor | Description | Return Type | -+=========================+=============================================================================================+===============+ -| getHeaders() | Returns an array of all response headers. | Array | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getHeader(\ *header*) | Returns the value for a specific response header e.g. Content-Type. | Mixed | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getStatus() | The response status code e.g. 200. | Int | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getContent() | The raw page content of the requested page. | String | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getContentType() | The content type of the requested page. | String | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getUrl() | The URL of the requested page. | String | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getRedirectUrl() | If the response was a redirect, this will return the redirect URL. | String | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| isRedirect() | Will return true if the response was a redirect or false otherwise. | Boolean | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ -| getConsole() | Returns an array of any javascript errors on the requested page along with a stack trace. | Array | -+-------------------------+---------------------------------------------------------------------------------------------+---------------+ - -If the response contains a status code of 0, chances are the request -failed. Check the request `debug -log `__ -for more detailed information about what may have gone wrong. - -Screen Captures ---------------- - -You can save screen captures of a page to your local disk by creating a -screen capture request and setting the path you wish to save the file -to: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createCaptureRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $file = '/path/to/save/your/screen/capture/file.jpg'; - - $request->setCaptureFile($file); - - $client->send($request, $response); - -You will need to make sure the directory that you are saving the file to -exists and is writable by your application. - -You can also set the width, height, x and y axis for your screen -capture: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createCaptureRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $file = '/path/to/save/your/screen/capture/file.jpg'; - - $top = 10; - $left = 10; - $width = 200; - $height = 400; - - $request->setCaptureFile($file); - $request->setCaptureDimensions($width, $height, $top, $left); - - $client->send($request, $response); - -Set Viewport Size ------------------ - -You can easily set the viewport size for a request: - -.. code:: php - - getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $width = 200; - $height = 400; - - $request->setViewportSize($width, $height); - - $client->send($request, $response); - -Custom Timeout --------------- - -By default, each request will timeout after 5 seconds. You can set a -custom timeout period (in milliseconds) for each request: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $timeout = 10000; // 10 seconds - - $request->setTimeout($timeout); - - $client->send($request, $response); - -Delay Page Render ------------------ - -Sometimes when taking screen captures you may want to wait until the -page is completely loaded before saving the capture. In this instance -you can set a page render delay (in seconds) for the request: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - - $request = $client->getMessageFactory()->createCaptureRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $delay = 5; // 5 seconds - - $request->setDelay($delay); - - $client->send($request, $response); - -You can set a page render delay for standard requests also. - -Custom Run Options ------------------- - -The PhantomJS API contains a range of command line options that can be -passed when executing the PhantomJS executable. These can also be passed -in via the client before a request: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - $client->addOption('--load-images=true'); - $client->addOption('--ignore-ssl-errors=true'); - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - -You can also set a path to a JSON configuration file that contains -multiple PhantomJS options: - -.. code:: php - - - use JonnyW\PhantomJs\Client; - - $client = Client::getInstance(); - $client->addOption('--config=/path/to/config.json'); - - $request = $client->getMessageFactory()->createRequest('http://google.com'); - $response = $client->getMessageFactory()->createResponse(); - - $client->send($request, $response); - -See the `PhantomJS -Documentation `__ for a full -list of command line options. \ No newline at end of file diff --git a/examples/basic-request.php b/examples/basic-request.php deleted file mode 100644 index d569bab..0000000 --- a/examples/basic-request.php +++ /dev/null @@ -1,17 +0,0 @@ -getMessageFactory()->createRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$request->setMethod('GET'); -$request->setUrl('http://google.com'); - -$client->send($request, $response); - -var_dump($response); \ No newline at end of file diff --git a/examples/capture-request.php b/examples/capture-request.php deleted file mode 100644 index 89d6f53..0000000 --- a/examples/capture-request.php +++ /dev/null @@ -1,31 +0,0 @@ -getMessageFactory()->createCaptureRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$top = 10; -$left = 10; -$width = 200; -$height = 400; - -$request->setMethod('GET'); -$request->setUrl('http://google.com'); -$request->setCaptureFile(sprintf('%s/file.jpg', sys_get_temp_dir())); -$request->setCaptureDimensions($width, $height, $top, $left); - -$client->send($request, $response); - -var_dump($response); - -// If the capture dimensions were applied -// to the request, you will see an information -// notice in the debug log. This is useful for -// debugging captures and will always be present, -// even if debug mode is disabled. -var_dump($client->getLog()); \ No newline at end of file diff --git a/examples/custom-phantomjs-location.php b/examples/custom-phantomjs-location.php deleted file mode 100644 index a22e9fc..0000000 --- a/examples/custom-phantomjs-location.php +++ /dev/null @@ -1,8 +0,0 @@ -setPhantomJs('/path/to/phantomjs'); // PhantomJS executbale file path \ No newline at end of file diff --git a/examples/custom-script.php b/examples/custom-script.php deleted file mode 100644 index 0722041..0000000 --- a/examples/custom-script.php +++ /dev/null @@ -1,42 +0,0 @@ -get('procedure_loader_factory'); -$procedureLoader = $procedureLoaderFactory->createProcedureLoader($filePath); // Set the path to your custom procedure(s) - -$client = Client::getInstance(); -$client->getProcedureLoader()->addLoader($procedureLoader); // Add new loader with path to you procedures to the chain loader - -$request = $client->getMessageFactory()->createRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$request->setType($fileName); // Set the request type to the name of your procedure you want to execute for this request - -$client->send($request, $response); - -var_dump($response); - -// If your debug log contains 'SyntaxError: Parse error' -// then your custom procedure has a javascript error. Try -// setting $client->debug(true) before making your request -// to get more information about your error. -var_dump($client->getLog()); \ No newline at end of file diff --git a/examples/debug-request.php b/examples/debug-request.php deleted file mode 100644 index a166f45..0000000 --- a/examples/debug-request.php +++ /dev/null @@ -1,21 +0,0 @@ -debug(true); // Set debug flag - -$request = $client->getMessageFactory()->createRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$request->setMethod('GET'); -$request->setUrl('http://google.com'); - -$client->send($request, $response); - -// The PhantomJS executable log. Will contain -// any script parse errors, script info and -// anything else PhantomJS outputs in debug mode. -var_dump($client->getLog()); \ No newline at end of file diff --git a/examples/delay-page-render.php b/examples/delay-page-render.php deleted file mode 100644 index 1cc722a..0000000 --- a/examples/delay-page-render.php +++ /dev/null @@ -1,28 +0,0 @@ -getMessageFactory()->createCaptureRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$delay = 5; // Seconds - -$request->setMethod('GET'); -$request->setUrl('http://google.com'); -$request->setCaptureFile(sprintf('%s/file.jpg', sys_get_temp_dir())); -$request->setDelay($delay); - -$client->send($request, $response); - -var_dump($response); - -// A debug info notice will be written to -// the log when the page render delay starts -// and when the page render executes. This is -// useful for debugging page render delay and -// will always be present, even if debug is disabled. -var_dump($client->getLog()); \ No newline at end of file diff --git a/examples/javascript-console.php b/examples/javascript-console.php deleted file mode 100644 index c9d4726..0000000 --- a/examples/javascript-console.php +++ /dev/null @@ -1,21 +0,0 @@ -getMessageFactory()->createRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$request->setMethod('GET'); -$request->setUrl('http://google.com'); - -$client->send($request, $response); - -// Any javascript errors that show up in -// the browser console will appear in -// response console data along with stack -// trace. console.log() data will not be present. -var_dump($response->getConsole()); \ No newline at end of file diff --git a/examples/post-request.php b/examples/post-request.php deleted file mode 100644 index 4eda900..0000000 --- a/examples/post-request.php +++ /dev/null @@ -1,23 +0,0 @@ -getMessageFactory()->createRequest(); -$response = $client->getMessageFactory()->createResponse(); - -$data = array( - 'param1' => 'Param 1', - 'param2' => 'Param 2' -); - -$request->setMethod('POST'); -$request->setUrl('http://google.com'); -$request->setRequestData($data); // Set post data - -$client->send($request, $response); - -var_dump($response); \ No newline at end of file From 69318519beb2aaba5070111fa4cce866ae464616 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:58:09 +0000 Subject: [PATCH 11/54] Updaitng README --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 13c3587..af6a8dd 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,9 @@ PHP PhantomJS ============= +> #### Important +> Currently when installing PHP PhantomJS on **Linux OS** you will need to compile your own version of PhantomJS for your system. This is due to an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with the PhantomJS Linux packages. An Ubuntu compiled version will be installed by default but this may not be compatible with your system. + PHP PhantomJS is a flexible PHP library to load pages through the PhantomJS headless browser and return the page response. It is handy for testing websites that demand javascript support and also supports screen captures. From 62921eae3954d388eef1b4746a80a2bee261a6fb Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:58:45 +0000 Subject: [PATCH 12/54] Updaitng README --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index af6a8dd..5105162 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ PHP PhantomJS ============= -> #### Important -> Currently when installing PHP PhantomJS on **Linux OS** you will need to compile your own version of PhantomJS for your system. This is due to an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with the PhantomJS Linux packages. An Ubuntu compiled version will be installed by default but this may not be compatible with your system. - PHP PhantomJS is a flexible PHP library to load pages through the PhantomJS headless browser and return the page response. It is handy for testing websites that demand javascript support and also supports screen captures. +> #### Important +> Currently when installing PHP PhantomJS on **Linux OS** you will need to compile your own version of PhantomJS for your system. This is due to an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with the PhantomJS Linux packages. An Ubuntu compiled version will be installed by default but this may not be compatible with your system. + [Full Documentation](http://jonnnnyw.github.io/php-phantomjs/) [![Total Downloads](https://poser.pugx.org/jonnyw/php-phantomjs/downloads.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Latest Stable Version](https://poser.pugx.org/jonnyw/php-phantomjs/v/stable.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Build Status](https://travis-ci.org/jonnnnyw/php-phantomjs.png?branch=master)](https://travis-ci.org/jonnnnyw/php-phantomjs) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/quality-score.png?s=631d32fa1fbb9300eb84b9b52702c7ffeac046a1)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) [![Code Coverage](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/coverage.png?s=893b5997da45448e32983b8568a39630b0b2d91b)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) From 0dd39438fb766bff14e37f5d8682bb2f66aba54b Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 11:59:03 +0000 Subject: [PATCH 13/54] Updaitng README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5105162..201a266 100644 --- a/README.md +++ b/README.md @@ -5,11 +5,11 @@ PHP PhantomJS is a flexible PHP library to load pages through the PhantomJS headless browser and return the page response. It is handy for testing websites that demand javascript support and also supports screen captures. +[Full Documentation](http://jonnnnyw.github.io/php-phantomjs/) + > #### Important > Currently when installing PHP PhantomJS on **Linux OS** you will need to compile your own version of PhantomJS for your system. This is due to an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with the PhantomJS Linux packages. An Ubuntu compiled version will be installed by default but this may not be compatible with your system. -[Full Documentation](http://jonnnnyw.github.io/php-phantomjs/) - [![Total Downloads](https://poser.pugx.org/jonnyw/php-phantomjs/downloads.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Latest Stable Version](https://poser.pugx.org/jonnyw/php-phantomjs/v/stable.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Build Status](https://travis-ci.org/jonnnnyw/php-phantomjs.png?branch=master)](https://travis-ci.org/jonnnnyw/php-phantomjs) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/quality-score.png?s=631d32fa1fbb9300eb84b9b52702c7ffeac046a1)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) [![Code Coverage](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/coverage.png?s=893b5997da45448e32983b8568a39630b0b2d91b)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) Feature List From def95fc99092a28ac445fb0bb4e207bd6f2a5e0a Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 12:00:14 +0000 Subject: [PATCH 14/54] Updaitng README --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 201a266..26d54cf 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,8 @@ websites that demand javascript support and also supports screen captures. > #### Important > Currently when installing PHP PhantomJS on **Linux OS** you will need to compile your own version of PhantomJS for your system. This is due to an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with the PhantomJS Linux packages. An Ubuntu compiled version will be installed by default but this may not be compatible with your system. + + [![Total Downloads](https://poser.pugx.org/jonnyw/php-phantomjs/downloads.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Latest Stable Version](https://poser.pugx.org/jonnyw/php-phantomjs/v/stable.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Build Status](https://travis-ci.org/jonnnnyw/php-phantomjs.png?branch=master)](https://travis-ci.org/jonnnnyw/php-phantomjs) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/quality-score.png?s=631d32fa1fbb9300eb84b9b52702c7ffeac046a1)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) [![Code Coverage](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/coverage.png?s=893b5997da45448e32983b8568a39630b0b2d91b)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) Feature List From 406a6f9f7bf5e769af38b3a2fb3af9aa4ab70441 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 13:26:08 +0000 Subject: [PATCH 15/54] Bumping dependency versions --- composer.json | 8 +- .../PhantomJs/Resources/config/services.yml | 90 +++++++++---------- 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/composer.json b/composer.json index d5c2bbe..eaf8389 100644 --- a/composer.json +++ b/composer.json @@ -14,10 +14,10 @@ "minimum-stability": "stable", "require": { "php": ">=5.3.0", - "symfony/config": "~2.3", - "symfony/dependency-injection": "~2.3", - "symfony/filesystem": "~2.3", - "symfony/yaml": "~2.3", + "symfony/config": "~3.0", + "symfony/dependency-injection": "~3.0", + "symfony/filesystem": "~3.0", + "symfony/yaml": "~3.0", "twig/twig": "~1.16", "jakoch/phantomjs-installer": "2.0.0" }, diff --git a/src/JonnyW/PhantomJs/Resources/config/services.yml b/src/JonnyW/PhantomJs/Resources/config/services.yml index c4da236..f97551b 100644 --- a/src/JonnyW/PhantomJs/Resources/config/services.yml +++ b/src/JonnyW/PhantomJs/Resources/config/services.yml @@ -8,7 +8,7 @@ services: alias: phantomjs.engine phantomjs.engine: - class: %phantomjs.engine.class% + class: "%phantomjs.engine.class%" ################## ### PROCEDURES ### @@ -27,53 +27,53 @@ services: alias: phantomjs.procedure.procedure_loader_factory phantomjs.procedure.file_locator: - class: %phantomjs.loader.file_locator.class% + class: "%phantomjs.loader.file_locator.class%" arguments: - - %phantomjs.procedure_dir% + - "%phantomjs.procedure_dir%" public: false phantomjs.procedure.procedure_loader: - class: %phantomjs.procedure.procedure_loader.class% + class: "%phantomjs.procedure.procedure_loader.class%" arguments: - - @phantomjs.procedure.procedure_factory - - @phantomjs.procedure.file_locator + - "@phantomjs.procedure.procedure_factory" + - "@phantomjs.procedure.file_locator" public: false phantomjs.procedure.chain_loader: - class: %phantomjs.procedure.chain_loader.class% + class: "%phantomjs.procedure.chain_loader.class%" arguments: - - [ @phantomjs.procedure.procedure_loader ] + - [ "@phantomjs.procedure.procedure_loader" ] public: false phantomjs.procedure.procedure_factory: - class: %phantomjs.procedure.procedure_factory.class% + class: "%phantomjs.procedure.procedure_factory.class%" arguments: - - @engine - - @phantomjs.parser.json_parser - - @phantomjs.cache.file_cache - - @phantomjs.template.template_renderer + - "@engine" + - "@phantomjs.parser.json_parser" + - "@phantomjs.cache.file_cache" + - "@phantomjs.template.template_renderer" public: false phantomjs.procedure.procedure_loader_factory: - class: %phantomjs.procedure.procedure_loader_factory.class% + class: "%phantomjs.procedure.procedure_loader_factory.class%" arguments: - - @phantomjs.procedure.procedure_factory + - "@phantomjs.procedure.procedure_factory" public: false phantomjs.procedure.procedure_compiler: - class: %phantomjs.procedure.procedure_compiler.class% + class: "%phantomjs.procedure.procedure_compiler.class%" arguments: - - @procedure_loader - - @procedure_validator - - @phantomjs.cache.file_cache - - @phantomjs.procedure.template_renderer + - "@procedure_loader" + - "@procedure_validator" + - "@phantomjs.cache.file_cache" + - "@phantomjs.procedure.template_renderer" public: false phantomjs.procedure.procedure_validator: - class: %phantomjs.procedure.procedure_validator.class% + class: "%phantomjs.procedure.procedure_validator.class%" arguments: - - @procedure_loader - - @validator + - "@procedure_loader" + - "@validator" public: false ############ @@ -84,7 +84,7 @@ services: alias: phantomjs.http.message_factory phantomjs.http.message_factory: - class: %phantomjs.http.message_factory.class% + class: "%phantomjs.http.message_factory.class%" public: false ################ @@ -92,7 +92,7 @@ services: ################ phantomjs.parser.json_parser: - class: %phantomjs.parser.json_parser.class% + class: "%phantomjs.parser.json_parser.class%" public: false ################### @@ -103,16 +103,16 @@ services: alias: phantomjs.validator.esprima phantomjs.validator.file_locator: - class: %phantomjs.loader.file_locator.class% + class: "%phantomjs.loader.file_locator.class%" arguments: - - %phantomjs.validator_dir% + - "%phantomjs.validator_dir%" public: false phantomjs.validator.esprima: - class: %phantomjs.validator.esprima.class% + class: "%phantomjs.validator.esprima.class%" arguments: - - @phantomjs.validator.file_locator - - %phantomjs.validator_engine% + - "@phantomjs.validator.file_locator" + - "%phantomjs.validator_engine%" public: false ################## @@ -120,39 +120,39 @@ services: ################## phantomjs.template.template_renderer: - class: %phantomjs.template.template_renderer.class% + class: "%phantomjs.template.template_renderer.class%" arguments: - - @phantomjs.twig.environment + - "@phantomjs.twig.environment" public: false phantomjs.twig.environment: - class: %phantomjs.twig.environment.class% + class: "%phantomjs.twig.environment.class%" arguments: - - @phantomjs.twig.string_loader + - "@phantomjs.twig.string_loader" public: false phantomjs.twig.string_loader: - class: %phantomjs.twig.string_loader.class% + class: "%phantomjs.twig.string_loader.class%" public: false phantomjs.procedure.template_renderer: - class: %phantomjs.template.template_renderer.class% + class: "%phantomjs.template.template_renderer.class%" arguments: - - @phantomjs.procedure.twig.environment + - "@phantomjs.procedure.twig.environment" public: false phantomjs.procedure.twig.environment: - class: %phantomjs.twig.environment.class% + class: "%phantomjs.twig.environment.class%" arguments: - - @phantomjs.twig.string_loader + - "@phantomjs.twig.string_loader" public: false calls: - - [ "setLexer", [ @phantomjs.procedure.twig.lexer ] ] + - [ "setLexer", [ "@phantomjs.procedure.twig.lexer" ] ] phantomjs.procedure.twig.lexer: - class: %phantomjs.twig.lexer.class% + class: "%phantomjs.twig.lexer.class%" arguments: - - @phantomjs.procedure.twig.environment + - "@phantomjs.procedure.twig.environment" - { tag_variable: [ "[[", "]]" ], tag_comment: [ "[#", "#]" ], tag_block: [ "[%", "%]" ], interpolation: [ "#[", "]" ] } public: false @@ -161,8 +161,8 @@ services: ################## phantomjs.cache.file_cache: - class: %phantomjs.cache.file_cache.class% + class: "%phantomjs.cache.file_cache.class%" arguments: - - %phantomjs.cache_dir% - - %phantomjs.procedure_extension% + - "%phantomjs.cache_dir%" + - "%phantomjs.procedure_extension%" public: false From a2f676adf271bd7f1983fd0eca22b9344b02989f Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 17 Dec 2015 13:33:40 +0000 Subject: [PATCH 16/54] Dropping dependency versions --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index eaf8389..d5c2bbe 100644 --- a/composer.json +++ b/composer.json @@ -14,10 +14,10 @@ "minimum-stability": "stable", "require": { "php": ">=5.3.0", - "symfony/config": "~3.0", - "symfony/dependency-injection": "~3.0", - "symfony/filesystem": "~3.0", - "symfony/yaml": "~3.0", + "symfony/config": "~2.3", + "symfony/dependency-injection": "~2.3", + "symfony/filesystem": "~2.3", + "symfony/yaml": "~2.3", "twig/twig": "~1.16", "jakoch/phantomjs-installer": "2.0.0" }, From b9cc9fd683ef2023cd4be249dd0b314134409d0c Mon Sep 17 00:00:00 2001 From: Thiery Laverdure Date: Sun, 24 Jan 2016 20:17:46 -0500 Subject: [PATCH 17/54] Added the procedure compiler to the Client class to match instructions in docs. http://jonnnnyw.github.io/php-phantomjs/4.0/caching/ --- src/JonnyW/PhantomJs/Client.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/JonnyW/PhantomJs/Client.php b/src/JonnyW/PhantomJs/Client.php index 0fb0e3e..46ac37e 100644 --- a/src/JonnyW/PhantomJs/Client.php +++ b/src/JonnyW/PhantomJs/Client.php @@ -197,4 +197,15 @@ public function getProcedure() { return $this->procedure; } + + /** + * Get procedure compiler. + * + * @access public + * @return \JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface + */ + public function getProcedureCompiler() + { + return $this->procedureCompiler; + } } From 789f757ab1812de843a168e13185b841b057156c Mon Sep 17 00:00:00 2001 From: Thiery Laverdure Date: Sun, 24 Jan 2016 21:01:42 -0500 Subject: [PATCH 18/54] Added getters and setters for image capture format and quality to be used on Phantom JS render() http://phantomjs.org/api/webpage/method/render.html --- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 2 + src/JonnyW/PhantomJs/Http/CaptureRequest.php | 131 ++++++++++++------ .../Http/CaptureRequestInterface.php | 39 ++++-- .../procedures/procedure_capture.partial | 12 +- 4 files changed, 131 insertions(+), 53 deletions(-) diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index a778374..0a7e178 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -204,6 +204,8 @@ public function setViewportSize($width, $height) { $this->viewportWidth = (int) $width; $this->viewportHeight = (int) $height; + + return $this; } /** diff --git a/src/JonnyW/PhantomJs/Http/CaptureRequest.php b/src/JonnyW/PhantomJs/Http/CaptureRequest.php index 9b1c21f..9da3b71 100644 --- a/src/JonnyW/PhantomJs/Http/CaptureRequest.php +++ b/src/JonnyW/PhantomJs/Http/CaptureRequest.php @@ -12,7 +12,7 @@ use JonnyW\PhantomJs\Exception\NotWritableException; /** - * PHP PhantomJs + * PHP PhantomJs. * * @author Jon Wenmoth */ @@ -20,10 +20,9 @@ class CaptureRequest extends AbstractRequest implements CaptureRequestInterface { /** - * Request type + * Request type. * * @var string - * @access protected */ protected $type; @@ -31,65 +30,75 @@ class CaptureRequest extends AbstractRequest * File to save output. * * @var string - * @access protected */ protected $outputFile; /** - * Rect top + * Rect top. * * @var int - * @access protected */ protected $rectTop; /** - * Rect left + * Rect left. * * @var int - * @access protected */ protected $rectLeft; /** - * Rect width + * Rect width. * * @var int - * @access protected */ protected $rectWidth; /** - * Rect height + * Rect height. * * @var int - * @access protected */ protected $rectHeight; /** - * Internal constructor + * Capture Format. + * + * @var string + */ + protected $format; + + /** + * Capture Quality. + * + * @var int + */ + protected $quality; + + /** + * Internal constructor. + * + * @param string $url (default: null) + * @param string $method (default: RequestInterface::METHOD_GET) + * @param int $timeout (default: 5000) * - * @access public - * @param string $url (default: null) - * @param string $method (default: RequestInterface::METHOD_GET) - * @param int $timeout (default: 5000) * @return \JonnyW\PhantomJs\Http\CaptureRequest */ public function __construct($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000) { parent::__construct($url, $method, $timeout); - $this->rectTop = 0; - $this->rectLeft = 0; - $this->rectWidth = 0; + $this->rectTop = 0; + $this->rectLeft = 0; + $this->rectWidth = 0; $this->rectHeight = 0; + $this->format = 'jpeg'; + $this->quality = 75; } /** - * Get request type + * Get request type. * - * @access public * @return string */ public function getType() @@ -102,10 +111,10 @@ public function getType() } /** - * Set request type + * Set request type. + * + * @param string $type * - * @access public - * @param string $type * @return \JonnyW\PhantomJs\Http\AbstractRequest */ public function setType($type) @@ -118,19 +127,19 @@ public function setType($type) /** * Set viewport size. * - * @access public - * @param int $width - * @param int $height - * @param int $top (default: 0) - * @param int $left (default: 0) + * @param int $width + * @param int $height + * @param int $top (default: 0) + * @param int $left (default: 0) + * * @return \JonnyW\PhantomJs\Http\AbstractRequest */ public function setCaptureDimensions($width, $height, $top = 0, $left = 0) { - $this->rectWidth = (int) $width; + $this->rectWidth = (int) $width; $this->rectHeight = (int) $height; - $this->rectTop = (int) $top; - $this->rectLeft = (int) $left; + $this->rectTop = (int) $top; + $this->rectLeft = (int) $left; return $this; } @@ -138,7 +147,6 @@ public function setCaptureDimensions($width, $height, $top = 0, $left = 0) /** * Get rect top. * - * @access public * @return int */ public function getRectTop() @@ -149,7 +157,6 @@ public function getRectTop() /** * Get rect left. * - * @access public * @return int */ public function getRectLeft() @@ -160,7 +167,6 @@ public function getRectLeft() /** * Get rect width. * - * @access public * @return int */ public function getRectWidth() @@ -171,7 +177,6 @@ public function getRectWidth() /** * Get rect height. * - * @access public * @return int */ public function getRectHeight() @@ -182,9 +187,10 @@ public function getRectHeight() /** * Set file to save output. * - * @access public - * @param string $file + * @param string $file + * * @throws \JonnyW\PhantomJs\Exception\NotWritableException + * * @return \JonnyW\PhantomJs\Http\CaptureRequest */ public function setOutputFile($file) @@ -201,11 +207,56 @@ public function setOutputFile($file) /** * Get output file. * - * @access public * @return string */ public function getOutputFile() { return $this->outputFile; } + + /** + * Get image format of the capture. + * + * @return string + */ + public function getFormat() + { + return $this->format; + } + + /** + * Set image format of capture. + * options: pdf, png, jpeg, bmp, ppm, gif. + * + * @param string $format + */ + public function setFormat($format) + { + $this->format = $format; + + return $this; + } + + /** + * Get quality of capture. + * + * @return string + */ + public function getQuality() + { + return $this->quality; + } + + /** + * Set quality of the capture. + * example: 0 - 100. + * + * @param int $format + */ + public function setQuality($quality) + { + $this->quality = (int) $quality; + + return $this; + } } diff --git a/src/JonnyW/PhantomJs/Http/CaptureRequestInterface.php b/src/JonnyW/PhantomJs/Http/CaptureRequestInterface.php index 2991d8e..2b41856 100644 --- a/src/JonnyW/PhantomJs/Http/CaptureRequestInterface.php +++ b/src/JonnyW/PhantomJs/Http/CaptureRequestInterface.php @@ -10,7 +10,7 @@ namespace JonnyW\PhantomJs\Http; /** - * PHP PhantomJs + * PHP PhantomJs. * * @author Jon Wenmoth */ @@ -19,7 +19,6 @@ interface CaptureRequestInterface /** * Set viewport size. * - * @access public * @param int $width * @param int $height * @param int $top (default: 0) @@ -30,7 +29,6 @@ public function setCaptureDimensions($width, $height, $top = 0, $left = 0); /** * Get rect top. * - * @access public * @return int */ public function getRectTop(); @@ -38,7 +36,6 @@ public function getRectTop(); /** * Get rect left. * - * @access public * @return int */ public function getRectLeft(); @@ -46,7 +43,6 @@ public function getRectLeft(); /** * Get rect width. * - * @access public * @return int */ public function getRectWidth(); @@ -54,7 +50,6 @@ public function getRectWidth(); /** * Get rect height. * - * @access public * @return int */ public function getRectHeight(); @@ -62,7 +57,6 @@ public function getRectHeight(); /** * Set file to save output. * - * @access public * @param string $file */ public function setOutputFile($file); @@ -70,8 +64,37 @@ public function setOutputFile($file); /** * Get output file. * - * @access public * @return string */ public function getOutputFile(); + + /** + * Get image format of the capture. + * + * @return string + */ + public function getFormat(); + + /** + * Set image format of capture. + * options: pdf, png, jpeg, bmp, ppm, gif. + * + * @param string $format + */ + public function setFormat($format); + + /** + * Get quality of capture. + * + * @return string + */ + public function getQuality(); + + /** + * Set quality of the capture. + * example: 0 - 100. + * + * @param int $format + */ + public function setQuality($quality); } diff --git a/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial b/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial index ac830f5..5450e9d 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial @@ -1,14 +1,17 @@ if (status === 'success') { - + try { - page.render('{{ input.getOutputFile() }}'); - + page.render('{{ input.getOutputFile() }}', { + format: '{{ input.getFormat() }}', + quality: {{ input.getQuality() }}, + }); + response.content = page.evaluate(function () { return document.getElementsByTagName('html')[0].innerHTML }); - + } catch(e) { response.status = 500; @@ -22,4 +25,3 @@ system.stderr.write(debug.join('\\n') + '\\n'); system.stdout.write(JSON.stringify(response, undefined, 4)); phantom.exit(); - From ed03e169c3f9059ef577dd8c3164495f98d2b916 Mon Sep 17 00:00:00 2001 From: Jason Pirkey Date: Fri, 29 Jan 2016 11:14:45 -0500 Subject: [PATCH 19/54] Fixing misnamed method in Unit test. --- src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php index ad4bdce..3dd43e2 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php @@ -486,7 +486,7 @@ public function testRawHeadersCanBeAccessed() * @access public * @return void */ - public function tesNotWritableExceptonIsThrownIfOutputPathIsNotWritable() + public function testNotWritableExceptonIsThrownIfOutputPathIsNotWritable() { $this->setExpectedException('\JonnyW\PhantomJs\Exception\NotWritableException'); From d6ad92b439c2f05bd8230edadcfb5d4cd1f57256 Mon Sep 17 00:00:00 2001 From: Nicholas Woodward Date: Fri, 29 Jan 2016 13:56:26 -0500 Subject: [PATCH 20/54] upgraded phantomjs installer to 2.1.1 - all unit tests pass --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d5c2bbe..ff1e586 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "symfony/filesystem": "~2.3", "symfony/yaml": "~2.3", "twig/twig": "~1.16", - "jakoch/phantomjs-installer": "2.0.0" + "jakoch/phantomjs-installer": "2.1.1" }, "require-dev": { "phpunit/phpunit": "~4.0", From 3ae8d8406323476759e9ec9c4ce3e35842f7e075 Mon Sep 17 00:00:00 2001 From: Nicholas Woodward Date: Sun, 31 Jan 2016 09:25:41 -0500 Subject: [PATCH 21/54] include minor and patch updates to phantomjs-installer --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index ff1e586..dd59e71 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "symfony/filesystem": "~2.3", "symfony/yaml": "~2.3", "twig/twig": "~1.16", - "jakoch/phantomjs-installer": "2.1.1" + "jakoch/phantomjs-installer": "~2.1" }, "require-dev": { "phpunit/phpunit": "~4.0", From 3a9e11e0190b2632f0caad24c912a6c3a6bd55de Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 2 Feb 2016 09:22:55 +1300 Subject: [PATCH 22/54] Upgrading PhantomJS to version 2.1.1 --- README.md | 5 ----- composer.json | 6 ------ 2 files changed, 11 deletions(-) diff --git a/README.md b/README.md index 26d54cf..13c3587 100644 --- a/README.md +++ b/README.md @@ -7,11 +7,6 @@ websites that demand javascript support and also supports screen captures. [Full Documentation](http://jonnnnyw.github.io/php-phantomjs/) -> #### Important -> Currently when installing PHP PhantomJS on **Linux OS** you will need to compile your own version of PhantomJS for your system. This is due to an [unresolved issue](https://github.com/ariya/phantomjs/issues/12948) with the PhantomJS Linux packages. An Ubuntu compiled version will be installed by default but this may not be compatible with your system. - - - [![Total Downloads](https://poser.pugx.org/jonnyw/php-phantomjs/downloads.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Latest Stable Version](https://poser.pugx.org/jonnyw/php-phantomjs/v/stable.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Build Status](https://travis-ci.org/jonnnnyw/php-phantomjs.png?branch=master)](https://travis-ci.org/jonnnnyw/php-phantomjs) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/quality-score.png?s=631d32fa1fbb9300eb84b9b52702c7ffeac046a1)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) [![Code Coverage](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/coverage.png?s=893b5997da45448e32983b8568a39630b0b2d91b)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) Feature List diff --git a/composer.json b/composer.json index dd59e71..2dbbf22 100644 --- a/composer.json +++ b/composer.json @@ -25,12 +25,6 @@ "phpunit/phpunit": "~4.0", "zendframework/zendpdf": "~2.0" }, - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/jonnnnyw/phantomjs-installer" - } - ], "autoload": { "psr-0": { "JonnyW\\PhantomJs\\": "src" From 030ee312113becfda7a34e3f22c92215f714b189 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 2 Feb 2016 21:59:52 +1300 Subject: [PATCH 23/54] Redirect URL is always blank due to wrong case - https://github.com/jonnnnyw/php-phantomjs/issues/64 --- src/JonnyW/PhantomJs/Http/Response.php | 4 ++-- .../Tests/Integration/ClientTest.php | 22 +++++++++++++++++++ .../Tests/Unit/Http/ResponseTest.php | 2 +- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/JonnyW/PhantomJs/Http/Response.php b/src/JonnyW/PhantomJs/Http/Response.php index 6a89424..9ec5291 100644 --- a/src/JonnyW/PhantomJs/Http/Response.php +++ b/src/JonnyW/PhantomJs/Http/Response.php @@ -64,7 +64,7 @@ class Response * @var string * @access public */ - public $redirectUrl; + public $redirectURL; /** * Request time string @@ -209,7 +209,7 @@ public function getUrl() */ public function getRedirectUrl() { - return $this->redirectUrl; + return $this->redirectURL; } /** diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index cfb8d35..ee7792f 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -243,6 +243,28 @@ public function testResponseContainsHeaders() $this->assertNotEmpty($response->getHeaders()); } + + /** + * Test redirect URL is set in response + * if request is redirected. + * + * @access public + * @return void + */ + public function testRedirectUrlIsSetInResponseIfRequestIsRedirected() + { + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('https://jigsaw.w3.org/HTTP/300/302.html'); + + $client->send($request, $response); + + $this->assertNotEmpty($response->getRedirectUrl()); + } /** * Test POST request sends request data. diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php index 931eff2..94c6837 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php @@ -103,7 +103,7 @@ public function testUrlCanBeImported() public function testRedirectUrlCanBeImported() { $data = array( - 'redirectUrl' => 'http://test.com' + 'redirectURL' => 'http://test.com' ); $response = $this->getResponse(); From 59b4325be7f2a1b628cbb84f4be4fdb4adce0d6c Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 4 Feb 2016 09:05:32 +1300 Subject: [PATCH 24/54] Upgrading dependencies to check backwards compatibility in automated tests --- .travis.yml | 1 + composer.json | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 41e7274..c55dcba 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,6 +8,7 @@ php: - 5.3 - 5.4 - 5.5 + - 5.6 before_script: - composer self-update diff --git a/composer.json b/composer.json index 2dbbf22..3839eef 100644 --- a/composer.json +++ b/composer.json @@ -14,10 +14,10 @@ "minimum-stability": "stable", "require": { "php": ">=5.3.0", - "symfony/config": "~2.3", - "symfony/dependency-injection": "~2.3", - "symfony/filesystem": "~2.3", - "symfony/yaml": "~2.3", + "symfony/config": "~2.3|~3.0", + "symfony/dependency-injection": "~2.3|~3.0", + "symfony/filesystem": "~2.3|~3.0", + "symfony/yaml": "~2.3|~3.0", "twig/twig": "~1.16", "jakoch/phantomjs-installer": "~2.1" }, From a0b32700c8ea980290124fa8a8058e2b28192631 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 22 Mar 2016 09:02:33 +0000 Subject: [PATCH 25/54] Twig_Loader_String is now deprecated - https://github.com/jonnnnyw/php-phantomjs/issues/84 --- src/JonnyW/PhantomJs/Resources/config/config.yml | 2 +- src/JonnyW/PhantomJs/Resources/config/services.yml | 10 ++++++---- src/JonnyW/PhantomJs/Template/TemplateRenderer.php | 4 +++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/JonnyW/PhantomJs/Resources/config/config.yml b/src/JonnyW/PhantomJs/Resources/config/config.yml index 3f4bc69..61bfacb 100644 --- a/src/JonnyW/PhantomJs/Resources/config/config.yml +++ b/src/JonnyW/PhantomJs/Resources/config/config.yml @@ -52,7 +52,7 @@ parameters: phantomjs.template.template_renderer.class: JonnyW\PhantomJs\Template\TemplateRenderer phantomjs.twig.environment.class: Twig_Environment phantomjs.twig.lexer.class: Twig_Lexer - phantomjs.twig.string_loader.class: Twig_Loader_String + phantomjs.twig.array_loader.class: Twig_Loader_Array ################## ### RESOURCES #### diff --git a/src/JonnyW/PhantomJs/Resources/config/services.yml b/src/JonnyW/PhantomJs/Resources/config/services.yml index f97551b..fcfddf4 100644 --- a/src/JonnyW/PhantomJs/Resources/config/services.yml +++ b/src/JonnyW/PhantomJs/Resources/config/services.yml @@ -128,11 +128,13 @@ services: phantomjs.twig.environment: class: "%phantomjs.twig.environment.class%" arguments: - - "@phantomjs.twig.string_loader" + - "@phantomjs.twig.array_loader" public: false - phantomjs.twig.string_loader: - class: "%phantomjs.twig.string_loader.class%" + phantomjs.twig.array_loader: + class: "%phantomjs.twig.array_loader.class%" + arguments: + - [] public: false phantomjs.procedure.template_renderer: @@ -144,7 +146,7 @@ services: phantomjs.procedure.twig.environment: class: "%phantomjs.twig.environment.class%" arguments: - - "@phantomjs.twig.string_loader" + - "@phantomjs.twig.array_loader" public: false calls: - [ "setLexer", [ "@phantomjs.procedure.twig.lexer" ] ] diff --git a/src/JonnyW/PhantomJs/Template/TemplateRenderer.php b/src/JonnyW/PhantomJs/Template/TemplateRenderer.php index 9e344c5..d0a9bef 100644 --- a/src/JonnyW/PhantomJs/Template/TemplateRenderer.php +++ b/src/JonnyW/PhantomJs/Template/TemplateRenderer.php @@ -44,6 +44,8 @@ public function __construct(\Twig_Environment $twig) */ public function render($template, array $context = array()) { - return $this->twig->render($template, $context); + $template = $this->twig->createTemplate($template); + + return $template->render($context); } } From 5ba49503c445f36294093283a64e57b07ffb3504 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Wed, 20 Apr 2016 17:58:18 +0100 Subject: [PATCH 26/54] Locking PhantomJS installer to version 2.1.1 as it was causing issues - https://github.com/jonnnnyw/php-phantomjs/issues/97 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 3839eef..a106512 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "symfony/filesystem": "~2.3|~3.0", "symfony/yaml": "~2.3|~3.0", "twig/twig": "~1.16", - "jakoch/phantomjs-installer": "~2.1" + "jakoch/phantomjs-installer": "2.1.1" }, "require-dev": { "phpunit/phpunit": "~4.0", From 1e09977d6fac345b438049594a894b0c87c16177 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Mon, 2 May 2016 10:25:10 +0100 Subject: [PATCH 27/54] Adding body styles partial allowing CSS styles to be set on the body tag of the requested page - https://github.com/jonnnnyw/php-phantomjs/issues/92 --- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 39 +++++++++++++++++++ .../PhantomJs/Http/RequestInterface.php | 16 ++++++++ .../Resources/procedures/http_default.proc | 1 + .../procedures/page_body_styles.partial | 9 +++++ .../Tests/Integration/ClientTest.php | 31 ++++++++++++++- 5 files changed, 94 insertions(+), 2 deletions(-) create mode 100644 src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index 0a7e178..0a6e1c0 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -85,6 +85,14 @@ abstract class AbstractRequest */ protected $viewportHeight; + /** + * Body styles. + * + * @var int + * @access protected + */ + protected $bodyStyles; + /** * Internal constructor * @@ -97,6 +105,7 @@ public function __construct($url = null, $method = RequestInterface::METHOD_GET, { $this->headers = array(); $this->data = array(); + $this->bodyStyles = array(); $this->delay = 0; $this->viewportWidth = 0; $this->viewportHeight = 0; @@ -377,6 +386,36 @@ public function getHeaders($format = 'default') return $this->headers; } + /** + * Set body styles + * + * @access public + * @param array $styles + * @return \JonnyW\PhantomJs\Http\AbstractRequest + */ + public function setBodyStyles(array $styles) + { + $this->bodyStyles = $styles; + + return $this; + } + + /** + * Get body styles + * + * @access public + * @param string $format (default: 'default') + * @return array + */ + public function getBodyStyles($format = 'default') + { + if ($format === 'json') { + return json_encode($this->bodyStyles); + } + + return $this->bodyStyles; + } + /** * Flatten data into single * dimensional array diff --git a/src/JonnyW/PhantomJs/Http/RequestInterface.php b/src/JonnyW/PhantomJs/Http/RequestInterface.php index 0265cd9..4cb5b72 100644 --- a/src/JonnyW/PhantomJs/Http/RequestInterface.php +++ b/src/JonnyW/PhantomJs/Http/RequestInterface.php @@ -184,4 +184,20 @@ public function addHeaders(array $headers); * @return array */ public function getHeaders($format = 'default'); + + /** + * Set body styles + * + * @access public + * @param array $styles + */ + public function setBodyStyles(array $styles); + + /** + * Get body styles + * + * @access public + * @return array + */ + public function getBodyStyles(); } diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc index 2006fa7..031bd1d 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc @@ -75,6 +75,7 @@ phantom.onError = function(msg, trace) { * Open page */ page.open ('{{ input.getUrl() }}', '{{ input.getMethod() }}', '{{ input.getBody() }}', function (status) { + [[ engine.load('page_body_styles') ]] [[ engine.load('page_open') ]] }); diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial new file mode 100644 index 0000000..339f164 --- /dev/null +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial @@ -0,0 +1,9 @@ + +page.evaluate(function() { + + var styles = {{ input.getBodyStyles('json') }}; + + for(var property in styles) { + document.body.style[property] = styles[property]; + } +}); \ No newline at end of file diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index ee7792f..0130490 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -243,7 +243,7 @@ public function testResponseContainsHeaders() $this->assertNotEmpty($response->getHeaders()); } - + /** * Test redirect URL is set in response * if request is redirected. @@ -310,7 +310,7 @@ public function testCaptureRequestSavesFileToLocalDisk() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $client->send($request, $response); @@ -750,6 +750,33 @@ public function testDebugLogsDebugInfoToClientLog() $this->assertContains('[DEBUG]', $client->getLog()); } + /** + * Test test can set page + * background color + * + * @access public + * @return void + */ + public function testCanSetPageBackgroundColor() + { + $this->filename = 'test.jpg'; + $file = ($this->directory . '/' . $this->filename); + + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createCaptureRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setBodyStyles(array('backgroundColor' => 'red')); + $request->setOutputFile($file); + + $client->send($request, $response); + + $this->assertContains('body style="background-color: red;"', $response->getContent()); + } + /** +++++++++++++++++++++++++++++++++++ **/ /** ++++++++++ TEST ENTITIES ++++++++++ **/ /** +++++++++++++++++++++++++++++++++++ **/ From 62ab9b854c7ec0667796a521a85e9c0603bae0d8 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Mon, 2 May 2016 10:36:55 +0100 Subject: [PATCH 28/54] Fixing property doc type --- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index 0a6e1c0..a8af5e9 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -88,7 +88,7 @@ abstract class AbstractRequest /** * Body styles. * - * @var int + * @var array * @access protected */ protected $bodyStyles; From ee6cecba62538962586361a5653bcde35053ac1d Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Fri, 20 May 2016 19:45:00 +0100 Subject: [PATCH 29/54] Using uniqid for tmp file name generation appears to be causing conflicts when running processes in parallel. Have replaced for random string generation seeded by mt_rand - https://github.com/jonnnnyw/php-phantomjs/issues/101 --- src/JonnyW/PhantomJs/Cache/FileCache.php | 3 +- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 2 +- src/JonnyW/PhantomJs/Procedure/Procedure.php | 3 +- src/JonnyW/PhantomJs/StringUtils.php | 30 +++++++++++ .../Tests/Integration/ClientTest.php | 2 +- .../PhantomJs/Tests/Unit/StringUtilsTest.php | 52 +++++++++++++++++++ 6 files changed, 88 insertions(+), 4 deletions(-) create mode 100644 src/JonnyW/PhantomJs/StringUtils.php create mode 100644 src/JonnyW/PhantomJs/Tests/Unit/StringUtilsTest.php diff --git a/src/JonnyW/PhantomJs/Cache/FileCache.php b/src/JonnyW/PhantomJs/Cache/FileCache.php index 8576520..752aab7 100644 --- a/src/JonnyW/PhantomJs/Cache/FileCache.php +++ b/src/JonnyW/PhantomJs/Cache/FileCache.php @@ -8,6 +8,7 @@ */ namespace JonnyW\PhantomJs\Cache; +use JonnyW\PhantomJs\StringUtils; use JonnyW\PhantomJs\Exception\NotWritableException; use JonnyW\PhantomJs\Exception\NotExistsException; @@ -169,7 +170,7 @@ protected function readData($file) protected function getFileName($id) { if (is_dir($id)) { - return sprintf('%1$s/%2$s.%3$s', rtrim($id, DIRECTORY_SEPARATOR), uniqid(), $this->extension); + return sprintf('%1$s/%2$s.%3$s', rtrim($id, DIRECTORY_SEPARATOR), StringUtils::random(20), $this->extension); } $dirName = dirname($id); diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index a8af5e9..8ed6ec2 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -404,7 +404,7 @@ public function setBodyStyles(array $styles) * Get body styles * * @access public - * @param string $format (default: 'default') + * @param string $format (default: 'default') * @return array */ public function getBodyStyles($format = 'default') diff --git a/src/JonnyW/PhantomJs/Procedure/Procedure.php b/src/JonnyW/PhantomJs/Procedure/Procedure.php index 3e5df4f..633312f 100644 --- a/src/JonnyW/PhantomJs/Procedure/Procedure.php +++ b/src/JonnyW/PhantomJs/Procedure/Procedure.php @@ -14,6 +14,7 @@ use JonnyW\PhantomJs\Template\TemplateRendererInterface; use JonnyW\PhantomJs\Exception\NotWritableException; use JonnyW\PhantomJs\Exception\ProcedureFailedException; +use JonnyW\PhantomJs\StringUtils; /** * PHP PhantomJs @@ -184,7 +185,7 @@ public function compile(InputInterface $input) */ protected function write($compiled) { - return $this->cacheHandler->save(uniqid(), $compiled); + return $this->cacheHandler->save(StringUtils::random(20), $compiled); } /** diff --git a/src/JonnyW/PhantomJs/StringUtils.php b/src/JonnyW/PhantomJs/StringUtils.php new file mode 100644 index 0000000..536af8e --- /dev/null +++ b/src/JonnyW/PhantomJs/StringUtils.php @@ -0,0 +1,30 @@ + + */ +final class StringUtils +{ + /** + * Generate random string + * + * @static + * @access public + * @param int $length (default: 20) + * @return string + */ + public static function random($length = 20) + { + return substr(md5(mt_rand()), 0, $length); + } +} diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 0130490..41afa0f 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -751,7 +751,7 @@ public function testDebugLogsDebugInfoToClientLog() } /** - * Test test can set page + * Test test can set page * background color * * @access public diff --git a/src/JonnyW/PhantomJs/Tests/Unit/StringUtilsTest.php b/src/JonnyW/PhantomJs/Tests/Unit/StringUtilsTest.php new file mode 100644 index 0000000..bd8df35 --- /dev/null +++ b/src/JonnyW/PhantomJs/Tests/Unit/StringUtilsTest.php @@ -0,0 +1,52 @@ + + */ +class StringUtilsTest extends \PHPUnit_Framework_TestCase +{ + +/** +++++++++++++++++++++++++++++++++++ **/ +/** ++++++++++++++ TESTS ++++++++++++++ **/ +/** +++++++++++++++++++++++++++++++++++ **/ + + /** + * Test can generate random string for + * specific length + * + * @access public + * @return void + */ + public function testCanGenerateRandomStringForSpecificLength() + { + $string = StringUtils::random(14); + + $this->assertEquals(14, strlen($string)); + } + + /** + * Test random string is random + * + * @access public + * @return void + */ + public function testRandomStringIsRandom() + { + $string1 = StringUtils::random(14); + $string2 = StringUtils::random(14); + + $this->assertNotEquals($string1, $string2); + } +} From dafb41807dbbb3583787f6983669c27c11c4f4a2 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 16 Jun 2016 16:12:32 +0100 Subject: [PATCH 30/54] Can now add repeating header and footer to PDF output - https://github.com/jonnnnyw/php-phantomjs/issues/99 --- composer.json | 3 +- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 4 +- src/JonnyW/PhantomJs/Http/PdfRequest.php | 72 +++++++++++++++++ .../PhantomJs/Http/PdfRequestInterface.php | 36 +++++++++ .../PhantomJs/Http/RequestInterface.php | 7 +- .../procedures/page_body_styles.partial | 2 +- .../procedures/page_custom_headers.partial | 4 +- .../procedures/page_paper_size.partial | 31 ++++++-- .../Resources/procedures/validator.proc | 2 +- .../Tests/Integration/ClientTest.php | 78 ++++++++++++++++++- .../Procedure/ProcedureCompilerTest.php | 6 +- .../PhantomJs/Tests/Unit/ClientTest.php | 8 +- .../Procedure/ChainProcedureLoaderTest.php | 4 +- .../Procedure/ProcedureLoaderFactoryTest.php | 2 +- .../Unit/Procedure/ProcedureLoaderTest.php | 2 +- .../Tests/Unit/Procedure/ProcedureTest.php | 2 +- 16 files changed, 229 insertions(+), 34 deletions(-) diff --git a/composer.json b/composer.json index a106512..0f16ff6 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,8 @@ }, "require-dev": { "phpunit/phpunit": "~4.0", - "zendframework/zendpdf": "~2.0" + "zendframework/zendpdf": "~2.0", + "smalot/pdfparser": "~0.9" }, "autoload": { "psr-0": { diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index 8ed6ec2..defaa94 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -375,7 +375,7 @@ public function addHeaders(array $headers) * * @access public * @param string $format - * @return array + * @return array|string */ public function getHeaders($format = 'default') { @@ -405,7 +405,7 @@ public function setBodyStyles(array $styles) * * @access public * @param string $format (default: 'default') - * @return array + * @return array|string */ public function getBodyStyles($format = 'default') { diff --git a/src/JonnyW/PhantomJs/Http/PdfRequest.php b/src/JonnyW/PhantomJs/Http/PdfRequest.php index e2e5d5c..3f5efa1 100644 --- a/src/JonnyW/PhantomJs/Http/PdfRequest.php +++ b/src/JonnyW/PhantomJs/Http/PdfRequest.php @@ -57,6 +57,22 @@ class PdfRequest extends CaptureRequest */ protected $margin; + /** + * Repeating header + * + * @var array + * @access protected + */ + protected $header; + + /** + * Repeating footer + * + * @var array + * @access protected + */ + protected $footer; + /** * Internal constructor * @@ -75,6 +91,8 @@ public function __construct($url = null, $method = RequestInterface::METHOD_GET, $this->margin = '1cm'; $this->format = 'A4'; $this->orientation = 'portrait'; + $this->header = array(); + $this->footer = array(); } @@ -221,4 +239,58 @@ public function getMargin() { return $this->margin; } + + /** + * Set repeating header. + * + * @access public + * @param string $content + * @param string $height (default: '1cm') + * @return void + */ + public function setRepeatingHeader($content, $height = '1cm') + { + $this->header = array( + 'content' => $content, + 'height' => $height + ); + } + + /** + * Get repeating header. + * + * @access public + * @return array + */ + public function getRepeatingHeader() + { + return $this->header; + } + + /** + * Set repeating footer. + * + * @access public + * @param string $content + * @param string $height (default: '1cm') + * @return void + */ + public function setRepeatingFooter($content, $height = '1cm') + { + $this->footer = array( + 'content' => $content, + 'height' => $height + ); + } + + /** + * Get repeating footer. + * + * @access public + * @return array + */ + public function getRepeatingFooter() + { + return $this->footer; + } } diff --git a/src/JonnyW/PhantomJs/Http/PdfRequestInterface.php b/src/JonnyW/PhantomJs/Http/PdfRequestInterface.php index 5b68e10..b4d4300 100644 --- a/src/JonnyW/PhantomJs/Http/PdfRequestInterface.php +++ b/src/JonnyW/PhantomJs/Http/PdfRequestInterface.php @@ -110,4 +110,40 @@ public function setMargin($margin); * @return string */ public function getMargin(); + + /** + * Set repeating header. + * + * @access public + * @param string $content + * @param string $height (default: '1cm') + * @return void + */ + public function setRepeatingHeader($content, $height = '1cm'); + + /** + * Get repeating header. + * + * @access public + * @return array + */ + public function getRepeatingHeader(); + + /** + * Set repeating footer. + * + * @access public + * @param string $content + * @param string $height (default: '1cm') + * @return void + */ + public function setRepeatingFooter($content, $height = '1cm'); + + /** + * Get repeating footer. + * + * @access public + * @return array + */ + public function getRepeatingFooter(); } diff --git a/src/JonnyW/PhantomJs/Http/RequestInterface.php b/src/JonnyW/PhantomJs/Http/RequestInterface.php index 4cb5b72..3416336 100644 --- a/src/JonnyW/PhantomJs/Http/RequestInterface.php +++ b/src/JonnyW/PhantomJs/Http/RequestInterface.php @@ -180,10 +180,9 @@ public function addHeaders(array $headers); * Get request headers * * @access public - * @param string $format - * @return array + * @return array|string */ - public function getHeaders($format = 'default'); + public function getHeaders(); /** * Set body styles @@ -197,7 +196,7 @@ public function setBodyStyles(array $styles); * Get body styles * * @access public - * @return array + * @return array|string */ public function getBodyStyles(); } diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial index 339f164..58e60ff 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial @@ -1,7 +1,7 @@ page.evaluate(function() { - var styles = {{ input.getBodyStyles('json') }}; + var styles = {{ input.getBodyStyles()|json_encode(constant('JSON_FORCE_OBJECT')) }}; for(var property in styles) { document.body.style[property] = styles[property]; diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_custom_headers.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_custom_headers.partial index 7290371..f919ca5 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/page_custom_headers.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_custom_headers.partial @@ -1,5 +1,3 @@ -var headers = {{ input.getHeaders('json') }}; - -page.customHeaders = headers ? headers : {}; +page.customHeaders = {{ input.getHeaders()|json_encode(constant('JSON_FORCE_OBJECT')) }}; diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial index 30e72da..934c141 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial @@ -5,28 +5,45 @@ paperHeight = '{{ input.getPaperHeight() }}', paperFormat = '{{ input.getFormat() }}', paperOrientation = '{{ input.getOrientation() }}', - paperMargin = '{{ input.getMargin() }}'; - + paperMargin = '{{ input.getMargin() }}', + header = {{ input.getRepeatingHeader()|json_encode(constant('JSON_FORCE_OBJECT')) }}, + footer = {{ input.getRepeatingFooter()|json_encode(constant('JSON_FORCE_OBJECT')) }}; + if(paperWidth && paperHeight) { debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set page size ~ width: ' + paperWidth + ' height: ' + paperHeight + ' margin: ' + paperMargin); - page.paperSize = { + var paperSize = { width: paperWidth, height: paperHeight, - margin: paperMargin + margin: paperMargin }; } else { debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set page size ~ format: ' + paperFormat + ' orientation: ' + paperOrientation + ' margin: ' + paperMargin); - page.paperSize = { + var paperSize = { format: paperFormat, orientation: paperOrientation, - margin: paperMargin + margin: paperMargin }; - } + + paperSize.header = { + height: header.height, + contents: phantom.callback(function(pageNum, pageTotal) { + return header.content.replace('%pageNum%', pageNum).replace('%pageTotal%', pageTotal); + }) + }; + + paperSize.footer = { + height: footer.height, + contents: phantom.callback(function(pageNum, pageTotal) { + return footer.content.replace('%pageNum%', pageNum).replace('%pageTotal%', pageTotal); + }) + }; + + page.paperSize = paperSize; {% endif %} \ No newline at end of file diff --git a/src/JonnyW/PhantomJs/Resources/procedures/validator.proc b/src/JonnyW/PhantomJs/Resources/procedures/validator.proc index b578d86..398e9dd 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/validator.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/validator.proc @@ -7,7 +7,7 @@ var system = require('system'), try { - syntax = esprima.parse("{{ input.get('procedure')|replace({'"': '\'', '\n': ' ', '\r': ' '}) }}"); + syntax = esprima.parse("{{ input.get('procedure')|escape('js') }}"); } catch(e) { diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 41afa0f..e1e472a 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -378,7 +378,7 @@ public function testPdfRequestSavesPdfToLocalDisk() } /** - * Test capture request saves file to + * Test PDF request saves file to * disk with correct paper size. * * @access public @@ -415,7 +415,7 @@ public function testPdfRequestSavesFileToDiskWithCorrectPaperSize() } /** - * Test capture request saves file to + * Test PDF request saves file to * disk with correct format size. * * @access public @@ -449,7 +449,7 @@ public function testPdfRequestSavesFileToDiskWithCorrectFormatSize() } /** - * Test capture request saves file to + * Test PDF request saves file to * disk with correct orientation. * * @access public @@ -482,6 +482,78 @@ public function testPdfRequestSavesFileToDiskWithCorrectOrientation() $this->assertEquals(30, $pdfWidth); $this->assertEquals(21, $pdfHeight); } + + /** + * Test can set repeating header + * for PDF request + * + * @access public + * @return void + */ + public function testCanSetRepeatingHeaderForPDFRequest() + { + $this->filename = 'test.pdf'; + $file = ($this->directory . '/' . $this->filename); + + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createPdfRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setOutputFile($file); + $request->setFormat('A4'); + $request->setOrientation('landscape'); + $request->setMargin('0cm'); + $request->setRepeatingHeader('

Header %pageNum% / %pageTotal%

', '2cm'); + $request->setRepeatingFooter('
Footer %pageNum% / %pageTotal%
', '2cm'); + + $client->send($request, $response); + + $pdf = (new \Smalot\PdfParser\Parser()) + ->parseFile($file); + + $text = str_replace(' ', '', $pdf->getText()); + + $this->assertContains('Header', $text); + } + + /** + * Test can set repeating footer + * for PDF request + * + * @access public + * @return void + */ + public function testCanSetRepeatingFooterForPDFRequest() + { + $this->filename = 'test.pdf'; + $file = ($this->directory . '/' . $this->filename); + + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createPdfRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setOutputFile($file); + $request->setFormat('A4'); + $request->setOrientation('landscape'); + $request->setMargin('0cm'); + $request->setRepeatingHeader('

Header %pageNum% / %pageTotal%

', '2cm'); + $request->setRepeatingFooter('
Footer %pageNum% / %pageTotal%
', '2cm'); + + $client->send($request, $response); + + $pdf = (new \Smalot\PdfParser\Parser()) + ->parseFile($file); + + $text = str_replace(' ', '', $pdf->getText()); + + $this->assertContains('Footer', $text); + } /** * Test set viewport size sets diff --git a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php index 07c8f67..91e0cca 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php @@ -60,7 +60,7 @@ public function testProcedureIsLoadedFromCacheIfCacheIsEnabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(1)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -94,7 +94,7 @@ public function testProcedureIsNotLoadedFromCacheIfCacheIsDisabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -127,7 +127,7 @@ public function testProcedureCacheCanBeCleared() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); diff --git a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php index 65f30b0..cb4b95f 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php @@ -121,7 +121,7 @@ protected function getClient(Engine $engine, ProcedureLoaderInterface $procedure */ protected function getEngine() { - $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); return $engine; } @@ -134,7 +134,7 @@ protected function getEngine() */ protected function getMessageFactory() { - $messageFactory = $this->getMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); + $messageFactory = $this->createMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); return $messageFactory; } @@ -147,7 +147,7 @@ protected function getMessageFactory() */ protected function getProcedureLoader() { - $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -160,7 +160,7 @@ protected function getProcedureLoader() */ protected function getProcedureCompiler() { - $procedureCompiler = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); + $procedureCompiler = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); return $procedureCompiler; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php index ecf42d2..d40d4fb 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php @@ -153,7 +153,7 @@ protected function getChainProcedureLoader(array $procedureLoaders) */ protected function getProcedureLoader() { - $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -166,7 +166,7 @@ protected function getProcedureLoader() */ protected function getProcedure() { - $procedure = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); + $procedure = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); return $procedure; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php index 00f3429..0366ca8 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php @@ -93,7 +93,7 @@ protected function getProcedureLoaderFactory(ProcedureFactoryInterface $procedur */ protected function getProcedureFactory() { - $procedureFactory = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); + $procedureFactory = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); return $procedureFactory; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php index 11d1693..4c9f74b 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php @@ -268,7 +268,7 @@ protected function getRenderer() */ protected function getFileLocator() { - $fileLocator = $this->getMock('\Symfony\Component\Config\FileLocatorInterface'); + $fileLocator = $this->createMock('\Symfony\Component\Config\FileLocatorInterface'); return $fileLocator; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php index af706c2..4baa4d5 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php @@ -232,7 +232,7 @@ protected function getOutput() */ protected function getEngine() { - $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); return $engine; } From 486144ac38f4ab8c74f2b3f257f2bdab9d8c65b8 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 16 Jun 2016 16:20:23 +0100 Subject: [PATCH 31/54] Upgrading phpunit version and fixing broken test in earlier php versions --- composer.json | 2 +- src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/composer.json b/composer.json index 0f16ff6..6aea504 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "jakoch/phantomjs-installer": "2.1.1" }, "require-dev": { - "phpunit/phpunit": "~4.0", + "phpunit/phpunit": "~5.0", "zendframework/zendpdf": "~2.0", "smalot/pdfparser": "~0.9" }, diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index e1e472a..d26d6da 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -511,8 +511,8 @@ public function testCanSetRepeatingHeaderForPDFRequest() $client->send($request, $response); - $pdf = (new \Smalot\PdfParser\Parser()) - ->parseFile($file); + $parser = new \Smalot\PdfParser\Parser(); + $pdf = $parser->parseFile($file); $text = str_replace(' ', '', $pdf->getText()); @@ -547,8 +547,8 @@ public function testCanSetRepeatingFooterForPDFRequest() $client->send($request, $response); - $pdf = (new \Smalot\PdfParser\Parser()) - ->parseFile($file); + $parser = new \Smalot\PdfParser\Parser(); + $pdf = $parser->parseFile($file); $text = str_replace(' ', '', $pdf->getText()); From 9f5e81f0bd25e098a51fdf8d87bc3230c339259a Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 16 Jun 2016 16:27:40 +0100 Subject: [PATCH 32/54] Downgrading phpunit for support for earlier PHP versions --- composer.json | 2 +- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 4 ++-- src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php | 4 ++-- .../Tests/Integration/Procedure/ProcedureCompilerTest.php | 6 +++--- src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php | 8 ++++---- .../Tests/Unit/Procedure/ChainProcedureLoaderTest.php | 4 ++-- .../Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php | 2 +- .../Tests/Unit/Procedure/ProcedureLoaderTest.php | 2 +- .../PhantomJs/Tests/Unit/Procedure/ProcedureTest.php | 2 +- 9 files changed, 17 insertions(+), 17 deletions(-) diff --git a/composer.json b/composer.json index 6aea504..0f16ff6 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "jakoch/phantomjs-installer": "2.1.1" }, "require-dev": { - "phpunit/phpunit": "~5.0", + "phpunit/phpunit": "~4.0", "zendframework/zendpdf": "~2.0", "smalot/pdfparser": "~0.9" }, diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index defaa94..e5a7ae8 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -374,7 +374,7 @@ public function addHeaders(array $headers) * Get request headers * * @access public - * @param string $format + * @param string $format * @return array|string */ public function getHeaders($format = 'default') @@ -404,7 +404,7 @@ public function setBodyStyles(array $styles) * Get body styles * * @access public - * @param string $format (default: 'default') + * @param string $format (default: 'default') * @return array|string */ public function getBodyStyles($format = 'default') diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index d26d6da..05bbdbc 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -482,7 +482,7 @@ public function testPdfRequestSavesFileToDiskWithCorrectOrientation() $this->assertEquals(30, $pdfWidth); $this->assertEquals(21, $pdfHeight); } - + /** * Test can set repeating header * for PDF request @@ -518,7 +518,7 @@ public function testCanSetRepeatingHeaderForPDFRequest() $this->assertContains('Header', $text); } - + /** * Test can set repeating footer * for PDF request diff --git a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php index 91e0cca..07c8f67 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php @@ -60,7 +60,7 @@ public function testProcedureIsLoadedFromCacheIfCacheIsEnabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(1)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -94,7 +94,7 @@ public function testProcedureIsNotLoadedFromCacheIfCacheIsDisabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -127,7 +127,7 @@ public function testProcedureCacheCanBeCleared() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); diff --git a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php index cb4b95f..65f30b0 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php @@ -121,7 +121,7 @@ protected function getClient(Engine $engine, ProcedureLoaderInterface $procedure */ protected function getEngine() { - $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); return $engine; } @@ -134,7 +134,7 @@ protected function getEngine() */ protected function getMessageFactory() { - $messageFactory = $this->createMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); + $messageFactory = $this->getMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); return $messageFactory; } @@ -147,7 +147,7 @@ protected function getMessageFactory() */ protected function getProcedureLoader() { - $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -160,7 +160,7 @@ protected function getProcedureLoader() */ protected function getProcedureCompiler() { - $procedureCompiler = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); + $procedureCompiler = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); return $procedureCompiler; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php index d40d4fb..ecf42d2 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php @@ -153,7 +153,7 @@ protected function getChainProcedureLoader(array $procedureLoaders) */ protected function getProcedureLoader() { - $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -166,7 +166,7 @@ protected function getProcedureLoader() */ protected function getProcedure() { - $procedure = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); + $procedure = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); return $procedure; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php index 0366ca8..00f3429 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php @@ -93,7 +93,7 @@ protected function getProcedureLoaderFactory(ProcedureFactoryInterface $procedur */ protected function getProcedureFactory() { - $procedureFactory = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); + $procedureFactory = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); return $procedureFactory; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php index 4c9f74b..11d1693 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php @@ -268,7 +268,7 @@ protected function getRenderer() */ protected function getFileLocator() { - $fileLocator = $this->createMock('\Symfony\Component\Config\FileLocatorInterface'); + $fileLocator = $this->getMock('\Symfony\Component\Config\FileLocatorInterface'); return $fileLocator; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php index 4baa4d5..af706c2 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php @@ -232,7 +232,7 @@ protected function getOutput() */ protected function getEngine() { - $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); return $engine; } From 50bc19d022dff9434148b4fe6b357ec084d11ef9 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 16 Jun 2016 18:26:45 +0100 Subject: [PATCH 33/54] Comment blocks in procedures and partials no longer break validation - https://github.com/jonnnnyw/php-phantomjs/issues/103 --- .../Tests/Integration/ClientTest.php | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 05bbdbc..5ac65ba 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -72,6 +72,44 @@ public function testAdditionalProceduresCanBeLoadedThroughChainLoader() $this->assertSame($content, $response->getContent()); } + /** + * Test additional procedures can be loaded + * through chain loader if procedures + * contain comments + * + * @access public + * @return void + */ + public function testAdditionalProceduresCanBeLoadedThroughChainLoaderIfProceduresContainComments() + { + $content = 'TEST_PROCEDURE'; + + $procedure = <<writeProcedure($procedure); + + $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory'); + $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); + + $client = $this->getClient(); + $client->setProcedure('test'); + $client->getProcedureLoader()->addLoader($procedureLoader); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $client->send($request, $response); + + $this->assertSame($content, $response->getContent()); + } + /** * Test syntax exception is thrown if request * procedure contains syntax error. From 384b6dbeab6d2d30a9650c55f12b4254a98d1902 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 16 Jun 2016 21:33:06 +0100 Subject: [PATCH 34/54] Can now set client to lazy load pages which will wait for all resources on the page to load before rendering - https://github.com/jonnnnyw/php-phantomjs/issues/85 --- src/JonnyW/PhantomJs/Client.php | 11 ++ src/JonnyW/PhantomJs/ClientInterface.php | 8 ++ src/JonnyW/PhantomJs/Http/AbstractRequest.php | 12 +- .../Resources/procedures/http_default.proc | 7 + .../Resources/procedures/http_lazy.proc | 125 ++++++++++++++++++ .../page_on_resource_requested.partial | 2 + .../Tests/Integration/ClientTest.php | 49 +++++++ 7 files changed, 208 insertions(+), 6 deletions(-) create mode 100644 src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc create mode 100644 src/JonnyW/PhantomJs/Resources/procedures/page_on_resource_requested.partial diff --git a/src/JonnyW/PhantomJs/Client.php b/src/JonnyW/PhantomJs/Client.php index 46ac37e..0f542ec 100644 --- a/src/JonnyW/PhantomJs/Client.php +++ b/src/JonnyW/PhantomJs/Client.php @@ -208,4 +208,15 @@ public function getProcedureCompiler() { return $this->procedureCompiler; } + + /** + * Set lazy request flag. + * + * @access public + * @return void + */ + public function isLazy() + { + $this->procedure = 'http_lazy'; + } } diff --git a/src/JonnyW/PhantomJs/ClientInterface.php b/src/JonnyW/PhantomJs/ClientInterface.php index df79859..494db0f 100644 --- a/src/JonnyW/PhantomJs/ClientInterface.php +++ b/src/JonnyW/PhantomJs/ClientInterface.php @@ -83,4 +83,12 @@ public function setProcedure($procedure); * @return string */ public function getProcedure(); + + /** + * Set lazy request flag. + * + * @access public + * @return void + */ + public function isLazy(); } diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index e5a7ae8..5db9d2a 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -103,12 +103,12 @@ abstract class AbstractRequest */ public function __construct($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000) { - $this->headers = array(); - $this->data = array(); - $this->bodyStyles = array(); - $this->delay = 0; - $this->viewportWidth = 0; - $this->viewportHeight = 0; + $this->headers = array(); + $this->data = array(); + $this->bodyStyles = array(); + $this->delay = 0; + $this->viewportWidth = 0; + $this->viewportHeight = 0; $this->setMethod($method); $this->setTimeout($timeout); diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc index 031bd1d..514ee18 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc @@ -50,6 +50,13 @@ page.onResourceTimeout = function (error) { [[ engine.load('page_on_resource_timeout') ]] }; +/** + * On resource requested + */ +page.onResourceRequested = function (resource) { + [[ engine.load('page_on_resource_requested') ]] +}; + /** * On resource received */ diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc new file mode 100644 index 0000000..8c023f1 --- /dev/null +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc @@ -0,0 +1,125 @@ + +[% autoescape false %] +{% autoescape false %} + +/** + * Set up page and script parameters + */ +var page = require('webpage').create(), + system = require('system'), + response = {}, + debug = [], + logs = [], + procedure = {}, + resources = 0, + timeout; + +/** + * Global variables + */ +[[ engine.load('global_variables') ]] + +/** + * Define width & height of capture + */ +[[ engine.load('page_clip_rect') ]] + +/** + * Define paper size. + */ +[[ engine.load('page_paper_size') ]] + +/** + * Define viewport size. + */ +[[ engine.load('page_viewport_size') ]] + + +/** + * Define custom headers. + */ +[[ engine.load('page_custom_headers') ]] + +/** + * Page settings + */ +[[ engine.load('page_settings') ]] + +/** + * On resource timeout + */ +page.onResourceTimeout = function (error) { + [[ engine.load('page_on_resource_timeout') ]] +}; + +/** + * On resource requested + */ +page.onResourceRequested = function (req) { + + [[ engine.load('page_on_resource_requested') ]] + + resources++; + window.clearTimeout(timeout); + + debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Resource requested (' + req.url + ')'); +}; + +/** + * On resource received + */ +page.onResourceReceived = function (res) { + + var resource = res; // To be removed in version 5.0 + + [[ engine.load('page_on_resource_received') ]] + + if(!res.stage || res.stage === 'end') { + + resources--; + debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Resource received (' + res.url + ') ~ ' + res.status); + + if (resources === 0) { + + timeout = window.setTimeout(function() { + procedure.execute('success'); + }, 300); + } + } +}; + +/** + * Handle page errors + */ +page.onError = function (msg, trace) { + [[ engine.load('page_on_error') ]] +}; + +/** + * Handle global errors + */ +phantom.onError = function(msg, trace) { + [[ engine.load('phantom_on_error') ]] +}; + +/** + * Open page + */ +page.open ('{{ input.getUrl() }}', '{{ input.getMethod() }}', '{{ input.getBody() }}', function (status) { + + [[ engine.load('page_body_styles') ]] + + window.setTimeout(function () { + procedure.execute(status); + }, {{ input.getTimeout() - 200 }}); +}); + +/** + * Execute procedure + */ +procedure.execute = function (status) { + [[ engine.load( 'procedure_' ~ procedure_type ) ]] +}; + +{% endautoescape %} +[% endautoescape %] \ No newline at end of file diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_on_resource_requested.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_on_resource_requested.partial new file mode 100644 index 0000000..139597f --- /dev/null +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_on_resource_requested.partial @@ -0,0 +1,2 @@ + + diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 5ac65ba..5fbd43b 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -837,6 +837,55 @@ public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest() $this->assertSame(($startTime+$delay), $endTime); } + /** + * Test lazy request returns content after + * all resources are loaded + * + * @access public + * @return void + */ + public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded() + { + $client = $this->getClient(); + $client->isLazy(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://jonnyw.kiwi/tests/test-lazy.php'); + $request->setTimeout(5000); + + $client->send($request, $response); + + $this->assertContains('

loaded

', $response->getContent()); + } + + /** + * Test content is returned for lazy request + * if timeout is reached before resource is + * loaded + * + * @access public + * @return void + */ + public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResourceIsLoaded() + { + $client = $this->getClient(); + $client->isLazy(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://jonnyw.kiwi/tests/test-lazy.php'); + $request->setTimeout(1000); + + $client->send($request, $response); + + $this->assertContains('

', $response->getContent()); + } + /** * Test debug logs debug info to * client log. From 1cb8011d45f6dc0aa2278f606c48219761a5faca Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Thu, 16 Jun 2016 21:44:00 +0100 Subject: [PATCH 35/54] Updating build status badge --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 13c3587..8ac0948 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ websites that demand javascript support and also supports screen captures. [Full Documentation](http://jonnnnyw.github.io/php-phantomjs/) -[![Total Downloads](https://poser.pugx.org/jonnyw/php-phantomjs/downloads.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Latest Stable Version](https://poser.pugx.org/jonnyw/php-phantomjs/v/stable.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Build Status](https://travis-ci.org/jonnnnyw/php-phantomjs.png?branch=master)](https://travis-ci.org/jonnnnyw/php-phantomjs) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/quality-score.png?s=631d32fa1fbb9300eb84b9b52702c7ffeac046a1)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) [![Code Coverage](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/coverage.png?s=893b5997da45448e32983b8568a39630b0b2d91b)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) +[![Total Downloads](https://poser.pugx.org/jonnyw/php-phantomjs/downloads.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Latest Stable Version](https://poser.pugx.org/jonnyw/php-phantomjs/v/stable.png)](https://packagist.org/packages/jonnyw/php-phantomjs) [![Build Status](https://travis-ci.org/jonnnnyw/php-phantomjs.svg?branch=master)](https://travis-ci.org/jonnnnyw/php-phantomjs) [![Scrutinizer Quality Score](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/quality-score.png?s=631d32fa1fbb9300eb84b9b52702c7ffeac046a1)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) [![Code Coverage](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/badges/coverage.png?s=893b5997da45448e32983b8568a39630b0b2d91b)](https://scrutinizer-ci.com/g/jonnnnyw/php-phantomjs/) Feature List --------------------- From cf8d9a221f4c624aa1537c55a2e181f4b50367d7 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 28 Jun 2016 17:00:15 +0100 Subject: [PATCH 36/54] Resource debug logging was causing the script to hang whith large numnber of resources - https://github.com/jonnnnyw/php-phantomjs/issues/107 --- src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc index 8c023f1..7365e39 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc @@ -61,8 +61,6 @@ page.onResourceRequested = function (req) { resources++; window.clearTimeout(timeout); - - debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Resource requested (' + req.url + ')'); }; /** @@ -77,7 +75,6 @@ page.onResourceReceived = function (res) { if(!res.stage || res.stage === 'end') { resources--; - debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Resource received (' + res.url + ') ~ ' + res.status); if (resources === 0) { From 01d377d71b31f65d65f078cfc0504ca056622ac9 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 28 Jun 2016 17:51:21 +0100 Subject: [PATCH 37/54] Updating readme --- README.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 8ac0948..2050d1a 100644 --- a/README.md +++ b/README.md @@ -12,15 +12,17 @@ websites that demand javascript support and also supports screen captures. Feature List --------------------- -* Load webpages through the PhantomJS headless browser -* View detailed response data including page content, headers, status code etc. -* Handle redirects -* View javascript console errors -* View detailed PhantomJS debuged information -* Save screen captures to local disk -* Output web pages to PDF document -* Set viewport size -* Define screen capture x, y, width and height parameters -* Delay page rendering for a specified time -* Execute PhantomJS with command line options -* Easily build and run custom PhantomJS scripts \ No newline at end of file +* Load webpages through the PhantomJS headless browser +* View detailed response data including page content, headers, status code etc. +* Handle redirects +* View javascript console errors +* View detailed PhantomJS debug information +* Save screen captures to local disk +* Output web pages to PDF document +* Set viewport size +* Set fixed header and footer for PDF output +* Define screen capture x, y, width and height parameters +* Delay page rendering for a specified time +* Delay page rendering until page resources are fully loaded +* Execute PhantomJS with command line options +* Easily build and run custom PhantomJS scripts \ No newline at end of file From cb3a4e5550d08a1ab6153da7c6368f1853575a14 Mon Sep 17 00:00:00 2001 From: amitaymolko Date: Thu, 20 Oct 2016 11:04:53 +0300 Subject: [PATCH 38/54] Update composer.json --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 0f16ff6..cefd8cd 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "symfony/filesystem": "~2.3|~3.0", "symfony/yaml": "~2.3|~3.0", "twig/twig": "~1.16", - "jakoch/phantomjs-installer": "2.1.1" + "jakoch/phantomjs-installer": "^2.1" }, "require-dev": { "phpunit/phpunit": "~4.0", From 23c9092e06f16c987fb8dfc37e05b20c90998e9c Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 15 Nov 2016 12:36:27 +0000 Subject: [PATCH 39/54] URL validation has been removed as it cannot cover all use cases. A request with an invalid URL fails with a status code of 0 - https://github.com/jonnnnyw/php-phantomjs/issues/119 --- composer.json | 2 +- src/JonnyW/PhantomJs/Engine.php | 29 +++++++++++++++++++ src/JonnyW/PhantomJs/Http/AbstractRequest.php | 8 +---- .../Procedure/ProcedureCompilerTest.php | 6 ++-- .../PhantomJs/Tests/Unit/ClientTest.php | 8 ++--- .../PhantomJs/Tests/Unit/EngineTest.php | 29 +++++++++++++++++++ .../Tests/Unit/Http/CaptureRequestTest.php | 15 ---------- .../Tests/Unit/Http/PdfRequestTest.php | 15 ---------- .../PhantomJs/Tests/Unit/Http/RequestTest.php | 15 ---------- .../Procedure/ChainProcedureLoaderTest.php | 4 +-- .../Procedure/ProcedureLoaderFactoryTest.php | 2 +- .../Unit/Procedure/ProcedureLoaderTest.php | 2 +- .../Tests/Unit/Procedure/ProcedureTest.php | 2 +- 13 files changed, 72 insertions(+), 65 deletions(-) diff --git a/composer.json b/composer.json index cefd8cd..1469f7d 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "jakoch/phantomjs-installer": "^2.1" }, "require-dev": { - "phpunit/phpunit": "~4.0", + "phpunit/phpunit": "~5.0", "zendframework/zendpdf": "~2.0", "smalot/pdfparser": "~0.9" }, diff --git a/src/JonnyW/PhantomJs/Engine.php b/src/JonnyW/PhantomJs/Engine.php index 10a5a0f..ef46fb1 100644 --- a/src/JonnyW/PhantomJs/Engine.php +++ b/src/JonnyW/PhantomJs/Engine.php @@ -33,6 +33,14 @@ class Engine */ protected $debug; + /** + * Cache flag. + * + * @var boolean + * @access protected + */ + protected $cache; + /** * PhantomJs run options. * @@ -59,6 +67,9 @@ public function __construct() { $this->path = 'bin/phantomjs'; $this->options = array(); + + $this->debug = false; + $this->cache = true; } /** @@ -75,6 +86,10 @@ public function getCommand() $this->validateExecutable($path); + if ($this->cache) { + array_push($options, '--disk-cache=true'); + } + if ($this->debug) { array_push($options, '--debug=true'); } @@ -164,6 +179,20 @@ public function debug($doDebug) return $this; } + /** + * Cache. + * + * @access public + * @param boolean $doCache + * @return \JonnyW\PhantomJs\Client + */ + public function cache($doCache) + { + $this->cache = $doCache; + + return $this; + } + /** * Log info. * diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index 5db9d2a..2efa042 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -9,7 +9,6 @@ namespace JonnyW\PhantomJs\Http; -use JonnyW\PhantomJs\Exception\InvalidUrlException; use JonnyW\PhantomJs\Exception\InvalidMethodException; use JonnyW\PhantomJs\Procedure\InputInterface; @@ -243,16 +242,11 @@ public function getViewportHeight() * Set request URL * * @access public - * @param string $url + * @param string $url * @return \JonnyW\PhantomJs\Http\AbstractRequest - * @throws \JonnyW\PhantomJs\Exception\InvalidUrlException */ public function setUrl($url) { - if (!filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)) { - throw new InvalidUrlException(sprintf('Invalid URL provided: %s', $url)); - } - $this->url = $url; return $this; diff --git a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php index 07c8f67..91e0cca 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php @@ -60,7 +60,7 @@ public function testProcedureIsLoadedFromCacheIfCacheIsEnabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(1)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -94,7 +94,7 @@ public function testProcedureIsNotLoadedFromCacheIfCacheIsDisabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -127,7 +127,7 @@ public function testProcedureCacheCanBeCleared() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); diff --git a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php index 65f30b0..cb4b95f 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php @@ -121,7 +121,7 @@ protected function getClient(Engine $engine, ProcedureLoaderInterface $procedure */ protected function getEngine() { - $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); return $engine; } @@ -134,7 +134,7 @@ protected function getEngine() */ protected function getMessageFactory() { - $messageFactory = $this->getMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); + $messageFactory = $this->createMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); return $messageFactory; } @@ -147,7 +147,7 @@ protected function getMessageFactory() */ protected function getProcedureLoader() { - $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -160,7 +160,7 @@ protected function getProcedureLoader() */ protected function getProcedureCompiler() { - $procedureCompiler = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); + $procedureCompiler = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); return $procedureCompiler; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/EngineTest.php b/src/JonnyW/PhantomJs/Tests/Unit/EngineTest.php index ef2b75d..c924b78 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/EngineTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/EngineTest.php @@ -168,6 +168,35 @@ public function testDebugFlagIsNotSetIfDebuggingIsNotEnabled() $this->assertNotContains('--debug=true', $engine->getCommand()); } + /** + * Test disk cache flag can be set. + * + * @access public + * @return void + */ + public function testDiskCacheFlagCanBeSet() + { + $engine = $this->getEngine(); + $engine->cache(true); + + $this->assertContains('--disk-cache=true', $engine->getCommand()); + } + + /** + * Test disk cache flag is not set if + * caching is not enabled. + * + * @access public + * @return void + */ + public function testDiskCacheFlagIsNotSetIfCachingIsNotEnabled() + { + $engine = $this->getEngine(); + $engine->cache(false); + + $this->assertNotContains('--disk-cache=true', $engine->getCommand()); + } + /** * Test command contains run options. * diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php index 3dd43e2..e0ab357 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php @@ -180,21 +180,6 @@ public function testRectLeftCanBeSet() $this->assertSame($left, $captureRequest->getRectLeft()); } - /** - * Test invalid URL exception is thrown - * if URL is invalid format. - * - * @access public - * @return void - */ - public function testInvalidUrlExceptionIsThrownIfUrlIsInvalidFormat() - { - $this->setExpectedException('\JonnyW\PhantomJs\Exception\InvalidUrlException'); - - $captureRequest = $this->getCaptureRequest(); - $captureRequest->setUrl('\\AnInvalidUrl'); - } - /** * Test URL does not contain query params if * mehtod is not HEAD or GET. diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php index f873bda..32b1dbe 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php @@ -110,21 +110,6 @@ public function testInvalidMethodIsThrownIfMethodIsInvalid() $pdfRequest->setMethod('INVALID_METHOD'); } - /** - * Test invalid URL exception is thrown - * if URL is invalid format. - * - * @access public - * @return void - */ - public function testInvalidUrlExceptionIsThrownIfUrlIsInvalidFormat() - { - $this->setExpectedException('\JonnyW\PhantomJs\Exception\InvalidUrlException'); - - $pdfRequest = $this->getPdfRequest(); - $pdfRequest->setUrl('\\AnInvalidUrl'); - } - /** * Test URL does not contain query params if * mehtod is not HEAD or GET. diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php index 58210b5..b0d2c46 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php @@ -110,21 +110,6 @@ public function testInvalidMethodIsThrownIfMethodIsInvalid() $request->setMethod('INVALID_METHOD'); } - /** - * Test invalid URL exception is thrown - * if URL is invalid format. - * - * @access public - * @return void - */ - public function testInvalidUrlExceptionIsThrownIfUrlIsInvalidFormat() - { - $this->setExpectedException('\JonnyW\PhantomJs\Exception\InvalidUrlException'); - - $request = $this->getRequest(); - $request->setUrl('\\AnInvalidUrl'); - } - /** * Test URL does not contain query params if * mehtod is not HEAD or GET. diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php index ecf42d2..d40d4fb 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php @@ -153,7 +153,7 @@ protected function getChainProcedureLoader(array $procedureLoaders) */ protected function getProcedureLoader() { - $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -166,7 +166,7 @@ protected function getProcedureLoader() */ protected function getProcedure() { - $procedure = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); + $procedure = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); return $procedure; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php index 00f3429..0366ca8 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php @@ -93,7 +93,7 @@ protected function getProcedureLoaderFactory(ProcedureFactoryInterface $procedur */ protected function getProcedureFactory() { - $procedureFactory = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); + $procedureFactory = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); return $procedureFactory; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php index 11d1693..4c9f74b 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php @@ -268,7 +268,7 @@ protected function getRenderer() */ protected function getFileLocator() { - $fileLocator = $this->getMock('\Symfony\Component\Config\FileLocatorInterface'); + $fileLocator = $this->createMock('\Symfony\Component\Config\FileLocatorInterface'); return $fileLocator; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php index af706c2..4baa4d5 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php @@ -232,7 +232,7 @@ protected function getOutput() */ protected function getEngine() { - $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); return $engine; } From c11e1b5e8af7f5097344d964044a8b9ef19471f3 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 15 Nov 2016 14:01:42 +0000 Subject: [PATCH 40/54] Downgrading phpunit for support for earlier PHP versions --- composer.json | 2 +- .../Tests/Integration/Procedure/ProcedureCompilerTest.php | 6 +++--- src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php | 8 ++++---- .../Tests/Unit/Procedure/ChainProcedureLoaderTest.php | 4 ++-- .../Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php | 2 +- .../Tests/Unit/Procedure/ProcedureLoaderTest.php | 2 +- .../PhantomJs/Tests/Unit/Procedure/ProcedureTest.php | 2 +- 7 files changed, 13 insertions(+), 13 deletions(-) diff --git a/composer.json b/composer.json index 1469f7d..cefd8cd 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ "jakoch/phantomjs-installer": "^2.1" }, "require-dev": { - "phpunit/phpunit": "~5.0", + "phpunit/phpunit": "~4.0", "zendframework/zendpdf": "~2.0", "smalot/pdfparser": "~0.9" }, diff --git a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php index 91e0cca..07c8f67 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/Procedure/ProcedureCompilerTest.php @@ -60,7 +60,7 @@ public function testProcedureIsLoadedFromCacheIfCacheIsEnabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(1)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -94,7 +94,7 @@ public function testProcedureIsNotLoadedFromCacheIfCacheIsDisabled() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); @@ -127,7 +127,7 @@ public function testProcedureCacheCanBeCleared() $request = $this->getRequest(); $request->setUrl('http://test.com'); - $renderer = $this->createMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); + $renderer = $this->getMock('\JonnyW\PhantomJs\Template\TemplateRendererInterface'); $renderer->expects($this->exactly(2)) ->method('render') ->will($this->returnValue('var test=1; phantom.exit(1);')); diff --git a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php index cb4b95f..65f30b0 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/ClientTest.php @@ -121,7 +121,7 @@ protected function getClient(Engine $engine, ProcedureLoaderInterface $procedure */ protected function getEngine() { - $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); return $engine; } @@ -134,7 +134,7 @@ protected function getEngine() */ protected function getMessageFactory() { - $messageFactory = $this->createMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); + $messageFactory = $this->getMock('\JonnyW\PhantomJs\Http\MessageFactoryInterface'); return $messageFactory; } @@ -147,7 +147,7 @@ protected function getMessageFactory() */ protected function getProcedureLoader() { - $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -160,7 +160,7 @@ protected function getProcedureLoader() */ protected function getProcedureCompiler() { - $procedureCompiler = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); + $procedureCompiler = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface'); return $procedureCompiler; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php index d40d4fb..ecf42d2 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ChainProcedureLoaderTest.php @@ -153,7 +153,7 @@ protected function getChainProcedureLoader(array $procedureLoaders) */ protected function getProcedureLoader() { - $procedureLoader = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); + $procedureLoader = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface'); return $procedureLoader; } @@ -166,7 +166,7 @@ protected function getProcedureLoader() */ protected function getProcedure() { - $procedure = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); + $procedure = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureInterface'); return $procedure; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php index 0366ca8..00f3429 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderFactoryTest.php @@ -93,7 +93,7 @@ protected function getProcedureLoaderFactory(ProcedureFactoryInterface $procedur */ protected function getProcedureFactory() { - $procedureFactory = $this->createMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); + $procedureFactory = $this->getMock('\JonnyW\PhantomJs\Procedure\ProcedureFactoryInterface'); return $procedureFactory; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php index 4c9f74b..11d1693 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureLoaderTest.php @@ -268,7 +268,7 @@ protected function getRenderer() */ protected function getFileLocator() { - $fileLocator = $this->createMock('\Symfony\Component\Config\FileLocatorInterface'); + $fileLocator = $this->getMock('\Symfony\Component\Config\FileLocatorInterface'); return $fileLocator; } diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php index 4baa4d5..af706c2 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Procedure/ProcedureTest.php @@ -232,7 +232,7 @@ protected function getOutput() */ protected function getEngine() { - $engine = $this->createMock('\JonnyW\PhantomJs\Engine'); + $engine = $this->getMock('\JonnyW\PhantomJs\Engine'); return $engine; } From 0baec84ed6ea6c4fc1a4aa7deafb495d2c2151ad Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 15 Nov 2016 15:12:42 +0000 Subject: [PATCH 41/54] Margin for PDF output can now be defined as an object allowing different margins to be applied to each edge of PDF - https://github.com/jonnnnyw/php-phantomjs/issues/113 --- src/JonnyW/PhantomJs/Http/PdfRequest.php | 6 +++--- .../PhantomJs/Resources/procedures/page_paper_size.partial | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/JonnyW/PhantomJs/Http/PdfRequest.php b/src/JonnyW/PhantomJs/Http/PdfRequest.php index 3f5efa1..f8a2ea4 100644 --- a/src/JonnyW/PhantomJs/Http/PdfRequest.php +++ b/src/JonnyW/PhantomJs/Http/PdfRequest.php @@ -52,7 +52,7 @@ class PdfRequest extends CaptureRequest /** * Margin * - * @var string + * @var string|array * @access protected */ protected $margin; @@ -221,7 +221,7 @@ public function getOrientation() * Set margin. * * @access public - * @param string $margin + * @param string|array $margin * @return void */ public function setMargin($margin) @@ -233,7 +233,7 @@ public function setMargin($margin) * Get margin. * * @access public - * @return string + * @return string|array */ public function getMargin() { diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial index 934c141..d2ce5bc 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial @@ -5,7 +5,7 @@ paperHeight = '{{ input.getPaperHeight() }}', paperFormat = '{{ input.getFormat() }}', paperOrientation = '{{ input.getOrientation() }}', - paperMargin = '{{ input.getMargin() }}', + paperMargin = {{ input.getMargin()|json_encode(constant('JSON_FORCE_OBJECT')) }}, header = {{ input.getRepeatingHeader()|json_encode(constant('JSON_FORCE_OBJECT')) }}, footer = {{ input.getRepeatingFooter()|json_encode(constant('JSON_FORCE_OBJECT')) }}; From 65564e83bcafcaf0a7e4724b277d72f82028ed50 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Tue, 15 Nov 2016 16:28:02 +0000 Subject: [PATCH 42/54] Can now set PhantomJS page settings, including custom user agent, in request - https://github.com/jonnnnyw/php-phantomjs/issues/45 --- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 43 ++++++++- .../procedures/page_settings.partial | 8 +- .../Tests/Integration/ClientTest.php | 22 +++++ .../Tests/Unit/Http/CaptureRequestTest.php | 48 +++++----- .../Tests/Unit/Http/MessageFactoryTest.php | 12 +-- .../Tests/Unit/Http/PdfRequestTest.php | 44 +++++----- .../PhantomJs/Tests/Unit/Http/RequestTest.php | 87 ++++++++++++++----- .../Tests/Unit/Http/ResponseTest.php | 16 ++-- 8 files changed, 194 insertions(+), 86 deletions(-) diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index 2efa042..237d8e4 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -28,6 +28,14 @@ abstract class AbstractRequest */ protected $headers; + /** + * Settings + * + * @var array + * @access protected + */ + protected $settings; + /** * Request data * @@ -105,6 +113,7 @@ public function __construct($url = null, $method = RequestInterface::METHOD_GET, $this->headers = array(); $this->data = array(); $this->bodyStyles = array(); + $this->settings = array(); $this->delay = 0; $this->viewportWidth = 0; $this->viewportHeight = 0; @@ -159,7 +168,7 @@ public function getMethod() */ public function setTimeout($timeout) { - $this->timeout = $timeout; + $this->settings['resourceTimeout'] = $timeout; return $this; } @@ -172,7 +181,11 @@ public function setTimeout($timeout) */ public function getTimeout() { - return $this->timeout; + if (isset($this->settings['resourceTimeout'])) { + return $this->settings['resourceTimeout']; + } + + return null; } /** @@ -380,6 +393,32 @@ public function getHeaders($format = 'default') return $this->headers; } + /** + * Add single setting + * + * @access public + * @param string $setting + * @param string $value + * @return \JonnyW\PhantomJs\Http\AbstractRequest + */ + public function addSetting($setting, $value) + { + $this->settings[$setting] = $value; + + return $this; + } + + /** + * Get settings + * + * @access public + * @return array + */ + public function getSettings() + { + return $this->settings; + } + /** * Set body styles * diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_settings.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_settings.partial index b7572d4..b2becec 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/page_settings.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_settings.partial @@ -1,3 +1,9 @@ -page.settings.resourceTimeout = {{ input.getTimeout() }}; +var settings = {{ input.getSettings()|json_encode(constant('JSON_FORCE_OBJECT')) }}; +for(var prop in settings) { + + if(settings.hasOwnProperty(prop)) { + page.settings[prop] = settings[prop]; + } +} diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 5fbd43b..0a5c973 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -212,6 +212,28 @@ public function testResponseContainsValidBodyIfPageIsSuccessfullyLoaded() $this->assertContains('PHANTOMJS_DEFAULT_TEST', $response->getContent()); } + /** + * Test can set user agent in settings + * + * @access public + * @return void + */ + public function testCanSetUserAgentInSettings() + { + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->addSetting('userAgent', 'PhantomJS TEST'); + + $client->send($request, $response); + + $this->assertContains('userAgent=PhantomJS TEST', $response->getContent()); + } + /** * Test response contains console error if a * javascript error exists on the page. diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php index e0ab357..3c5b3f4 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php @@ -34,7 +34,7 @@ public function testCaptureTypeIsReturnedByDefaultIfNotTypeIsSet() { $captureRequest = $this->getCaptureRequest(); - $this->assertSame(RequestInterface::REQUEST_TYPE_CAPTURE, $captureRequest->getType()); + $this->assertEquals(RequestInterface::REQUEST_TYPE_CAPTURE, $captureRequest->getType()); } /** @@ -50,7 +50,7 @@ public function testCustomTypeCanBeSet() $captureRequest = $this->getCaptureRequest(); $captureRequest->setType($requestType); - $this->assertSame($requestType, $captureRequest->getType()); + $this->assertEquals($requestType, $captureRequest->getType()); } /** @@ -64,7 +64,7 @@ public function testUrlCanBeSetViaConstructor() $url = 'http://test.com'; $captureRequest = $this->getCaptureRequest($url); - $this->assertSame($url, $captureRequest->getUrl()); + $this->assertEquals($url, $captureRequest->getUrl()); } /** @@ -78,7 +78,7 @@ public function testMethodCanBeSetViaConstructor() $method = 'GET'; $captureRequest = $this->getCaptureRequest(null, $method); - $this->assertSame($method, $captureRequest->getMethod()); + $this->assertEquals($method, $captureRequest->getMethod()); } /** @@ -92,7 +92,7 @@ public function testTimeoutCanBeSetViaConstructor() $timeout = 100000; $captureRequest = $this->getCaptureRequest('http://test.com', 'GET', $timeout); - $this->assertSame($timeout, $captureRequest->getTimeout()); + $this->assertEquals($timeout, $captureRequest->getTimeout()); } /** @@ -124,7 +124,7 @@ public function testRectWidthCanBeSet() $captureRequest = $this->getCaptureRequest(); $captureRequest->setCaptureDimensions($width, $height); - $this->assertSame($width, $captureRequest->getRectWidth()); + $this->assertEquals($width, $captureRequest->getRectWidth()); } /** @@ -141,7 +141,7 @@ public function testRectHeightCanBeSet() $captureRequest = $this->getCaptureRequest(); $captureRequest->setCaptureDimensions($width, $height); - $this->assertSame($height, $captureRequest->getRectHeight()); + $this->assertEquals($height, $captureRequest->getRectHeight()); } /** @@ -159,7 +159,7 @@ public function testRectTopCanBeSet() $captureRequest = $this->getCaptureRequest(); $captureRequest->setCaptureDimensions($width, $height, $top); - $this->assertSame($top, $captureRequest->getRectTop()); + $this->assertEquals($top, $captureRequest->getRectTop()); } /** @@ -177,7 +177,7 @@ public function testRectLeftCanBeSet() $captureRequest = $this->getCaptureRequest(); $captureRequest->setCaptureDimensions($width, $height, 0, $left); - $this->assertSame($left, $captureRequest->getRectLeft()); + $this->assertEquals($left, $captureRequest->getRectLeft()); } /** @@ -201,7 +201,7 @@ public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet() $captureRequest->setUrl($url); $captureRequest->setRequestData($data); - $this->assertSame($url, $captureRequest->getUrl()); + $this->assertEquals($url, $captureRequest->getUrl()); } /** @@ -227,7 +227,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsGet() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $captureRequest->getUrl()); + $this->assertEquals($expectedUrl, $captureRequest->getUrl()); } /** @@ -253,7 +253,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsHead() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $captureRequest->getUrl()); + $this->assertEquals($expectedUrl, $captureRequest->getUrl()); } /** @@ -279,7 +279,7 @@ public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams( $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $captureRequest->getUrl()); + $this->assertEquals($expectedUrl, $captureRequest->getUrl()); } /** @@ -300,7 +300,7 @@ public function testRequestContainsNoBodyIfMethodIsGet() $captureRequest->setMethod('GET'); $captureRequest->setRequestData($data); - $this->assertSame('', $captureRequest->getBody()); + $this->assertEquals('', $captureRequest->getBody()); } /** @@ -321,7 +321,7 @@ public function testRequestContainsNoBodyIfMethodIsHead() $captureRequest->setMethod('HEAD'); $captureRequest->setRequestData($data); - $this->assertSame('', $captureRequest->getBody()); + $this->assertEquals('', $captureRequest->getBody()); } /** @@ -344,7 +344,7 @@ public function testRequestContainsABodyIfMethodIsNotHeadOrGet() $body = 'test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($body, $captureRequest->getBody()); + $this->assertEquals($body, $captureRequest->getBody()); } /** @@ -372,7 +372,7 @@ public function testRequestDataCanBeFalttened() 'test_param2[1]' => 'Testing3' ); - $this->assertSame($flatData, $captureRequest->getRequestData(true)); + $this->assertEquals($flatData, $captureRequest->getRequestData(true)); } /** @@ -394,7 +394,7 @@ public function testRawRequestDataCanBeAccessed() $captureRequest = $this->getCaptureRequest(); $captureRequest->setRequestData($data); - $this->assertSame($data, $captureRequest->getRequestData(false)); + $this->assertEquals($data, $captureRequest->getRequestData(false)); } /** @@ -420,7 +420,7 @@ public function testHeadersCanBeAdded() $expectedHeaders = array_merge($existingHeaders, $newHeaders); - $this->assertSame($expectedHeaders, $captureRequest->getHeaders()); + $this->assertEquals($expectedHeaders, $captureRequest->getHeaders()); } /** @@ -442,7 +442,7 @@ public function testHeadersCanBeAccessedInJsonFormat() $expectedHeaders = json_encode($headers); - $this->assertSame($expectedHeaders, $captureRequest->getHeaders('json')); + $this->assertEquals($expectedHeaders, $captureRequest->getHeaders('json')); } /** @@ -461,7 +461,7 @@ public function testRawHeadersCanBeAccessed() $captureRequest = $this->getCaptureRequest(); $captureRequest->setHeaders($headers); - $this->assertSame($headers, $captureRequest->getHeaders('default')); + $this->assertEquals($headers, $captureRequest->getHeaders('default')); } /** @@ -494,7 +494,7 @@ public function testCanSetOutputFile() $captureRequest = $this->getCaptureRequest(); $captureRequest->setOutputFile($outputFile); - $this->assertSame($outputFile, $captureRequest->getOutputFile()); + $this->assertEquals($outputFile, $captureRequest->getOutputFile()); } /** @@ -511,7 +511,7 @@ public function testCanSetViewportWidth() $caputreRequest = $this->getCaptureRequest(); $caputreRequest->setViewportSize($width, $height); - $this->assertSame($width, $caputreRequest->getViewportWidth()); + $this->assertEquals($width, $caputreRequest->getViewportWidth()); } /** @@ -528,7 +528,7 @@ public function testCanSetViewportHeight() $caputreRequest = $this->getCaptureRequest(); $caputreRequest->setViewportSize($width, $height); - $this->assertSame($height, $caputreRequest->getViewportHeight()); + $this->assertEquals($height, $caputreRequest->getViewportHeight()); } /** +++++++++++++++++++++++++++++++++++ **/ diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/MessageFactoryTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/MessageFactoryTest.php index e19ac3e..5390dbe 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/MessageFactoryTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/MessageFactoryTest.php @@ -59,7 +59,7 @@ public function testCanCreateRequestWithUrl() $messageFactory = $this->getMessageFactory(); $request = $messageFactory->createRequest($url); - $this->assertSame($url, $request->getUrl()); + $this->assertEquals($url, $request->getUrl()); } /** @@ -75,7 +75,7 @@ public function testCanCreateRequestWithMethod() $messageFactory = $this->getMessageFactory(); $request = $messageFactory->createRequest(null, $method); - $this->assertSame($method, $request->getMethod()); + $this->assertEquals($method, $request->getMethod()); } /** @@ -91,7 +91,7 @@ public function testCanCreateRequestWithTimeout() $messageFactory = $this->getMessageFactory(); $request = $messageFactory->createRequest(null, 'GET', $timeout); - $this->assertSame($timeout, $request->getTimeout()); + $this->assertEquals($timeout, $request->getTimeout()); } /** @@ -120,7 +120,7 @@ public function testCanCreateCaptureRequestWithUrl() $messageFactory = $this->getMessageFactory(); $captureRequest = $messageFactory->createCaptureRequest($url); - $this->assertSame($url, $captureRequest->getUrl()); + $this->assertEquals($url, $captureRequest->getUrl()); } /** @@ -137,7 +137,7 @@ public function testCanCreateCaptureRequestWithMethod() $messageFactory = $this->getMessageFactory(); $captureRequest = $messageFactory->createCaptureRequest(null, $method); - $this->assertSame($method, $captureRequest->getMethod()); + $this->assertEquals($method, $captureRequest->getMethod()); } /** @@ -153,7 +153,7 @@ public function testCanCreateCaptureRequestWithTimeout() $messageFactory = $this->getMessageFactory(); $captureRequest = $messageFactory->createCaptureRequest(null, 'GET', $timeout); - $this->assertSame($timeout, $captureRequest->getTimeout()); + $this->assertEquals($timeout, $captureRequest->getTimeout()); } /** diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php index 32b1dbe..089a174 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php @@ -34,7 +34,7 @@ public function testPdfTypeIsReturnedByDefaultIfNotTypeIsSet() { $pdfRequest = $this->getPdfRequest(); - $this->assertSame(RequestInterface::REQUEST_TYPE_PDF, $pdfRequest->getType()); + $this->assertEquals(RequestInterface::REQUEST_TYPE_PDF, $pdfRequest->getType()); } /** @@ -50,7 +50,7 @@ public function testCustomTypeCanBeSet() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setType($requestType); - $this->assertSame($requestType, $pdfRequest->getType()); + $this->assertEquals($requestType, $pdfRequest->getType()); } /** @@ -64,7 +64,7 @@ public function testUrlCanBeSetViaConstructor() $url = 'http://test.com'; $pdfRequest = $this->getPdfRequest($url); - $this->assertSame($url, $pdfRequest->getUrl()); + $this->assertEquals($url, $pdfRequest->getUrl()); } /** @@ -78,7 +78,7 @@ public function testMethodCanBeSetViaConstructor() $method = 'GET'; $pdfRequest = $this->getPdfRequest(null, $method); - $this->assertSame($method, $pdfRequest->getMethod()); + $this->assertEquals($method, $pdfRequest->getMethod()); } /** @@ -92,7 +92,7 @@ public function testTimeoutCanBeSetViaConstructor() $timeout = 100000; $pdfRequest = $this->getPdfRequest('http://test.com', 'GET', $timeout); - $this->assertSame($timeout, $pdfRequest->getTimeout()); + $this->assertEquals($timeout, $pdfRequest->getTimeout()); } /** @@ -131,7 +131,7 @@ public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet() $pdfRequest->setUrl($url); $pdfRequest->setRequestData($data); - $this->assertSame($url, $pdfRequest->getUrl()); + $this->assertEquals($url, $pdfRequest->getUrl()); } /** @@ -157,7 +157,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsGet() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $pdfRequest->getUrl()); + $this->assertEquals($expectedUrl, $pdfRequest->getUrl()); } /** @@ -183,7 +183,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsHead() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $pdfRequest->getUrl()); + $this->assertEquals($expectedUrl, $pdfRequest->getUrl()); } /** @@ -209,7 +209,7 @@ public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams( $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $pdfRequest->getUrl()); + $this->assertEquals($expectedUrl, $pdfRequest->getUrl()); } /** @@ -230,7 +230,7 @@ public function testRequestContainsNoBodyIfMethodIsGet() $pdfRequest->setMethod('GET'); $pdfRequest->setRequestData($data); - $this->assertSame('', $pdfRequest->getBody()); + $this->assertEquals('', $pdfRequest->getBody()); } /** @@ -251,7 +251,7 @@ public function testRequestContainsNoBodyIfMethodIsHead() $pdfRequest->setMethod('HEAD'); $pdfRequest->setRequestData($data); - $this->assertSame('', $pdfRequest->getBody()); + $this->assertEquals('', $pdfRequest->getBody()); } /** @@ -274,7 +274,7 @@ public function testRequestContainsABodyIfMethodIsNotHeadOrGet() $body = 'test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($body, $pdfRequest->getBody()); + $this->assertEquals($body, $pdfRequest->getBody()); } /** @@ -302,7 +302,7 @@ public function testRequestDataCanBeFalttened() 'test_param2[1]' => 'Testing3' ); - $this->assertSame($flatData, $pdfRequest->getRequestData(true)); + $this->assertEquals($flatData, $pdfRequest->getRequestData(true)); } /** @@ -324,7 +324,7 @@ public function testRawRequestDataCanBeAccessed() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setRequestData($data); - $this->assertSame($data, $pdfRequest->getRequestData(false)); + $this->assertEquals($data, $pdfRequest->getRequestData(false)); } /** @@ -350,7 +350,7 @@ public function testHeadersCanBeAdded() $expectedHeaders = array_merge($existingHeaders, $newHeaders); - $this->assertSame($expectedHeaders, $pdfRequest->getHeaders()); + $this->assertEquals($expectedHeaders, $pdfRequest->getHeaders()); } /** @@ -372,7 +372,7 @@ public function testHeadersCanBeAccessedInJsonFormat() $expectedHeaders = json_encode($headers); - $this->assertSame($expectedHeaders, $pdfRequest->getHeaders('json')); + $this->assertEquals($expectedHeaders, $pdfRequest->getHeaders('json')); } /** @@ -391,7 +391,7 @@ public function testRawHeadersCanBeAccessed() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setHeaders($headers); - $this->assertSame($headers, $pdfRequest->getHeaders('default')); + $this->assertEquals($headers, $pdfRequest->getHeaders('default')); } /** @@ -424,7 +424,7 @@ public function testCanSetOutputFile() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setOutputFile($outputFile); - $this->assertSame($outputFile, $pdfRequest->getOutputFile()); + $this->assertEquals($outputFile, $pdfRequest->getOutputFile()); } /** @@ -441,7 +441,7 @@ public function testCanSetViewportWidth() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setViewportSize($width, $height); - $this->assertSame($width, $pdfRequest->getViewportWidth()); + $this->assertEquals($width, $pdfRequest->getViewportWidth()); } /** @@ -458,7 +458,7 @@ public function testCanSetViewportHeight() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setViewportSize($width, $height); - $this->assertSame($height, $pdfRequest->getViewportHeight()); + $this->assertEquals($height, $pdfRequest->getViewportHeight()); } /** @@ -475,7 +475,7 @@ public function testCanSetPaperWidth() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setPaperSize($width, $height); - $this->assertSame($width, $pdfRequest->getPaperWidth()); + $this->assertEquals($width, $pdfRequest->getPaperWidth()); } /** @@ -492,7 +492,7 @@ public function testCanSetPaperHeight() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setPaperSize($width, $height); - $this->assertSame($height, $pdfRequest->getPaperHeight()); + $this->assertEquals($height, $pdfRequest->getPaperHeight()); } /** +++++++++++++++++++++++++++++++++++ **/ diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php index b0d2c46..54b0e56 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php @@ -34,7 +34,7 @@ public function testDefaultTypeIsReturnedByDefaultIfNotTypeIsSet() { $request = $this->getRequest(); - $this->assertSame(RequestInterface::REQUEST_TYPE_DEFAULT, $request->getType()); + $this->assertEquals(RequestInterface::REQUEST_TYPE_DEFAULT, $request->getType()); } /** @@ -50,7 +50,7 @@ public function testCustomTypeCanBeSet() $request = $this->getRequest(); $request->setType($requestType); - $this->assertSame($requestType, $request->getType()); + $this->assertEquals($requestType, $request->getType()); } /** @@ -64,7 +64,7 @@ public function testUrlCanBeSetViaConstructor() $url = 'http://test.com'; $request = $this->getRequest($url); - $this->assertSame($url, $request->getUrl()); + $this->assertEquals($url, $request->getUrl()); } /** @@ -78,7 +78,7 @@ public function testMethodCanBeSetViaConstructor() $method = 'GET'; $request = $this->getRequest(null, $method); - $this->assertSame($method, $request->getMethod()); + $this->assertEquals($method, $request->getMethod()); } /** @@ -92,7 +92,7 @@ public function testTimeoutCanBeSetViaConstructor() $timeout = 100000; $request = $this->getRequest('http://test.com', 'GET', $timeout); - $this->assertSame($timeout, $request->getTimeout()); + $this->assertEquals($timeout, $request->getTimeout()); } /** @@ -131,7 +131,7 @@ public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet() $request->setUrl($url); $request->setRequestData($data); - $this->assertSame($url, $request->getUrl()); + $this->assertEquals($url, $request->getUrl()); } /** @@ -157,7 +157,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsGet() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $request->getUrl()); + $this->assertEquals($expectedUrl, $request->getUrl()); } /** @@ -183,7 +183,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsHead() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $request->getUrl()); + $this->assertEquals($expectedUrl, $request->getUrl()); } /** @@ -209,7 +209,7 @@ public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams( $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $request->getUrl()); + $this->assertEquals($expectedUrl, $request->getUrl()); } /** @@ -230,7 +230,7 @@ public function testRequestContainsNoBodyIfMethodIsGet() $request->setMethod('GET'); $request->setRequestData($data); - $this->assertSame('', $request->getBody()); + $this->assertEquals('', $request->getBody()); } /** @@ -251,7 +251,7 @@ public function testRequestContainsNoBodyIfMethodIsHead() $request->setMethod('HEAD'); $request->setRequestData($data); - $this->assertSame('', $request->getBody()); + $this->assertEquals('', $request->getBody()); } /** @@ -274,7 +274,7 @@ public function testRequestContainsABodyIfMethodIsNotHeadOrGet() $body = 'test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($body, $request->getBody()); + $this->assertEquals($body, $request->getBody()); } /** @@ -302,7 +302,7 @@ public function testRequestDataCanBeFalttened() 'test_param2[1]' => 'Testing3' ); - $this->assertSame($flatData, $request->getRequestData(true)); + $this->assertEquals($flatData, $request->getRequestData(true)); } /** @@ -324,7 +324,7 @@ public function testRawRequestDataCanBeAccessed() $request = $this->getRequest(); $request->setRequestData($data); - $this->assertSame($data, $request->getRequestData(false)); + $this->assertEquals($data, $request->getRequestData(false)); } /** @@ -350,7 +350,7 @@ public function testHeadersCanBeAdded() $expectedHeaders = array_merge($existingHeaders, $newHeaders); - $this->assertSame($expectedHeaders, $request->getHeaders()); + $this->assertEquals($expectedHeaders, $request->getHeaders()); } /** @@ -372,7 +372,7 @@ public function testHeadersCanBeAccessedInJsonFormat() $expectedHeaders = json_encode($headers); - $this->assertSame($expectedHeaders, $request->getHeaders('json')); + $this->assertEquals($expectedHeaders, $request->getHeaders('json')); } /** @@ -391,7 +391,48 @@ public function testRawHeadersCanBeAccessed() $request = $this->getRequest(); $request->setHeaders($headers); - $this->assertSame($headers, $request->getHeaders('default')); + $this->assertEquals($headers, $request->getHeaders('default')); + } + + /** + * Test can add setting. + * + * @access public + * @return void + */ + public function testCanAddSetting() + { + $request = $this->getRequest(); + $request->addSetting('userAgent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36'); + $request->addSetting('localToRemoteUrlAccessEnabled', 'true'); + $request->addSetting('resourceTimeout', 3000); + + $expected = array( + 'userAgent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36', + 'localToRemoteUrlAccessEnabled' => 'true', + 'resourceTimeout' => 3000 + ); + + $this->assertEquals($expected, $request->getSettings()); + } + + /** + * Test set timeout sets resource + * timeout in settings + * + * @access public + * @return void + */ + public function testSetTimeoutSetsResourceTimeoutInSettings() + { + $request = $this->getRequest(); + $request->setTimeout(1000); + + $expected = array( + 'resourceTimeout' => 1000 + ); + + $this->assertEquals($expected, $request->getSettings()); } /** @@ -405,10 +446,10 @@ public function testCanSetViewportWidth() $width = 100; $height = 200; - $caputreRequest = $this->getRequest(); - $caputreRequest->setViewportSize($width, $height); + $request = $this->getRequest(); + $request->setViewportSize($width, $height); - $this->assertSame($width, $caputreRequest->getViewportWidth()); + $this->assertEquals($width, $request->getViewportWidth()); } /** @@ -422,10 +463,10 @@ public function testCanSetViewportHeight() $width = 100; $height = 200; - $caputreRequest = $this->getRequest(); - $caputreRequest->setViewportSize($width, $height); + $request = $this->getRequest(); + $request->setViewportSize($width, $height); - $this->assertSame($height, $caputreRequest->getViewportHeight()); + $this->assertEquals($height, $request->getViewportHeight()); } /** +++++++++++++++++++++++++++++++++++ **/ diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php index 94c6837..05cad4a 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php @@ -37,7 +37,7 @@ public function testStatusCanBeImported() $response = $this->getResponse(); $response->import($data); - $this->assertSame(200, $response->getStatus()); + $this->assertEquals(200, $response->getStatus()); } /** @@ -55,7 +55,7 @@ public function testContentCanBeImported() $response = $this->getResponse(); $response->import($data); - $this->assertSame('Test content', $response->getContent()); + $this->assertEquals('Test content', $response->getContent()); } /** @@ -73,7 +73,7 @@ public function testContentTypeCanBeImported() $response = $this->getResponse(); $response->import($data); - $this->assertSame('text/html', $response->getContentType()); + $this->assertEquals('text/html', $response->getContentType()); } /** @@ -91,7 +91,7 @@ public function testUrlCanBeImported() $response = $this->getResponse(); $response->import($data); - $this->assertSame('http://test.com', $response->getUrl()); + $this->assertEquals('http://test.com', $response->getUrl()); } /** @@ -109,7 +109,7 @@ public function testRedirectUrlCanBeImported() $response = $this->getResponse(); $response->import($data); - $this->assertSame('http://test.com', $response->getRedirectUrl()); + $this->assertEquals('http://test.com', $response->getRedirectUrl()); } /** @@ -127,7 +127,7 @@ public function testTimeCanBeImported() $response = $this->getResponse(); $response->import($data); - $this->assertSame(123456789, $response->getTime()); + $this->assertEquals(123456789, $response->getTime()); } /** @@ -156,7 +156,7 @@ public function testHeadersCanBeImported() $headers[0]['name'] => $headers[0]['value'] ); - $this->assertSame($expectedHeaders, $response->getHeaders()); + $this->assertEquals($expectedHeaders, $response->getHeaders()); } /** @@ -194,7 +194,7 @@ public function testCanGetHeader() $response = $this->getResponse(); $response->import($data); - $this->assertSame('Test Header 1', $response->getHeader('Header1')); + $this->assertEquals('Test Header 1', $response->getHeader('Header1')); } /** From 78887bafdd2514c6e9ec90decb8eb7468a4929f9 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Wed, 16 Nov 2016 11:37:35 +0000 Subject: [PATCH 43/54] Added support for cookie management. Can now add and delete cookies - https://github.com/jonnnnyw/php-phantomjs/issues/124 --- src/JonnyW/PhantomJs/Http/AbstractRequest.php | 70 +++++++ .../PhantomJs/Http/RequestInterface.php | 16 ++ .../Resources/procedures/http_default.proc | 6 +- .../Resources/procedures/http_lazy.proc | 6 +- .../Resources/procedures/page_cookies.partial | 23 +++ .../Tests/Integration/ClientTest.php | 175 +++++++++++++++--- .../PhantomJs/Tests/Unit/Http/RequestTest.php | 72 +++++++ 7 files changed, 338 insertions(+), 30 deletions(-) create mode 100644 src/JonnyW/PhantomJs/Resources/procedures/page_cookies.partial diff --git a/src/JonnyW/PhantomJs/Http/AbstractRequest.php b/src/JonnyW/PhantomJs/Http/AbstractRequest.php index 237d8e4..71c3eb0 100644 --- a/src/JonnyW/PhantomJs/Http/AbstractRequest.php +++ b/src/JonnyW/PhantomJs/Http/AbstractRequest.php @@ -36,6 +36,14 @@ abstract class AbstractRequest */ protected $settings; + /** + * Cookies + * + * @var array + * @access protected + */ + protected $cookies; + /** * Request data * @@ -118,6 +126,11 @@ public function __construct($url = null, $method = RequestInterface::METHOD_GET, $this->viewportWidth = 0; $this->viewportHeight = 0; + $this->cookies = array( + 'add' => array(), + 'delete' => array() + ); + $this->setMethod($method); $this->setTimeout($timeout); @@ -419,6 +432,63 @@ public function getSettings() return $this->settings; } + /** + * Add cookie. + * + * @access public + * @param string $name + * @param mixed $value + * @param string $path + * @param string $domain + * @param bool $httpOnly (default: true) + * @param bool $secure (default: false) + * @param int $expires (default: null) + * @return \JonnyW\PhantomJs\Http\AbstractRequest + */ + public function addCookie($name, $value, $path, $domain, $httpOnly = true, $secure = false, $expires = null) + { + $filter = function ($value) { + return !is_null($value); + }; + + $this->cookies['add'][] = array_filter(array( + 'name' => $name, + 'value' => $value, + 'path' => $path, + 'domain' => $domain, + 'httponly' => $httpOnly, + 'secure' => $secure, + 'expires' => $expires + ), $filter); + + return $this; + } + + /** + * Delete cookie. + * + * @access public + * @param string $name + * @return \JonnyW\PhantomJs\Http\AbstractRequest + */ + public function deleteCookie($name) + { + $this->cookies['delete'][] = $name; + + return $this; + } + + /** + * Get cookies + * + * @access public + * @return array + */ + public function getCookies() + { + return $this->cookies; + } + /** * Set body styles * diff --git a/src/JonnyW/PhantomJs/Http/RequestInterface.php b/src/JonnyW/PhantomJs/Http/RequestInterface.php index 3416336..c1f0918 100644 --- a/src/JonnyW/PhantomJs/Http/RequestInterface.php +++ b/src/JonnyW/PhantomJs/Http/RequestInterface.php @@ -184,6 +184,22 @@ public function addHeaders(array $headers); */ public function getHeaders(); + /** + * Get settings + * + * @access public + * @return array|string + */ + public function getSettings(); + + /** + * Get cookies + * + * @access public + * @return array|string + */ + public function getCookies(); + /** * Set body styles * diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc index 514ee18..c08b8fb 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc @@ -32,7 +32,6 @@ var page = require('webpage').create(), */ [[ engine.load('page_viewport_size') ]] - /** * Define custom headers. */ @@ -43,6 +42,11 @@ var page = require('webpage').create(), */ [[ engine.load('page_settings') ]] +/** + * Page cookies + */ +[[ engine.load('page_cookies') ]] + /** * On resource timeout */ diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc index 7365e39..115ee34 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc @@ -34,7 +34,6 @@ var page = require('webpage').create(), */ [[ engine.load('page_viewport_size') ]] - /** * Define custom headers. */ @@ -45,6 +44,11 @@ var page = require('webpage').create(), */ [[ engine.load('page_settings') ]] +/** + * Page cookies + */ +[[ engine.load('page_cookies') ]] + /** * On resource timeout */ diff --git a/src/JonnyW/PhantomJs/Resources/procedures/page_cookies.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_cookies.partial new file mode 100644 index 0000000..2ca867b --- /dev/null +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_cookies.partial @@ -0,0 +1,23 @@ + +var cookies = {{ input.getCookies()|json_encode() }}; + +cookies.delete.forEach(function(name) { + + if(name == '*') { + page.clearCookies(); + debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Deleted all cookies'); + } else { + + if(page.deleteCookie(name)) { + debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Deleted cookie ' + name); + } + } +}); + + +cookies.add.forEach(function(cookie) { + + if(page.addCookie(cookie)) { + debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Added cookie ' + cookie.name + '=' + cookie.value); + } +}); diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 0a5c973..ec4e9cd 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -157,7 +157,7 @@ public function testResponseContains200StatusCodeIfPageIsSuccessfullyLoaded() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $client->send($request, $response); @@ -179,7 +179,7 @@ public function testResponseContains200StatusCodeIfRequestUrlContainsReservedCha $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->setRequestData(array( 'test1' => 'http://test.com', 'test2' => 'A string with an \' ) / # some other invalid [ characters.' @@ -205,7 +205,7 @@ public function testResponseContainsValidBodyIfPageIsSuccessfullyLoaded() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $client->send($request, $response); @@ -226,7 +226,7 @@ public function testCanSetUserAgentInSettings() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->addSetting('userAgent', 'PhantomJS TEST'); $client->send($request, $response); @@ -234,6 +234,125 @@ public function testCanSetUserAgentInSettings() $this->assertContains('userAgent=PhantomJS TEST', $response->getContent()); } + /** + * Test can add cookies to request + * + * @access public + * @return void + */ + public function testCanAddCookiesToRequest() + { + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi'); + + $client->send($request, $response); + + $this->assertContains('cookie_test_cookie=TESTING_COOKIES', $response->getContent()); + } + + /** + * Test can load cookies from + * persistent cookie file + * + * @access public + * @return void + */ + public function testCanLoadCookiesFromPersistentCookieFile() + { + $this->filename = 'cookies.txt'; + $file = ($this->directory . '/' . $this->filename); + + $client = $this->getClient(); + $client->getEngine()->addOption('--cookies-file=' . $file); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + + $client->send($request, $response); + + $this->assertContains('test_cookie=TESTING_COOKIES; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file)); + } + + /** + * Test can delete cookie from + * persistent cookie file + * + * @access public + * @return void + */ + public function testCanDeleteCookieFromPersistentCookieFile() + { + $this->filename = 'cookies.txt'; + $file = ($this->directory . '/' . $this->filename); + + $client = $this->getClient(); + $client->getEngine()->addOption('--cookies-file=' . $file); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + + $client->send($request, $response); + + $request = $client->getMessageFactory()->createRequest(); + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->deleteCookie('test_cookie'); + + $client->send($request, $response); + + $this->assertNotContains('test_cookie=TESTING_COOKIES; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/)', file_get_contents($file)); + } + + /** + * Test can delete all cookies from + * persistent cookie file + * + * @access public + * @return void + */ + public function testCanDeleteAllCookiesFromPersistentCookieFile() + { + $this->filename = 'cookies.txt'; + $file = ($this->directory . '/' . $this->filename); + + $client = $this->getClient(); + $client->getEngine()->addOption('--cookies-file=' . $file); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->addCookie('test_cookie_1', 'TESTING_COOKIES_1', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + $request->addCookie('test_cookie_2', 'TESTING_COOKIES_2', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + + $client->send($request, $response); + + $request = $client->getMessageFactory()->createRequest(); + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->deleteCookie('*'); + + $client->send($request, $response); + + $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)); + $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)); + } + /** * Test response contains console error if a * javascript error exists on the page. @@ -249,7 +368,7 @@ public function testResponseContainsConsoleErrorIfAJavascriptErrorExistsOnThePag $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php'); $client->send($request, $response); @@ -274,7 +393,7 @@ public function testResponseContainsConsoleTraceIfAJavascriptErrorExistsOnThePag $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php'); $client->send($request, $response); @@ -297,7 +416,7 @@ public function testResponseContainsHeaders() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php'); $client->send($request, $response); @@ -340,7 +459,7 @@ public function testPostRequestSendsRequestData() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('POST'); - $request->setUrl('http://jonnyw.kiwi/tests/test-post.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-post.php'); $request->setRequestData(array( 'test1' => 'http://test.com', 'test2' => 'A string with an \' ) / # some other invalid [ characters.' @@ -370,7 +489,7 @@ public function testCaptureRequestSavesFileToLocalDisk() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $client->send($request, $response); @@ -399,7 +518,7 @@ public function testCaptureRequestSavesFileToDiskWithCorrectCaptureDimensions() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $request->setCaptureDimensions($width, $height); @@ -429,7 +548,7 @@ public function testPdfRequestSavesPdfToLocalDisk() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $client->send($request, $response); @@ -458,7 +577,7 @@ public function testPdfRequestSavesFileToDiskWithCorrectPaperSize() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $request->setPaperSize(sprintf('%scm', $width), sprintf('%scm', $height)); $request->setMargin('0cm'); @@ -492,7 +611,7 @@ public function testPdfRequestSavesFileToDiskWithCorrectFormatSize() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setMargin('0cm'); @@ -526,7 +645,7 @@ public function testPdfRequestSavesFileToDiskWithCorrectOrientation() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -561,7 +680,7 @@ public function testCanSetRepeatingHeaderForPDFRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -597,7 +716,7 @@ public function testCanSetRepeatingFooterForPDFRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -634,7 +753,7 @@ public function testSetViewportSizeSetsSizeOfViewportInDefaultRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->setViewportsize($width, $height); $client->send($request, $response); @@ -665,7 +784,7 @@ public function testSetViewportSizeSetsSizeOfViewportInCaptureRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->setViewportsize($width, $height); $client->send($request, $response); @@ -694,7 +813,7 @@ public function testDelayLogsStartTimeInClientForDefaultRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->setDelay($delay); $client->send($request, $response); @@ -723,7 +842,7 @@ public function testDelayLogsEndTimeInClientForDefaultRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->setDelay($delay); $client->send($request, $response); @@ -752,7 +871,7 @@ public function testDelayDelaysPageRenderForSpecifiedTimeForDefaultRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $request->setDelay($delay); $client->send($request, $response); @@ -785,7 +904,7 @@ public function testDelayLogsStartTimeInClientForCaptureRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setDelay($delay); $client->send($request, $response); @@ -814,7 +933,7 @@ public function testDelayLogsEndTimeInClientForCaptureRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setDelay($delay); $client->send($request, $response); @@ -843,7 +962,7 @@ public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setDelay($delay); $client->send($request, $response); @@ -875,7 +994,7 @@ public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-lazy.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php'); $request->setTimeout(5000); $client->send($request, $response); @@ -900,7 +1019,7 @@ public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResou $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-lazy.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php'); $request->setTimeout(1000); $client->send($request, $response); @@ -924,7 +1043,7 @@ public function testDebugLogsDebugInfoToClientLog() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); $client->send($request, $response); @@ -949,7 +1068,7 @@ public function testCanSetPageBackgroundColor() $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); $request->setBodyStyles(array('backgroundColor' => 'red')); $request->setOutputFile($file); diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php index 54b0e56..3ffc1a7 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php @@ -435,6 +435,78 @@ public function testSetTimeoutSetsResourceTimeoutInSettings() $this->assertEquals($expected, $request->getSettings()); } + /** + * Test can add cookies. + * + * @access public + * @return void + */ + public function testCanAddCookies() + { + $name = 'test_cookie'; + $value = 'TESTING_COOKIES'; + $path = '/'; + $domain = 'localhost'; + $httpOnly = false; + $secure = true; + $expires = time() + 3600; + + $request = $this->getRequest(); + $request->addCookie( + $name, + $value, + $path, + $domain, + $httpOnly, + $secure, + $expires + ); + + $expected = array( + 'name' => $name, + 'value' => $value, + 'path' => $path, + 'domain' => $domain, + 'httponly' => $httpOnly, + 'secure' => $secure, + 'expires' => $expires + ); + + $this->assertEquals(array($expected), $request->getCookies()['add']); + } + + /** + * Test can delete cookies. + * + * @access public + * @return void + */ + public function testCanDeleteCookies() + { + $name = 'test_cookie'; + $value = 'TESTING_COOKIES'; + $path = '/'; + $domain = 'localhost'; + $httpOnly = false; + $secure = true; + $expires = time() + 3600; + + $request = $this->getRequest(); + $request->addCookie( + $name, + $value, + $path, + $domain, + $httpOnly, + $secure, + $expires + ); + + $request->deleteCookie($name); + + $this->assertEquals(array($name), $request->getCookies()['delete']); + } + /** * Test can set viewport width. * From 95cfd7a72ce3cec5107fd88ac2292a8447c2541a Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Wed, 16 Nov 2016 12:03:42 +0000 Subject: [PATCH 44/54] Removing PHP5.6 specific code --- .../PhantomJs/Tests/Integration/ClientTest.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index ec4e9cd..40f1480 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -274,9 +274,11 @@ public function testCanLoadCookiesFromPersistentCookieFile() $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); + $expireAt = strtotime('16-Nov-2020 00:00:00'); + $request->setMethod('GET'); $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); - $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $client->send($request, $response); @@ -301,9 +303,11 @@ public function testCanDeleteCookieFromPersistentCookieFile() $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); + $expireAt = strtotime('16-Nov-2020 00:00:00'); + $request->setMethod('GET'); $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); - $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $client->send($request, $response); @@ -335,10 +339,12 @@ public function testCanDeleteAllCookiesFromPersistentCookieFile() $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); + $expireAt = strtotime('16-Nov-2020 00:00:00'); + $request->setMethod('GET'); $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); - $request->addCookie('test_cookie_1', 'TESTING_COOKIES_1', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); - $request->addCookie('test_cookie_2', 'TESTING_COOKIES_2', '/', '.jonnyw.kiwi', true, false, ((new \DateTime('16-Nov-2020 00:00:00'))->getTimestamp() * 1000)); + $request->addCookie('test_cookie_1', 'TESTING_COOKIES_1', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); + $request->addCookie('test_cookie_2', 'TESTING_COOKIES_2', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $client->send($request, $response); From a89abbcd9c0bb83bd58aa2916f45f950f90047eb Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Wed, 16 Nov 2016 12:07:52 +0000 Subject: [PATCH 45/54] Removing PHP5.6 specific code --- src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php index 3ffc1a7..a3b3b75 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/RequestTest.php @@ -471,8 +471,10 @@ public function testCanAddCookies() 'secure' => $secure, 'expires' => $expires ); - - $this->assertEquals(array($expected), $request->getCookies()['add']); + + $cookies = $request->getCookies(); + + $this->assertEquals(array($expected), $cookies['add']); } /** @@ -504,7 +506,9 @@ public function testCanDeleteCookies() $request->deleteCookie($name); - $this->assertEquals(array($name), $request->getCookies()['delete']); + $cookies = $request->getCookies(); + + $this->assertEquals(array($name), $cookies['delete']); } /** From a23253fd453b4c030edd8ebe6200cabb8dd4a85a Mon Sep 17 00:00:00 2001 From: "Jens A. Koch" Date: Tue, 10 Jan 2017 11:13:43 +0100 Subject: [PATCH 46/54] updating jakoch/phantomjs-installer to 2.1.1-p08 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index cefd8cd..8023365 100644 --- a/composer.json +++ b/composer.json @@ -19,7 +19,7 @@ "symfony/filesystem": "~2.3|~3.0", "symfony/yaml": "~2.3|~3.0", "twig/twig": "~1.16", - "jakoch/phantomjs-installer": "^2.1" + "jakoch/phantomjs-installer": "2.1.1-p08" }, "require-dev": { "phpunit/phpunit": "~4.0", From 7abe78269e8af8b84e405d3cd46f285258e10a33 Mon Sep 17 00:00:00 2001 From: Mathijs Miermans Date: Wed, 18 Jan 2017 14:29:14 -0800 Subject: [PATCH 47/54] Added networkRequest to onResourceRequested This parameter can be used to cancel the request. --- src/JonnyW/PhantomJs/Resources/procedures/http_default.proc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc index c08b8fb..19a11f3 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc @@ -57,7 +57,7 @@ page.onResourceTimeout = function (error) { /** * On resource requested */ -page.onResourceRequested = function (resource) { +page.onResourceRequested = function (resource, networkRequest) { [[ engine.load('page_on_resource_requested') ]] }; @@ -98,4 +98,4 @@ procedure.execute = function (status) { }; {% endautoescape %} -[% endautoescape %] \ No newline at end of file +[% endautoescape %] From e884a57a5fe2ec1fef55704692d85bff10f1c812 Mon Sep 17 00:00:00 2001 From: Andrius Petrauskis Date: Mon, 10 Apr 2017 15:49:21 +0300 Subject: [PATCH 48/54] Introduce ability to get cookies from response --- src/JonnyW/PhantomJs/Http/Response.php | 19 ++++++++++ .../PhantomJs/Http/ResponseInterface.php | 8 +++++ .../procedures/phantom_on_error.partial | 1 + .../procedures/procedure_capture.partial | 1 + .../procedures/procedure_default.partial | 1 + .../procedures/procedure_pdf.partial | 1 + .../Tests/Integration/ClientTest.php | 35 +++++++++++++++++++ .../Tests/Unit/Http/ResponseTest.php | 19 ++++++++++ 8 files changed, 85 insertions(+) diff --git a/src/JonnyW/PhantomJs/Http/Response.php b/src/JonnyW/PhantomJs/Http/Response.php index 9ec5291..ea36cef 100644 --- a/src/JonnyW/PhantomJs/Http/Response.php +++ b/src/JonnyW/PhantomJs/Http/Response.php @@ -82,6 +82,14 @@ class Response */ public $console; + /** + * Session cookies + * + * @var array + * @access public + */ + public $cookies; + /** * Import response data * @@ -247,4 +255,15 @@ public function getConsole() { return $this->console; } + + /** + * Get session cookies + * + * @access public + * @return array + */ + public function getCookies() + { + return $this->cookies; + } } diff --git a/src/JonnyW/PhantomJs/Http/ResponseInterface.php b/src/JonnyW/PhantomJs/Http/ResponseInterface.php index ea693dd..1908ce7 100644 --- a/src/JonnyW/PhantomJs/Http/ResponseInterface.php +++ b/src/JonnyW/PhantomJs/Http/ResponseInterface.php @@ -96,4 +96,12 @@ public function isRedirect(); * @return string */ public function getTime(); + + /** + * Get session cookies + * + * @access public + * @return array + */ + public function getCookies(); } diff --git a/src/JonnyW/PhantomJs/Resources/procedures/phantom_on_error.partial b/src/JonnyW/PhantomJs/Resources/procedures/phantom_on_error.partial index 2d1191c..13ba163 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/phantom_on_error.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/phantom_on_error.partial @@ -8,6 +8,7 @@ trace.forEach(function(t) { response.status = 500; response.content = msg; response.console = stack; +response.cookies = phantom.cookies; system.stdout.write(JSON.stringify(response, undefined, 4)); phantom.exit(1); diff --git a/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial b/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial index 5450e9d..fab1e67 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial @@ -20,6 +20,7 @@ if (status === 'success') { } response.console = logs; +response.cookies = phantom.cookies; system.stderr.write(debug.join('\\n') + '\\n'); system.stdout.write(JSON.stringify(response, undefined, 4)); diff --git a/src/JonnyW/PhantomJs/Resources/procedures/procedure_default.partial b/src/JonnyW/PhantomJs/Resources/procedures/procedure_default.partial index 3b2fde3..c30bffe 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/procedure_default.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/procedure_default.partial @@ -15,6 +15,7 @@ if (status === 'success') { } response.console = logs; +response.cookies = phantom.cookies; system.stderr.write(debug.join('\\n') + '\\n'); system.stdout.write(JSON.stringify(response, undefined, 4)); diff --git a/src/JonnyW/PhantomJs/Resources/procedures/procedure_pdf.partial b/src/JonnyW/PhantomJs/Resources/procedures/procedure_pdf.partial index ac830f5..c0783ab 100644 --- a/src/JonnyW/PhantomJs/Resources/procedures/procedure_pdf.partial +++ b/src/JonnyW/PhantomJs/Resources/procedures/procedure_pdf.partial @@ -17,6 +17,7 @@ if (status === 'success') { } response.console = logs; +response.cookies = phantom.cookies; system.stderr.write(debug.join('\\n') + '\\n'); system.stdout.write(JSON.stringify(response, undefined, 4)); diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 40f1480..12c0128 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -359,6 +359,41 @@ public function testCanDeleteAllCookiesFromPersistentCookieFile() $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)); } + + /** + * Test can load cookies from + * persistent cookie file + * + * @access public + * @return void + */ + public function testCookiesPresentInResponse() + { + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $expireAt = strtotime('16-Nov-2020 00:00:00'); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); + + $client->send($request, $response); + + $this->assertEquals(array( + 'domain' => '.jonnyw.kiwi', + 'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT', + 'expiry' => '1605481200', + 'httponly' => true, + 'name' => 'test_cookie', + 'path' => '/', + 'secure' => false, + 'value' => 'TESTING_COOKIES', + ), $response->getCookies()[0]); + } + /** * Test response contains console error if a * javascript error exists on the page. diff --git a/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php b/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php index 05cad4a..8a7c3cb 100644 --- a/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php +++ b/src/JonnyW/PhantomJs/Tests/Unit/Http/ResponseTest.php @@ -368,6 +368,25 @@ public function testIsNotRedirectIfStatusCodeIsNotRedirect() $this->assertFalse($response->isRedirect()); } + /** + * Test if cookies can be parsed and imported + * + * @access public + * @return void + */ + public function testCookiesCanBeImported() + { + $cookie = 'cookie=TESTING; HttpOnly; expires=Mon, 16-Nov-2020 00:00:00 GMT; domain=.jonnyw.kiwi; path=/'; + $data = array( + 'cookies' => array($cookie) + ); + + $response = $this->getResponse(); + $response->import($data); + + $this->assertContains($cookie, $response->getCookies()); + } + /** +++++++++++++++++++++++++++++++++++ **/ /** ++++++++++ TEST ENTITIES ++++++++++ **/ /** +++++++++++++++++++++++++++++++++++ **/ From ea0db4f07b41473520573a0cdca5e03798997e68 Mon Sep 17 00:00:00 2001 From: Andrius Petrauskis Date: Mon, 10 Apr 2017 16:04:15 +0300 Subject: [PATCH 49/54] Update timestamp value in test --- src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 12c0128..8e8da5a 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -385,7 +385,7 @@ public function testCookiesPresentInResponse() $this->assertEquals(array( 'domain' => '.jonnyw.kiwi', 'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT', - 'expiry' => '1605481200', + 'expiry' => '1605477600', 'httponly' => true, 'name' => 'test_cookie', 'path' => '/', From 17c50b75fc6b8adc847c26ef60cd5227f39e51ba Mon Sep 17 00:00:00 2001 From: Andrius Petrauskis Date: Mon, 10 Apr 2017 16:10:32 +0300 Subject: [PATCH 50/54] Fix test for PHP5.3 --- src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 8e8da5a..021c344 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -382,6 +382,7 @@ public function testCookiesPresentInResponse() $client->send($request, $response); + $cookies = $response->getCookies(); $this->assertEquals(array( 'domain' => '.jonnyw.kiwi', 'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT', @@ -391,7 +392,7 @@ public function testCookiesPresentInResponse() 'path' => '/', 'secure' => false, 'value' => 'TESTING_COOKIES', - ), $response->getCookies()[0]); + ), $cookies[0]); } /** From 69f9333a244371f7771b8f50f0e5669823d72e8c Mon Sep 17 00:00:00 2001 From: Andrius Petrauskis Date: Mon, 10 Apr 2017 16:11:05 +0300 Subject: [PATCH 51/54] Adjust timestamp in test to Travis timezone --- src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 021c344..2b9af50 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -386,7 +386,7 @@ public function testCookiesPresentInResponse() $this->assertEquals(array( 'domain' => '.jonnyw.kiwi', 'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT', - 'expiry' => '1605477600', + 'expiry' => '1605484800', 'httponly' => true, 'name' => 'test_cookie', 'path' => '/', From b3c3e20857caf9a36eb90fb1a7cf1e1f1ec4b672 Mon Sep 17 00:00:00 2001 From: Jonny Wenmoth Date: Sat, 22 Apr 2017 22:24:02 +0100 Subject: [PATCH 52/54] Trying to user local install of phpunit --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c55dcba..711588b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,7 +16,7 @@ before_script: - phpenv rehash script: - - phpunit --coverage-clover=coverage.clover + - bin/phpunit --coverage-clover=coverage.clover after_script: - wget https://scrutinizer-ci.com/ocular.phar From 0f56dd5aae630324dfbc95b55407589ff41305a3 Mon Sep 17 00:00:00 2001 From: Sergii Bondarenko Date: Wed, 7 Mar 2018 13:47:02 +0200 Subject: [PATCH 53/54] Remove wrongly overridden "load()" method but preserve the logic --- .../DependencyInjection/ServiceContainer.php | 31 ++++++------------- 1 file changed, 10 insertions(+), 21 deletions(-) diff --git a/src/JonnyW/PhantomJs/DependencyInjection/ServiceContainer.php b/src/JonnyW/PhantomJs/DependencyInjection/ServiceContainer.php index 1b4d586..3340d80 100644 --- a/src/JonnyW/PhantomJs/DependencyInjection/ServiceContainer.php +++ b/src/JonnyW/PhantomJs/DependencyInjection/ServiceContainer.php @@ -22,7 +22,7 @@ class ServiceContainer extends ContainerBuilder /** * Service container instance * - * @var \JonnyW\PhantomJs\DependencyInjection\ServiceContainer + * @var static * @access private */ private static $instance; @@ -31,32 +31,21 @@ class ServiceContainer extends ContainerBuilder * Get singleton instance * * @access public - * @return \JonnyW\PhantomJs\Client + * @return static */ public static function getInstance() { - if (!self::$instance instanceof ServiceContainer) { + if (null === self::$instance) { + self::$instance = new static(); - self::$instance = new ServiceContainer(); - self::$instance->load(); + $loader = new YamlFileLoader(self::$instance, new FileLocator(__DIR__.'/../Resources/config')); + $loader->load('config.yml'); + $loader->load('services.yml'); + + self::$instance->setParameter('phantomjs.cache_dir', sys_get_temp_dir()); + self::$instance->setParameter('phantomjs.resource_dir', __DIR__.'/../Resources'); } return self::$instance; } - - /** - * Load service container. - * - * @access public - * @return void - */ - public function load() - { - $loader = new YamlFileLoader($this, new FileLocator(__DIR__.'/../Resources/config')); - $loader->load('config.yml'); - $loader->load('services.yml'); - - $this->setParameter('phantomjs.cache_dir', sys_get_temp_dir()); - $this->setParameter('phantomjs.resource_dir', __DIR__.'/../Resources'); - } } From f35764503f6828908fd1108c960080edf915eabe Mon Sep 17 00:00:00 2001 From: Jonny Date: Tue, 3 Apr 2018 18:45:23 +0100 Subject: [PATCH 54/54] Updaitng tests --- .travis.yml | 1 - composer.json | 2 +- .../Tests/Integration/ClientTest.php | 447 +++++++----------- 3 files changed, 164 insertions(+), 286 deletions(-) diff --git a/.travis.yml b/.travis.yml index 711588b..b54688b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,7 +5,6 @@ os: - windows php: - - 5.3 - 5.4 - 5.5 - 5.6 diff --git a/composer.json b/composer.json index 8023365..b5cf6f5 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,7 @@ ], "minimum-stability": "stable", "require": { - "php": ">=5.3.0", + "php": ">=5.4.0", "symfony/config": "~2.3|~3.0", "symfony/dependency-injection": "~2.3|~3.0", "symfony/filesystem": "~2.3|~3.0", diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index 2b9af50..7c28469 100644 --- a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php +++ b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php @@ -6,6 +6,7 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ + namespace JonnyW\PhantomJs\Tests\Integration; use JonnyW\PhantomJs\Test\TestCase; @@ -13,38 +14,33 @@ use JonnyW\PhantomJs\DependencyInjection\ServiceContainer; /** - * PHP PhantomJs + * PHP PhantomJs. * * @author Jon Wenmoth */ class ClientTest extends TestCase { /** - * Test filename + * Test filename. * * @var string - * @access protected */ protected $filename; /** - * Test directory + * Test directory. * * @var string - * @access protected */ protected $directory; -/** +++++++++++++++++++++++++++++++++++ **/ -/** ++++++++++++++ TESTS ++++++++++++++ **/ -/** +++++++++++++++++++++++++++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ + /** ++++++++++++++ TESTS ++++++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ /** * Test additional procedures can be loaded * through chain loader. - * - * @access public - * @return void */ public function testAdditionalProceduresCanBeLoadedThroughChainLoader() { @@ -58,13 +54,13 @@ public function testAdditionalProceduresCanBeLoadedThroughChainLoader() $this->writeProcedure($procedure); $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory'); - $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); + $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); $client = $this->getClient(); $client->setProcedure('test'); $client->getProcedureLoader()->addLoader($procedureLoader); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $client->send($request, $response); @@ -75,10 +71,7 @@ public function testAdditionalProceduresCanBeLoadedThroughChainLoader() /** * Test additional procedures can be loaded * through chain loader if procedures - * contain comments - * - * @access public - * @return void + * contain comments. */ public function testAdditionalProceduresCanBeLoadedThroughChainLoaderIfProceduresContainComments() { @@ -96,13 +89,13 @@ public function testAdditionalProceduresCanBeLoadedThroughChainLoaderIfProcedure $this->writeProcedure($procedure); $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory'); - $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); + $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); $client = $this->getClient(); $client->setProcedure('test'); $client->getProcedureLoader()->addLoader($procedureLoader); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $client->send($request, $response); @@ -113,9 +106,6 @@ public function testAdditionalProceduresCanBeLoadedThroughChainLoaderIfProcedure /** * Test syntax exception is thrown if request * procedure contains syntax error. - * - * @access public - * @return void */ public function testSyntaxExceptionIsThrownIfRequestProcedureContainsSyntaxError() { @@ -130,13 +120,13 @@ public function testSyntaxExceptionIsThrownIfRequestProcedureContainsSyntaxError $this->writeProcedure($procedure); $procedureLoaderFactory = $this->getContainer()->get('procedure_loader_factory'); - $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); + $procedureLoader = $procedureLoaderFactory->createProcedureLoader($this->directory); $client = $this->getClient(); $client->setProcedure('test'); $client->getProcedureLoader()->addLoader($procedureLoader); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $client->send($request, $response); @@ -145,19 +135,16 @@ public function testSyntaxExceptionIsThrownIfRequestProcedureContainsSyntaxError /** * Test response contains 200 status code if page * is successfully loaded. - * - * @access public - * @return void */ public function testResponseContains200StatusCodeIfPageIsSuccessfullyLoaded() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $client->send($request, $response); @@ -167,23 +154,20 @@ public function testResponseContains200StatusCodeIfPageIsSuccessfullyLoaded() /** * Test response contains 200 status code if * request URL contains reserved characters. - * - * @access public - * @return void */ public function testResponseContains200StatusCodeIfRequestUrlContainsReservedCharacters() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); - $request->setRequestData(array( + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); + $request->setRequestData([ 'test1' => 'http://test.com', - 'test2' => 'A string with an \' ) / # some other invalid [ characters.' - )); + 'test2' => 'A string with an \' ) / # some other invalid [ characters.', + ]); $client->send($request, $response); @@ -193,19 +177,16 @@ public function testResponseContains200StatusCodeIfRequestUrlContainsReservedCha /** * Test response contains valid body if page is * successfully loaded. - * - * @access public - * @return void */ public function testResponseContainsValidBodyIfPageIsSuccessfullyLoaded() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $client->send($request, $response); @@ -213,20 +194,17 @@ public function testResponseContainsValidBodyIfPageIsSuccessfullyLoaded() } /** - * Test can set user agent in settings - * - * @access public - * @return void + * Test can set user agent in settings. */ public function testCanSetUserAgentInSettings() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->addSetting('userAgent', 'PhantomJS TEST'); $client->send($request, $response); @@ -235,20 +213,17 @@ public function testCanSetUserAgentInSettings() } /** - * Test can add cookies to request - * - * @access public - * @return void + * Test can add cookies to request. */ public function testCanAddCookiesToRequest() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi'); $client->send($request, $response); @@ -258,26 +233,23 @@ public function testCanAddCookiesToRequest() /** * Test can load cookies from - * persistent cookie file - * - * @access public - * @return void + * persistent cookie file. */ public function testCanLoadCookiesFromPersistentCookieFile() { $this->filename = 'cookies.txt'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $client->getEngine()->addOption('--cookies-file=' . $file); + $client->getEngine()->addOption('--cookies-file='.$file); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $expireAt = strtotime('16-Nov-2020 00:00:00'); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $client->send($request, $response); @@ -287,33 +259,30 @@ public function testCanLoadCookiesFromPersistentCookieFile() /** * Test can delete cookie from - * persistent cookie file - * - * @access public - * @return void + * persistent cookie file. */ public function testCanDeleteCookieFromPersistentCookieFile() { $this->filename = 'cookies.txt'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $client->getEngine()->addOption('--cookies-file=' . $file); + $client->getEngine()->addOption('--cookies-file='.$file); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $expireAt = strtotime('16-Nov-2020 00:00:00'); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $client->send($request, $response); $request = $client->getMessageFactory()->createRequest(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->deleteCookie('test_cookie'); $client->send($request, $response); @@ -323,26 +292,23 @@ public function testCanDeleteCookieFromPersistentCookieFile() /** * Test can delete all cookies from - * persistent cookie file - * - * @access public - * @return void + * persistent cookie file. */ public function testCanDeleteAllCookiesFromPersistentCookieFile() { $this->filename = 'cookies.txt'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $client->getEngine()->addOption('--cookies-file=' . $file); + $client->getEngine()->addOption('--cookies-file='.$file); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $expireAt = strtotime('16-Nov-2020 00:00:00'); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->addCookie('test_cookie_1', 'TESTING_COOKIES_1', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $request->addCookie('test_cookie_2', 'TESTING_COOKIES_2', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); @@ -350,7 +316,7 @@ public function testCanDeleteAllCookiesFromPersistentCookieFile() $request = $client->getMessageFactory()->createRequest(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->deleteCookie('*'); $client->send($request, $response); @@ -359,31 +325,27 @@ public function testCanDeleteAllCookiesFromPersistentCookieFile() $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)); } - /** * Test can load cookies from - * persistent cookie file - * - * @access public - * @return void + * persistent cookie file. */ public function testCookiesPresentInResponse() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $expireAt = strtotime('16-Nov-2020 00:00:00'); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); $client->send($request, $response); $cookies = $response->getCookies(); - $this->assertEquals(array( + $this->assertEquals([ 'domain' => '.jonnyw.kiwi', 'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT', 'expiry' => '1605484800', @@ -392,25 +354,22 @@ public function testCookiesPresentInResponse() 'path' => '/', 'secure' => false, 'value' => 'TESTING_COOKIES', - ), $cookies[0]); + ], $cookies[0]); } /** * Test response contains console error if a * javascript error exists on the page. - * - * @access public - * @return void */ public function testResponseContainsConsoleErrorIfAJavascriptErrorExistsOnThePage() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error'); $client->send($request, $response); @@ -423,19 +382,16 @@ public function testResponseContainsConsoleErrorIfAJavascriptErrorExistsOnThePag /** * Test response contains console trace if a * javascript error exists on the page. - * - * @access public - * @return void */ public function testResponseContainsConsoleTraceIfAJavascriptErrorExistsOnThePage() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error'); $client->send($request, $response); @@ -446,19 +402,16 @@ public function testResponseContainsConsoleTraceIfAJavascriptErrorExistsOnThePag /** * Test response contains headers. - * - * @access public - * @return void */ public function testResponseContainsHeaders() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error'); $client->send($request, $response); @@ -468,15 +421,12 @@ public function testResponseContainsHeaders() /** * Test redirect URL is set in response * if request is redirected. - * - * @access public - * @return void */ public function testRedirectUrlIsSetInResponseIfRequestIsRedirected() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); @@ -489,23 +439,20 @@ public function testRedirectUrlIsSetInResponseIfRequestIsRedirected() /** * Test POST request sends request data. - * - * @access public - * @return void */ public function testPostRequestSendsRequestData() { $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('POST'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-post.php'); - $request->setRequestData(array( + $request->setUrl('http://www.jonnyw.kiwi/tests/test-post'); + $request->setRequestData([ 'test1' => 'http://test.com', - 'test2' => 'A string with an \' ) / # some other invalid [ characters.' - )); + 'test2' => 'A string with an \' ) / # some other invalid [ characters.', + ]); $client->send($request, $response); @@ -516,51 +463,45 @@ public function testPostRequestSendsRequestData() /** * Test capture request saves file to * to local disk. - * - * @access public - * @return void */ public function testCaptureRequestSavesFileToLocalDisk() { $this->filename = 'test.jpg'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $client->send($request, $response); - $this->assertTrue(file_exists($file)); + $this->assertFileExists($file); } /** * Test capture request saves file to * disk with correct capture dimensions. - * - * @access public - * @return void */ public function testCaptureRequestSavesFileToDiskWithCorrectCaptureDimensions() { $this->filename = 'test.jpg'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); - $width = 200; + $width = 200; $height = 400; $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setCaptureDimensions($width, $height); @@ -575,51 +516,45 @@ public function testCaptureRequestSavesFileToDiskWithCorrectCaptureDimensions() /** * Test PDF request saves pdf to * to local disk. - * - * @access public - * @return void */ public function testPdfRequestSavesPdfToLocalDisk() { $this->filename = 'test.pdf'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createPdfRequest(); + $request = $client->getMessageFactory()->createPdfRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $client->send($request, $response); - $this->assertTrue(file_exists($file)); + $this->assertFileExists($file); } /** * Test PDF request saves file to * disk with correct paper size. - * - * @access public - * @return void */ public function testPdfRequestSavesFileToDiskWithCorrectPaperSize() { $this->filename = 'test.pdf'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); - $width = 20; + $width = 20; $height = 30; $client = $this->getClient(); - $request = $client->getMessageFactory()->createPdfRequest(); + $request = $client->getMessageFactory()->createPdfRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setPaperSize(sprintf('%scm', $width), sprintf('%scm', $height)); $request->setMargin('0cm'); @@ -628,8 +563,8 @@ public function testPdfRequestSavesFileToDiskWithCorrectPaperSize() $pdf = \ZendPdf\PdfDocument::load($file); - $pdfWidth = round(($pdf->pages[0]->getWidth() * 0.0352777778)); - $pdfHeight = round(($pdf->pages[0]->getHeight() * 0.0352777778)); + $pdfWidth = round(($pdf->pages[0]->getWidth() * 0.0352777778)); + $pdfHeight = round(($pdf->pages[0]->getHeight() * 0.0352777778)); $this->assertEquals($width, $pdfWidth); $this->assertEquals($height, $pdfHeight); @@ -638,22 +573,19 @@ public function testPdfRequestSavesFileToDiskWithCorrectPaperSize() /** * Test PDF request saves file to * disk with correct format size. - * - * @access public - * @return void */ public function testPdfRequestSavesFileToDiskWithCorrectFormatSize() { $this->filename = 'test.pdf'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createPdfRequest(); + $request = $client->getMessageFactory()->createPdfRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setMargin('0cm'); @@ -662,8 +594,8 @@ public function testPdfRequestSavesFileToDiskWithCorrectFormatSize() $pdf = \ZendPdf\PdfDocument::load($file); - $pdfWidth = round(($pdf->pages[0]->getWidth() * 0.0352777778)); - $pdfHeight = round(($pdf->pages[0]->getHeight() * 0.0352777778)); + $pdfWidth = round(($pdf->pages[0]->getWidth() * 0.0352777778)); + $pdfHeight = round(($pdf->pages[0]->getHeight() * 0.0352777778)); $this->assertEquals(21, $pdfWidth); $this->assertEquals(30, $pdfHeight); @@ -672,22 +604,19 @@ public function testPdfRequestSavesFileToDiskWithCorrectFormatSize() /** * Test PDF request saves file to * disk with correct orientation. - * - * @access public - * @return void */ public function testPdfRequestSavesFileToDiskWithCorrectOrientation() { $this->filename = 'test.pdf'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createPdfRequest(); + $request = $client->getMessageFactory()->createPdfRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -697,8 +626,8 @@ public function testPdfRequestSavesFileToDiskWithCorrectOrientation() $pdf = \ZendPdf\PdfDocument::load($file); - $pdfWidth = round(($pdf->pages[0]->getWidth() * 0.0352777778)); - $pdfHeight = round(($pdf->pages[0]->getHeight() * 0.0352777778)); + $pdfWidth = round(($pdf->pages[0]->getWidth() * 0.0352777778)); + $pdfHeight = round(($pdf->pages[0]->getHeight() * 0.0352777778)); $this->assertEquals(30, $pdfWidth); $this->assertEquals(21, $pdfHeight); @@ -706,23 +635,20 @@ public function testPdfRequestSavesFileToDiskWithCorrectOrientation() /** * Test can set repeating header - * for PDF request - * - * @access public - * @return void + * for PDF request. */ public function testCanSetRepeatingHeaderForPDFRequest() { $this->filename = 'test.pdf'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createPdfRequest(); + $request = $client->getMessageFactory()->createPdfRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -733,7 +659,7 @@ public function testCanSetRepeatingHeaderForPDFRequest() $client->send($request, $response); $parser = new \Smalot\PdfParser\Parser(); - $pdf = $parser->parseFile($file); + $pdf = $parser->parseFile($file); $text = str_replace(' ', '', $pdf->getText()); @@ -742,23 +668,20 @@ public function testCanSetRepeatingHeaderForPDFRequest() /** * Test can set repeating footer - * for PDF request - * - * @access public - * @return void + * for PDF request. */ public function testCanSetRepeatingFooterForPDFRequest() { $this->filename = 'test.pdf'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createPdfRequest(); + $request = $client->getMessageFactory()->createPdfRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -769,7 +692,7 @@ public function testCanSetRepeatingFooterForPDFRequest() $client->send($request, $response); $parser = new \Smalot\PdfParser\Parser(); - $pdf = $parser->parseFile($file); + $pdf = $parser->parseFile($file); $text = str_replace(' ', '', $pdf->getText()); @@ -780,22 +703,19 @@ public function testCanSetRepeatingFooterForPDFRequest() * Test set viewport size sets * size of viewport in default * request. - * - * @access public - * @return void */ public function testSetViewportSizeSetsSizeOfViewportInDefaultRequest() { - $width = 100; + $width = 100; $height = 200; $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setViewportsize($width, $height); $client->send($request, $response); @@ -804,29 +724,26 @@ public function testSetViewportSizeSetsSizeOfViewportInDefaultRequest() $startIndex = $this->getLogEntryIndex($logs, 'Set viewport size ~ width: 100 height: 200'); - $this->assertTrue(($startIndex !== false)); + $this->assertTrue((false !== $startIndex)); } /** * Test set viewport size sets * size of viewport in capture * request. - * - * @access public - * @return void */ public function testSetViewportSizeSetsSizeOfViewportInCaptureRequest() { - $width = 100; + $width = 100; $height = 200; $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setViewportsize($width, $height); $client->send($request, $response); @@ -835,15 +752,12 @@ public function testSetViewportSizeSetsSizeOfViewportInCaptureRequest() $startIndex = $this->getLogEntryIndex($logs, 'Set viewport size ~ width: 100 height: 200'); - $this->assertTrue(($startIndex !== false)); + $this->assertTrue((false !== $startIndex)); } /** * Test delay logs start time * in client for default request. - * - * @access public - * @return void */ public function testDelayLogsStartTimeInClientForDefaultRequest() { @@ -851,11 +765,11 @@ public function testDelayLogsStartTimeInClientForDefaultRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setDelay($delay); $client->send($request, $response); @@ -864,15 +778,12 @@ public function testDelayLogsStartTimeInClientForDefaultRequest() $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for'); - $this->assertTrue(($startIndex !== false)); + $this->assertTrue((false !== $startIndex)); } /** * Test delay logs end time * in client for default request. - * - * @access public - * @return void */ public function testDelayLogsEndTimeInClientForDefaultRequest() { @@ -880,11 +791,11 @@ public function testDelayLogsEndTimeInClientForDefaultRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setDelay($delay); $client->send($request, $response); @@ -893,15 +804,12 @@ public function testDelayLogsEndTimeInClientForDefaultRequest() $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after'); - $this->assertTrue(($endIndex !== false)); + $this->assertTrue((false !== $endIndex)); } /** * Test delay delays page render for * specified time for default request. - * - * @access public - * @return void */ public function testDelayDelaysPageRenderForSpecifiedTimeForDefaultRequest() { @@ -909,32 +817,29 @@ public function testDelayDelaysPageRenderForSpecifiedTimeForDefaultRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setDelay($delay); $client->send($request, $response); - $logs = explode("\\n", $client->getLog()); + $logs = explode('\\n', $client->getLog()); $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for'); - $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after'); + $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after'); - $startTime = strtotime(substr($logs[$startIndex], 0 , 19)); - $endTime = strtotime(substr($logs[$endIndex], 0 , 19)); + $startTime = strtotime(substr($logs[$startIndex], 0, 19)); + $endTime = strtotime(substr($logs[$endIndex], 0, 19)); - $this->assertSame(($startTime+$delay), $endTime); + $this->assertSame(($startTime + $delay), $endTime); } /** * Test delay logs start time * in client for capture request. - * - * @access public - * @return void */ public function testDelayLogsStartTimeInClientForCaptureRequest() { @@ -942,28 +847,25 @@ public function testDelayLogsStartTimeInClientForCaptureRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setDelay($delay); $client->send($request, $response); - $logs = explode("\\n", $client->getLog()); + $logs = explode('\\n', $client->getLog()); $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for'); - $this->assertTrue(($startIndex !== false)); + $this->assertTrue((false !== $startIndex)); } /** * Test delay logs end time * in client for capture request. - * - * @access public - * @return void */ public function testDelayLogsEndTimeInClientForCaptureRequest() { @@ -971,28 +873,25 @@ public function testDelayLogsEndTimeInClientForCaptureRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setDelay($delay); $client->send($request, $response); - $logs = explode("\\n", $client->getLog()); + $logs = explode('\\n', $client->getLog()); $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after'); - $this->assertTrue(($endIndex !== false)); + $this->assertTrue((false !== $endIndex)); } /** * Test delay delays page render for * specified time for capture request. - * - * @access public - * @return void */ public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest() { @@ -1000,43 +899,40 @@ public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setDelay($delay); $client->send($request, $response); - $logs = explode("\\n", $client->getLog()); + $logs = explode('\\n', $client->getLog()); $startIndex = $this->getLogEntryIndex($logs, 'Delaying page render for'); - $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after'); + $endIndex = $this->getLogEntryIndex($logs, 'Rendering page after'); - $startTime = strtotime(substr($logs[$startIndex], 0 , 19)); - $endTime = strtotime(substr($logs[$endIndex], 0 , 19)); + $startTime = strtotime(substr($logs[$startIndex], 0, 19)); + $endTime = strtotime(substr($logs[$endIndex], 0, 19)); - $this->assertSame(($startTime+$delay), $endTime); + $this->assertSame(($startTime + $delay), $endTime); } /** * Test lazy request returns content after - * all resources are loaded - * - * @access public - * @return void + * all resources are loaded. */ public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded() { $client = $this->getClient(); $client->isLazy(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy'); $request->setTimeout(5000); $client->send($request, $response); @@ -1047,21 +943,18 @@ public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded() /** * Test content is returned for lazy request * if timeout is reached before resource is - * loaded - * - * @access public - * @return void + * loaded. */ public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResourceIsLoaded() { $client = $this->getClient(); $client->isLazy(); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy'); $request->setTimeout(1000); $client->send($request, $response); @@ -1072,20 +965,17 @@ public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResou /** * Test debug logs debug info to * client log. - * - * @access public - * @return void */ public function testDebugLogsDebugInfoToClientLog() { $client = $this->getClient(); $client->getEngine()->debug(true); - $request = $client->getMessageFactory()->createRequest(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $client->send($request, $response); @@ -1094,24 +984,21 @@ public function testDebugLogsDebugInfoToClientLog() /** * Test test can set page - * background color - * - * @access public - * @return void + * background color. */ public function testCanSetPageBackgroundColor() { $this->filename = 'test.jpg'; - $file = ($this->directory . '/' . $this->filename); + $file = ($this->directory.'/'.$this->filename); $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $response = $client->getMessageFactory()->createResponse(); $request->setMethod('GET'); - $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture.php'); - $request->setBodyStyles(array('backgroundColor' => 'red')); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); + $request->setBodyStyles(['backgroundColor' => 'red']); $request->setOutputFile($file); $client->send($request, $response); @@ -1119,9 +1006,9 @@ public function testCanSetPageBackgroundColor() $this->assertContains('body style="background-color: red;"', $response->getContent()); } -/** +++++++++++++++++++++++++++++++++++ **/ -/** ++++++++++ TEST ENTITIES ++++++++++ **/ -/** +++++++++++++++++++++++++++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ + /** ++++++++++ TEST ENTITIES ++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ /** * Get client instance. @@ -1142,19 +1029,16 @@ protected function getClient() return $client; } -/** +++++++++++++++++++++++++++++++++++ **/ -/** ++++++++++++ UTILITIES ++++++++++++ **/ -/** +++++++++++++++++++++++++++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ + /** ++++++++++++ UTILITIES ++++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ /** * Set up test environment. - * - * @access public - * @return void */ public function setUp() { - $this->filename = 'test.proc'; + $this->filename = 'test.proc'; $this->directory = sys_get_temp_dir(); if (!is_writable($this->directory)) { @@ -1164,9 +1048,6 @@ public function setUp() /** * Tear down test environment. - * - * @access public - * @return void */ public function tearDown() { @@ -1180,7 +1061,6 @@ public function tearDown() /** * Get test filename. * - * @access public * @return string */ public function getFilename() @@ -1191,8 +1071,8 @@ public function getFilename() /** * Write procedure body to file. * - * @access public - * @param string $data + * @param string $data + * * @return string */ public function writeProcedure($procedure) @@ -1207,18 +1087,17 @@ public function writeProcedure($procedure) /** * Get log entry index. * - * @access public - * @param array $logs - * @param string $search + * @param array $logs + * @param string $search + * * @return int|false */ public function getLogEntryIndex(array $logs, $search) { foreach ($logs as $index => $log) { - $pos = stripos($log, $search); - if ($pos !== false) { + if (false !== $pos) { return $index; } }