diff --git a/.travis.yml b/.travis.yml index 7e7a327..b54688b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,18 +1,21 @@ language: php +os: + - linux + - windows + php: - - 5.3 - 5.4 - 5.5 + - 5.6 before_script: - composer self-update - composer install - - pyrus install pear/PHP_CodeSniffer - phpenv rehash script: - - phpunit --coverage-clover=coverage.clover + - bin/phpunit --coverage-clover=coverage.clover after_script: - wget https://scrutinizer-ci.com/ocular.phar diff --git a/README.md b/README.md index 1b4b374..2050d1a 100644 --- a/README.md +++ b/README.md @@ -7,25 +7,22 @@ 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 --------------------- -* 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 debugged information -* Save screen captures to local disk -* 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. +* 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 diff --git a/composer.json b/composer.json index 3df86e4..b5cf6f5 100644 --- a/composer.json +++ b/composer.json @@ -13,17 +13,18 @@ ], "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", + "php": ">=5.4.0", + "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": "1.9.8" + "jakoch/phantomjs-installer": "2.1.1-p08" }, "require-dev": { "phpunit/phpunit": "~4.0", - "zendframework/zendpdf": "~2.0" + "zendframework/zendpdf": "~2.0", + "smalot/pdfparser": "~0.9" }, "autoload": { "psr-0": { @@ -34,9 +35,6 @@ "config": { "bin-dir": "bin" }, - "bin": [ - "bin/phantomloader" - ], "scripts": { "post-install-cmd": [ "PhantomInstaller\\Installer::installPhantomJS" 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 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/Client.php b/src/JonnyW/PhantomJs/Client.php index 0fb0e3e..0f542ec 100644 --- a/src/JonnyW/PhantomJs/Client.php +++ b/src/JonnyW/PhantomJs/Client.php @@ -197,4 +197,26 @@ public function getProcedure() { return $this->procedure; } + + /** + * Get procedure compiler. + * + * @access public + * @return \JonnyW\PhantomJs\Procedure\ProcedureCompilerInterface + */ + 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/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'); - } } 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 a778374..71c3eb0 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; @@ -29,6 +28,22 @@ abstract class AbstractRequest */ protected $headers; + /** + * Settings + * + * @var array + * @access protected + */ + protected $settings; + + /** + * Cookies + * + * @var array + * @access protected + */ + protected $cookies; + /** * Request data * @@ -85,6 +100,14 @@ abstract class AbstractRequest */ protected $viewportHeight; + /** + * Body styles. + * + * @var array + * @access protected + */ + protected $bodyStyles; + /** * Internal constructor * @@ -95,11 +118,18 @@ abstract class AbstractRequest */ public function __construct($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000) { - $this->headers = array(); - $this->data = array(); - $this->delay = 0; - $this->viewportWidth = 0; - $this->viewportHeight = 0; + $this->headers = array(); + $this->data = array(); + $this->bodyStyles = array(); + $this->settings = array(); + $this->delay = 0; + $this->viewportWidth = 0; + $this->viewportHeight = 0; + + $this->cookies = array( + 'add' => array(), + 'delete' => array() + ); $this->setMethod($method); $this->setTimeout($timeout); @@ -151,7 +181,7 @@ public function getMethod() */ public function setTimeout($timeout) { - $this->timeout = $timeout; + $this->settings['resourceTimeout'] = $timeout; return $this; } @@ -164,7 +194,11 @@ public function setTimeout($timeout) */ public function getTimeout() { - return $this->timeout; + if (isset($this->settings['resourceTimeout'])) { + return $this->settings['resourceTimeout']; + } + + return null; } /** @@ -204,6 +238,8 @@ public function setViewportSize($width, $height) { $this->viewportWidth = (int) $width; $this->viewportHeight = (int) $height; + + return $this; } /** @@ -232,16 +268,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; @@ -363,8 +394,8 @@ public function addHeaders(array $headers) * Get request headers * * @access public - * @param string $format - * @return array + * @param string $format + * @return array|string */ public function getHeaders($format = 'default') { @@ -375,6 +406,119 @@ 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; + } + + /** + * 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 + * + * @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|string + */ + 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/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/Http/PdfRequest.php b/src/JonnyW/PhantomJs/Http/PdfRequest.php index e2e5d5c..f8a2ea4 100644 --- a/src/JonnyW/PhantomJs/Http/PdfRequest.php +++ b/src/JonnyW/PhantomJs/Http/PdfRequest.php @@ -52,11 +52,27 @@ class PdfRequest extends CaptureRequest /** * Margin * - * @var string + * @var string|array * @access protected */ 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(); } @@ -203,7 +221,7 @@ public function getOrientation() * Set margin. * * @access public - * @param string $margin + * @param string|array $margin * @return void */ public function setMargin($margin) @@ -215,10 +233,64 @@ public function setMargin($margin) * Get margin. * * @access public - * @return string + * @return string|array */ 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 0265cd9..c1f0918 100644 --- a/src/JonnyW/PhantomJs/Http/RequestInterface.php +++ b/src/JonnyW/PhantomJs/Http/RequestInterface.php @@ -180,8 +180,39 @@ public function addHeaders(array $headers); * Get request headers * * @access public - * @param string $format - * @return array + * @return array|string + */ + 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 + * + * @access public + * @param array $styles + */ + public function setBodyStyles(array $styles); + + /** + * Get body styles + * + * @access public + * @return array|string */ - public function getHeaders($format = 'default'); + public function getBodyStyles(); } diff --git a/src/JonnyW/PhantomJs/Http/Response.php b/src/JonnyW/PhantomJs/Http/Response.php index 6a89424..ea36cef 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 @@ -82,6 +82,14 @@ class Response */ public $console; + /** + * Session cookies + * + * @var array + * @access public + */ + public $cookies; + /** * Import response data * @@ -209,7 +217,7 @@ public function getUrl() */ public function getRedirectUrl() { - return $this->redirectUrl; + return $this->redirectURL; } /** @@ -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/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/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 c4da236..fcfddf4 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,41 @@ 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.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: - 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.array_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 +163,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 diff --git a/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc b/src/JonnyW/PhantomJs/Resources/procedures/http_default.proc index 2006fa7..19a11f3 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 */ @@ -50,6 +54,13 @@ page.onResourceTimeout = function (error) { [[ engine.load('page_on_resource_timeout') ]] }; +/** + * On resource requested + */ +page.onResourceRequested = function (resource, networkRequest) { + [[ engine.load('page_on_resource_requested') ]] +}; + /** * On resource received */ @@ -75,6 +86,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') ]] }); @@ -86,4 +98,4 @@ procedure.execute = function (status) { }; {% endautoescape %} -[% endautoescape %] \ No newline at end of file +[% endautoescape %] 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..115ee34 --- /dev/null +++ b/src/JonnyW/PhantomJs/Resources/procedures/http_lazy.proc @@ -0,0 +1,126 @@ + +[% 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') ]] + +/** + * Page cookies + */ +[[ engine.load('page_cookies') ]] + +/** + * 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); +}; + +/** + * 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--; + + 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_body_styles.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial new file mode 100644 index 0000000..58e60ff --- /dev/null +++ b/src/JonnyW/PhantomJs/Resources/procedures/page_body_styles.partial @@ -0,0 +1,9 @@ + +page.evaluate(function() { + + var styles = {{ input.getBodyStyles()|json_encode(constant('JSON_FORCE_OBJECT')) }}; + + for(var property in styles) { + document.body.style[property] = styles[property]; + } +}); \ No newline at end of file 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/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_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/Resources/procedures/page_paper_size.partial b/src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial index 30e72da..d2ce5bc 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()|json_encode(constant('JSON_FORCE_OBJECT')) }}, + 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/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/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 ac830f5..fab1e67 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; @@ -17,9 +20,9 @@ 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)); phantom.exit(); - 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/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/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/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); } } diff --git a/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php b/src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php index cfb8d35..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,48 @@ 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(); + $response = $client->getMessageFactory()->createResponse(); + + $client->send($request, $response); + + $this->assertSame($content, $response->getContent()); + } + + /** + * Test additional procedures can be loaded + * through chain loader if procedures + * contain comments. + */ + 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(); + $request = $client->getMessageFactory()->createRequest(); $response = $client->getMessageFactory()->createResponse(); $client->send($request, $response); @@ -75,9 +106,6 @@ public function testAdditionalProceduresCanBeLoadedThroughChainLoader() /** * Test syntax exception is thrown if request * procedure contains syntax error. - * - * @access public - * @return void */ public function testSyntaxExceptionIsThrownIfRequestProcedureContainsSyntaxError() { @@ -92,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); @@ -107,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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $client->send($request, $response); @@ -129,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://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); @@ -155,41 +177,199 @@ 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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $client->send($request, $response); $this->assertContains('PHANTOMJS_DEFAULT_TEST', $response->getContent()); } + /** + * Test can set user agent in settings. + */ + public function testCanSetUserAgentInSettings() + { + $client = $this->getClient(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); + $request->addSetting('userAgent', 'PhantomJS TEST'); + + $client->send($request, $response); + + $this->assertContains('userAgent=PhantomJS TEST', $response->getContent()); + } + + /** + * Test can add cookies to request. + */ + 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'); + $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. + */ + 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(); + + $expireAt = strtotime('16-Nov-2020 00:00:00'); + + $request->setMethod('GET'); + $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); + + $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. + */ + 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(); + + $expireAt = strtotime('16-Nov-2020 00:00:00'); + + $request->setMethod('GET'); + $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'); + $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. + */ + 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(); + + $expireAt = strtotime('16-Nov-2020 00:00:00'); + + $request->setMethod('GET'); + $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)); + + $client->send($request, $response); + + $request = $client->getMessageFactory()->createRequest(); + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); + $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 can load cookies from + * persistent cookie file. + */ + 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'); + $request->addCookie('test_cookie', 'TESTING_COOKIES', '/', '.jonnyw.kiwi', true, false, ($expireAt * 1000)); + + $client->send($request, $response); + + $cookies = $response->getCookies(); + $this->assertEquals([ + 'domain' => '.jonnyw.kiwi', + 'expires' => 'Mon, 16 Nov 2020 00:00:00 GMT', + 'expiry' => '1605484800', + 'httponly' => true, + 'name' => 'test_cookie', + 'path' => '/', + 'secure' => false, + 'value' => 'TESTING_COOKIES', + ], $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://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error'); $client->send($request, $response); @@ -202,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://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error'); $client->send($request, $response); @@ -225,44 +402,57 @@ 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://jonnyw.kiwi/tests/test-console-error.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-console-error'); $client->send($request, $response); $this->assertNotEmpty($response->getHeaders()); } + /** + * Test redirect URL is set in response + * if request is redirected. + */ + 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. - * - * @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://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); @@ -273,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://jonnyw.kiwi/tests/test-console-error.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://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setCaptureDimensions($width, $height); @@ -332,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://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 + * 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://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'); @@ -385,32 +563,29 @@ 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); } /** - * Test capture request saves file to + * 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://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setMargin('0cm'); @@ -419,32 +594,29 @@ 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); } /** - * Test capture request saves file to + * 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://jonnyw.kiwi/tests/test-capture.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-capture'); $request->setOutputFile($file); $request->setFormat('A4'); $request->setOrientation('landscape'); @@ -454,33 +626,96 @@ 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); } + /** + * Test can set repeating header + * for PDF request. + */ + 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://www.jonnyw.kiwi/tests/test-capture'); + $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); + + $parser = new \Smalot\PdfParser\Parser(); + $pdf = $parser->parseFile($file); + + $text = str_replace(' ', '', $pdf->getText()); + + $this->assertContains('Header', $text); + } + + /** + * Test can set repeating footer + * for PDF request. + */ + 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://www.jonnyw.kiwi/tests/test-capture'); + $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); + + $parser = new \Smalot\PdfParser\Parser(); + $pdf = $parser->parseFile($file); + + $text = str_replace(' ', '', $pdf->getText()); + + $this->assertContains('Footer', $text); + } + /** * 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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setViewportsize($width, $height); $client->send($request, $response); @@ -489,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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setViewportsize($width, $height); $client->send($request, $response); @@ -520,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() { @@ -536,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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setDelay($delay); $client->send($request, $response); @@ -549,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() { @@ -565,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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $request->setDelay($delay); $client->send($request, $response); @@ -578,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() { @@ -594,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://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() { @@ -627,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://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() { @@ -656,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://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() { @@ -685,52 +899,116 @@ public function testDelayDelaysPageRenderForSpecifiedTimeForCaptureRequest() $client = $this->getClient(); - $request = $client->getMessageFactory()->createCaptureRequest(); + $request = $client->getMessageFactory()->createCaptureRequest(); $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'); $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)); + + $this->assertSame(($startTime + $delay), $endTime); + } + + /** + * Test lazy request returns content after + * all resources are loaded. + */ + public function testLazyRequestReturnsResourcesAfterAllResourcesAreLoaded() + { + $client = $this->getClient(); + $client->isLazy(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy'); + $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. + */ + public function testContentIsReturnedForLazyRequestIfTimeoutIsReachedBeforeResourceIsLoaded() + { + $client = $this->getClient(); + $client->isLazy(); + + $request = $client->getMessageFactory()->createRequest(); + $response = $client->getMessageFactory()->createResponse(); + + $request->setMethod('GET'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-lazy'); + $request->setTimeout(1000); - $startTime = strtotime(substr($logs[$startIndex], 0 , 19)); - $endTime = strtotime(substr($logs[$endIndex], 0 , 19)); + $client->send($request, $response); - $this->assertSame(($startTime+$delay), $endTime); + $this->assertContains('

', $response->getContent()); } /** * 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://jonnyw.kiwi/tests/test-default.php'); + $request->setUrl('http://www.jonnyw.kiwi/tests/test-default'); $client->send($request, $response); $this->assertContains('[DEBUG]', $client->getLog()); } -/** +++++++++++++++++++++++++++++++++++ **/ -/** ++++++++++ TEST ENTITIES ++++++++++ **/ -/** +++++++++++++++++++++++++++++++++++ **/ + /** + * Test test can set page + * background color. + */ + 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://www.jonnyw.kiwi/tests/test-capture'); + $request->setBodyStyles(['backgroundColor' => 'red']); + $request->setOutputFile($file); + + $client->send($request, $response); + + $this->assertContains('body style="background-color: red;"', $response->getContent()); + } + + /** +++++++++++++++++++++++++++++++++++ **/ + /** ++++++++++ TEST ENTITIES ++++++++++ **/ + /** +++++++++++++++++++++++++++++++++++ **/ /** * Get client instance. @@ -751,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)) { @@ -773,9 +1048,6 @@ public function setUp() /** * Tear down test environment. - * - * @access public - * @return void */ public function tearDown() { @@ -789,7 +1061,6 @@ public function tearDown() /** * Get test filename. * - * @access public * @return string */ public function getFilename() @@ -800,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) @@ -816,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; } } 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 ad4bdce..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,22 +177,7 @@ public function testRectLeftCanBeSet() $captureRequest = $this->getCaptureRequest(); $captureRequest->setCaptureDimensions($width, $height, 0, $left); - $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'); + $this->assertEquals($left, $captureRequest->getRectLeft()); } /** @@ -216,7 +201,7 @@ public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet() $captureRequest->setUrl($url); $captureRequest->setRequestData($data); - $this->assertSame($url, $captureRequest->getUrl()); + $this->assertEquals($url, $captureRequest->getUrl()); } /** @@ -242,7 +227,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsGet() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $captureRequest->getUrl()); + $this->assertEquals($expectedUrl, $captureRequest->getUrl()); } /** @@ -268,7 +253,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsHead() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $captureRequest->getUrl()); + $this->assertEquals($expectedUrl, $captureRequest->getUrl()); } /** @@ -294,7 +279,7 @@ public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams( $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $captureRequest->getUrl()); + $this->assertEquals($expectedUrl, $captureRequest->getUrl()); } /** @@ -315,7 +300,7 @@ public function testRequestContainsNoBodyIfMethodIsGet() $captureRequest->setMethod('GET'); $captureRequest->setRequestData($data); - $this->assertSame('', $captureRequest->getBody()); + $this->assertEquals('', $captureRequest->getBody()); } /** @@ -336,7 +321,7 @@ public function testRequestContainsNoBodyIfMethodIsHead() $captureRequest->setMethod('HEAD'); $captureRequest->setRequestData($data); - $this->assertSame('', $captureRequest->getBody()); + $this->assertEquals('', $captureRequest->getBody()); } /** @@ -359,7 +344,7 @@ public function testRequestContainsABodyIfMethodIsNotHeadOrGet() $body = 'test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($body, $captureRequest->getBody()); + $this->assertEquals($body, $captureRequest->getBody()); } /** @@ -387,7 +372,7 @@ public function testRequestDataCanBeFalttened() 'test_param2[1]' => 'Testing3' ); - $this->assertSame($flatData, $captureRequest->getRequestData(true)); + $this->assertEquals($flatData, $captureRequest->getRequestData(true)); } /** @@ -409,7 +394,7 @@ public function testRawRequestDataCanBeAccessed() $captureRequest = $this->getCaptureRequest(); $captureRequest->setRequestData($data); - $this->assertSame($data, $captureRequest->getRequestData(false)); + $this->assertEquals($data, $captureRequest->getRequestData(false)); } /** @@ -435,7 +420,7 @@ public function testHeadersCanBeAdded() $expectedHeaders = array_merge($existingHeaders, $newHeaders); - $this->assertSame($expectedHeaders, $captureRequest->getHeaders()); + $this->assertEquals($expectedHeaders, $captureRequest->getHeaders()); } /** @@ -457,7 +442,7 @@ public function testHeadersCanBeAccessedInJsonFormat() $expectedHeaders = json_encode($headers); - $this->assertSame($expectedHeaders, $captureRequest->getHeaders('json')); + $this->assertEquals($expectedHeaders, $captureRequest->getHeaders('json')); } /** @@ -476,7 +461,7 @@ public function testRawHeadersCanBeAccessed() $captureRequest = $this->getCaptureRequest(); $captureRequest->setHeaders($headers); - $this->assertSame($headers, $captureRequest->getHeaders('default')); + $this->assertEquals($headers, $captureRequest->getHeaders('default')); } /** @@ -486,7 +471,7 @@ public function testRawHeadersCanBeAccessed() * @access public * @return void */ - public function tesNotWritableExceptonIsThrownIfOutputPathIsNotWritable() + public function testNotWritableExceptonIsThrownIfOutputPathIsNotWritable() { $this->setExpectedException('\JonnyW\PhantomJs\Exception\NotWritableException'); @@ -509,7 +494,7 @@ public function testCanSetOutputFile() $captureRequest = $this->getCaptureRequest(); $captureRequest->setOutputFile($outputFile); - $this->assertSame($outputFile, $captureRequest->getOutputFile()); + $this->assertEquals($outputFile, $captureRequest->getOutputFile()); } /** @@ -526,7 +511,7 @@ public function testCanSetViewportWidth() $caputreRequest = $this->getCaptureRequest(); $caputreRequest->setViewportSize($width, $height); - $this->assertSame($width, $caputreRequest->getViewportWidth()); + $this->assertEquals($width, $caputreRequest->getViewportWidth()); } /** @@ -543,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 f873bda..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()); } /** @@ -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. @@ -146,7 +131,7 @@ public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet() $pdfRequest->setUrl($url); $pdfRequest->setRequestData($data); - $this->assertSame($url, $pdfRequest->getUrl()); + $this->assertEquals($url, $pdfRequest->getUrl()); } /** @@ -172,7 +157,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsGet() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $pdfRequest->getUrl()); + $this->assertEquals($expectedUrl, $pdfRequest->getUrl()); } /** @@ -198,7 +183,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsHead() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $pdfRequest->getUrl()); + $this->assertEquals($expectedUrl, $pdfRequest->getUrl()); } /** @@ -224,7 +209,7 @@ public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams( $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $pdfRequest->getUrl()); + $this->assertEquals($expectedUrl, $pdfRequest->getUrl()); } /** @@ -245,7 +230,7 @@ public function testRequestContainsNoBodyIfMethodIsGet() $pdfRequest->setMethod('GET'); $pdfRequest->setRequestData($data); - $this->assertSame('', $pdfRequest->getBody()); + $this->assertEquals('', $pdfRequest->getBody()); } /** @@ -266,7 +251,7 @@ public function testRequestContainsNoBodyIfMethodIsHead() $pdfRequest->setMethod('HEAD'); $pdfRequest->setRequestData($data); - $this->assertSame('', $pdfRequest->getBody()); + $this->assertEquals('', $pdfRequest->getBody()); } /** @@ -289,7 +274,7 @@ public function testRequestContainsABodyIfMethodIsNotHeadOrGet() $body = 'test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($body, $pdfRequest->getBody()); + $this->assertEquals($body, $pdfRequest->getBody()); } /** @@ -317,7 +302,7 @@ public function testRequestDataCanBeFalttened() 'test_param2[1]' => 'Testing3' ); - $this->assertSame($flatData, $pdfRequest->getRequestData(true)); + $this->assertEquals($flatData, $pdfRequest->getRequestData(true)); } /** @@ -339,7 +324,7 @@ public function testRawRequestDataCanBeAccessed() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setRequestData($data); - $this->assertSame($data, $pdfRequest->getRequestData(false)); + $this->assertEquals($data, $pdfRequest->getRequestData(false)); } /** @@ -365,7 +350,7 @@ public function testHeadersCanBeAdded() $expectedHeaders = array_merge($existingHeaders, $newHeaders); - $this->assertSame($expectedHeaders, $pdfRequest->getHeaders()); + $this->assertEquals($expectedHeaders, $pdfRequest->getHeaders()); } /** @@ -387,7 +372,7 @@ public function testHeadersCanBeAccessedInJsonFormat() $expectedHeaders = json_encode($headers); - $this->assertSame($expectedHeaders, $pdfRequest->getHeaders('json')); + $this->assertEquals($expectedHeaders, $pdfRequest->getHeaders('json')); } /** @@ -406,7 +391,7 @@ public function testRawHeadersCanBeAccessed() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setHeaders($headers); - $this->assertSame($headers, $pdfRequest->getHeaders('default')); + $this->assertEquals($headers, $pdfRequest->getHeaders('default')); } /** @@ -439,7 +424,7 @@ public function testCanSetOutputFile() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setOutputFile($outputFile); - $this->assertSame($outputFile, $pdfRequest->getOutputFile()); + $this->assertEquals($outputFile, $pdfRequest->getOutputFile()); } /** @@ -456,7 +441,7 @@ public function testCanSetViewportWidth() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setViewportSize($width, $height); - $this->assertSame($width, $pdfRequest->getViewportWidth()); + $this->assertEquals($width, $pdfRequest->getViewportWidth()); } /** @@ -473,7 +458,7 @@ public function testCanSetViewportHeight() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setViewportSize($width, $height); - $this->assertSame($height, $pdfRequest->getViewportHeight()); + $this->assertEquals($height, $pdfRequest->getViewportHeight()); } /** @@ -490,7 +475,7 @@ public function testCanSetPaperWidth() $pdfRequest = $this->getPdfRequest(); $pdfRequest->setPaperSize($width, $height); - $this->assertSame($width, $pdfRequest->getPaperWidth()); + $this->assertEquals($width, $pdfRequest->getPaperWidth()); } /** @@ -507,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 58210b5..a3b3b75 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()); } /** @@ -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. @@ -146,7 +131,7 @@ public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet() $request->setUrl($url); $request->setRequestData($data); - $this->assertSame($url, $request->getUrl()); + $this->assertEquals($url, $request->getUrl()); } /** @@ -172,7 +157,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsGet() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $request->getUrl()); + $this->assertEquals($expectedUrl, $request->getUrl()); } /** @@ -198,7 +183,7 @@ public function testUrlDoesContainQueryParamsIfMethodIsHead() $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $request->getUrl()); + $this->assertEquals($expectedUrl, $request->getUrl()); } /** @@ -224,7 +209,7 @@ public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams( $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($expectedUrl, $request->getUrl()); + $this->assertEquals($expectedUrl, $request->getUrl()); } /** @@ -245,7 +230,7 @@ public function testRequestContainsNoBodyIfMethodIsGet() $request->setMethod('GET'); $request->setRequestData($data); - $this->assertSame('', $request->getBody()); + $this->assertEquals('', $request->getBody()); } /** @@ -266,7 +251,7 @@ public function testRequestContainsNoBodyIfMethodIsHead() $request->setMethod('HEAD'); $request->setRequestData($data); - $this->assertSame('', $request->getBody()); + $this->assertEquals('', $request->getBody()); } /** @@ -289,7 +274,7 @@ public function testRequestContainsABodyIfMethodIsNotHeadOrGet() $body = 'test_param1=Testing1&test_param2=Testing2'; - $this->assertSame($body, $request->getBody()); + $this->assertEquals($body, $request->getBody()); } /** @@ -317,7 +302,7 @@ public function testRequestDataCanBeFalttened() 'test_param2[1]' => 'Testing3' ); - $this->assertSame($flatData, $request->getRequestData(true)); + $this->assertEquals($flatData, $request->getRequestData(true)); } /** @@ -339,7 +324,7 @@ public function testRawRequestDataCanBeAccessed() $request = $this->getRequest(); $request->setRequestData($data); - $this->assertSame($data, $request->getRequestData(false)); + $this->assertEquals($data, $request->getRequestData(false)); } /** @@ -365,7 +350,7 @@ public function testHeadersCanBeAdded() $expectedHeaders = array_merge($existingHeaders, $newHeaders); - $this->assertSame($expectedHeaders, $request->getHeaders()); + $this->assertEquals($expectedHeaders, $request->getHeaders()); } /** @@ -387,7 +372,7 @@ public function testHeadersCanBeAccessedInJsonFormat() $expectedHeaders = json_encode($headers); - $this->assertSame($expectedHeaders, $request->getHeaders('json')); + $this->assertEquals($expectedHeaders, $request->getHeaders('json')); } /** @@ -406,7 +391,124 @@ 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()); + } + + /** + * 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 + ); + + $cookies = $request->getCookies(); + + $this->assertEquals(array($expected), $cookies['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); + + $cookies = $request->getCookies(); + + $this->assertEquals(array($name), $cookies['delete']); } /** @@ -420,10 +522,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()); } /** @@ -437,10 +539,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 931eff2..8a7c3cb 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()); } /** @@ -103,13 +103,13 @@ public function testUrlCanBeImported() public function testRedirectUrlCanBeImported() { $data = array( - 'redirectUrl' => 'http://test.com' + 'redirectURL' => 'http://test.com' ); $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')); } /** @@ -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 ++++++++++ **/ /** +++++++++++++++++++++++++++++++++++ **/ 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); + } +}