소스 검색

Added support for saving to PDF - https://github.com/jonnnnyw/php-phantomjs/issues/35

Jonny Wenmoth 10 년 전
부모
커밋
176b6a272a

+ 2 - 1
composer.json

@@ -22,7 +22,8 @@
         "jakoch/phantomjs-installer": "1.9.8"
         "jakoch/phantomjs-installer": "1.9.8"
     },
     },
     "require-dev": {
     "require-dev": {
-        "phpunit/phpunit": "~4.0"
+        "phpunit/phpunit": "~4.0",
+        "zendframework/zendpdf": "~2.0"
     },
     },
     "autoload": {
     "autoload": {
         "psr-0": {
         "psr-0": {

+ 9 - 9
src/JonnyW/PhantomJs/Http/CaptureRequest.php

@@ -28,12 +28,12 @@ class CaptureRequest extends AbstractRequest
     protected $type;
     protected $type;
 
 
     /**
     /**
-     * File to save capture.
+     * File to save output.
      *
      *
      * @var string
      * @var string
      * @access protected
      * @access protected
      */
      */
-    protected $captureFile;
+    protected $outputFile;
 
 
     /**
     /**
      * Rect top
      * Rect top
@@ -180,32 +180,32 @@ class CaptureRequest extends AbstractRequest
     }
     }
 
 
     /**
     /**
-     * Set file to save screen capture.
+     * Set file to save output.
      *
      *
      * @access public
      * @access public
      * @param  string                                           $file
      * @param  string                                           $file
      * @throws \JonnyW\PhantomJs\Exception\NotWritableException
      * @throws \JonnyW\PhantomJs\Exception\NotWritableException
      * @return \JonnyW\PhantomJs\Http\CaptureRequest
      * @return \JonnyW\PhantomJs\Http\CaptureRequest
      */
      */
-    public function setCaptureFile($file)
+    public function setOutputFile($file)
     {
     {
         if (!is_writable(dirname($file))) {
         if (!is_writable(dirname($file))) {
-            throw new NotWritableException(sprintf('Capture file is not writeable by PhantomJs: %s', $file));
+            throw new NotWritableException(sprintf('Output file is not writeable by PhantomJs: %s', $file));
         }
         }
 
 
-        $this->captureFile = $file;
+        $this->outputFile = $file;
 
 
         return $this;
         return $this;
     }
     }
 
 
     /**
     /**
-     * Get capture file.
+     * Get output file.
      *
      *
      * @access public
      * @access public
      * @return string
      * @return string
      */
      */
-    public function getCaptureFile()
+    public function getOutputFile()
     {
     {
-        return $this->captureFile;
+        return $this->outputFile;
     }
     }
 }
 }

+ 4 - 4
src/JonnyW/PhantomJs/Http/CaptureRequestInterface.php

@@ -60,18 +60,18 @@ interface CaptureRequestInterface
     public function getRectHeight();
     public function getRectHeight();
 
 
     /**
     /**
-     * Set file to save screen capture.
+     * Set file to save output.
      *
      *
      * @access public
      * @access public
      * @param string $file
      * @param string $file
      */
      */
-    public function setCaptureFile($file);
+    public function setOutputFile($file);
 
 
     /**
     /**
-     * Get capture file.
+     * Get output file.
      *
      *
      * @access public
      * @access public
      * @return string
      * @return string
      */
      */
-    public function getCaptureFile();
+    public function getOutputFile();
 }
 }

+ 18 - 4
src/JonnyW/PhantomJs/Http/MessageFactory.php

@@ -56,16 +56,30 @@ class MessageFactory implements MessageFactoryInterface
      * Create capture request instance.
      * Create capture request instance.
      *
      *
      * @access public
      * @access public
-     * @param  string                         $url
-     * @param  string                         $method
-     * @param  int                            $timeout
-     * @return \JonnyW\PhantomJs\Http\Request
+     * @param  string                                $url
+     * @param  string                                $method
+     * @param  int                                   $timeout
+     * @return \JonnyW\PhantomJs\Http\CaptureRequest
      */
      */
     public function createCaptureRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000)
     public function createCaptureRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000)
     {
     {
         return new CaptureRequest($url, $method, $timeout);
         return new CaptureRequest($url, $method, $timeout);
     }
     }
 
 
+    /**
+     * Create PDF request instance.
+     *
+     * @access public
+     * @param  string                            $url
+     * @param  string                            $method
+     * @param  int                               $timeout
+     * @return \JonnyW\PhantomJs\Http\PdfRequest
+     */
+    public function createPdfRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000)
+    {
+        return new PdfRequest($url, $method, $timeout);
+    }
+
     /**
     /**
      * Create response instance.
      * Create response instance.
      *
      *

+ 11 - 0
src/JonnyW/PhantomJs/Http/MessageFactoryInterface.php

@@ -45,6 +45,17 @@ interface MessageFactoryInterface
      */
      */
     public function createCaptureRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000);
     public function createCaptureRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000);
 
 
+    /**
+     * Create PDF request instance.
+     *
+     * @access public
+     * @param  string                            $url
+     * @param  string                            $method
+     * @param  int                               $timeout
+     * @return \JonnyW\PhantomJs\Http\PdfRequest
+     */
+    public function createPdfRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000);
+
     /**
     /**
      * Create response instance.
      * Create response instance.
      *
      *

+ 224 - 0
src/JonnyW/PhantomJs/Http/PdfRequest.php

@@ -0,0 +1,224 @@
+<?php
+
+/*
+ * This file is part of the php-phantomjs.
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace JonnyW\PhantomJs\Http;
+
+/**
+ * PHP PhantomJs
+ *
+ * @author Jon Wenmoth <contact@jonnyw.me>
+ */
+class PdfRequest extends CaptureRequest
+    implements PdfRequestInterface
+{
+    /**
+     * Paper width
+     *
+     * @var int
+     * @access protected
+     */
+    protected $paperWidth;
+
+    /**
+     * Paper height
+     *
+     * @var int
+     * @access protected
+     */
+    protected $paperHeight;
+
+    /**
+     * Format
+     *
+     * @var string
+     * @access protected
+     */
+    protected $format;
+
+    /**
+     * Orientation
+     *
+     * @var string
+     * @access protected
+     */
+    protected $orientation;
+
+    /**
+     * Margin
+     *
+     * @var string
+     * @access protected
+     */
+    protected $margin;
+
+    /**
+     * Internal constructor
+     *
+     * @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->paperWidth  = '';
+        $this->paperHeight = '';
+        $this->margin      = '1cm';
+        $this->format      = 'A4';
+        $this->orientation = 'portrait';
+
+    }
+
+    /**
+     * Get request type
+     *
+     * @access public
+     * @return string
+     */
+    public function getType()
+    {
+        if (!$this->type) {
+            return RequestInterface::REQUEST_TYPE_PDF;
+        }
+
+        return $this->type;
+    }
+
+    /**
+     * Set paper width.
+     *
+     * @access public
+     * @param  string $width
+     * @return void
+     */
+    public function setPaperWidth($width)
+    {
+        $this->paperWidth = $width;
+    }
+
+    /**
+     * Get paper width.
+     *
+     * @access public
+     * @return string
+     */
+    public function getPaperWidth()
+    {
+        return $this->paperWidth;
+    }
+
+    /**
+     * Set paper height.
+     *
+     * @access public
+     * @param  string $height
+     * @return void
+     */
+    public function setPaperHeight($height)
+    {
+        $this->paperHeight = $height;
+    }
+
+    /**
+     * Get paper height.
+     *
+     * @access public
+     * @return string
+     */
+    public function getPaperHeight()
+    {
+        return $this->paperHeight;
+    }
+
+    /**
+     * Set paper size.
+     *
+     * @access public
+     * @param  string $width
+     * @param  string $height
+     * @return void
+     */
+    public function setPaperSize($width, $height)
+    {
+        $this->paperWidth  = $width;
+        $this->paperHeight = $height;
+    }
+
+    /**
+     * Set format.
+     *
+     * @access public
+     * @param  string $format
+     * @return void
+     */
+    public function setFormat($format)
+    {
+        $this->format = $format;
+    }
+
+    /**
+     * Get format.
+     *
+     * @access public
+     * @return string
+     */
+    public function getFormat()
+    {
+        return $this->format;
+    }
+
+    /**
+     * Set orientation.
+     *
+     * @access public
+     * @param  string $orientation
+     * @return void
+     */
+    public function setOrientation($orientation)
+    {
+        $this->orientation = $orientation;
+    }
+
+    /**
+     * Get orientation.
+     *
+     * @access public
+     * @return string
+     */
+    public function getOrientation()
+    {
+        return $this->orientation;
+    }
+
+    /**
+     * Set margin.
+     *
+     * @access public
+     * @param  string $margin
+     * @return void
+     */
+    public function setMargin($margin)
+    {
+        $this->margin = $margin;
+    }
+
+    /**
+     * Get margin.
+     *
+     * @access public
+     * @return string
+     */
+    public function getMargin()
+    {
+        return $this->margin;
+    }
+}

+ 113 - 0
src/JonnyW/PhantomJs/Http/PdfRequestInterface.php

@@ -0,0 +1,113 @@
+<?php
+
+/*
+ * This file is part of the php-phantomjs.
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace JonnyW\PhantomJs\Http;
+
+/**
+ * PHP PhantomJs
+ *
+ * @author Jon Wenmoth <contact@jonnyw.me>
+ */
+interface PdfRequestInterface
+{
+    /**
+     * Set paper width.
+     *
+     * @access public
+     * @param  string $width
+     * @return void
+     */
+    public function setPaperWidth($width);
+
+    /**
+     * Get paper width.
+     *
+     * @access public
+     * @return string
+     */
+    public function getPaperWidth();
+
+    /**
+     * Set paper height.
+     *
+     * @access public
+     * @param  string $height
+     * @return void
+     */
+    public function setPaperHeight($height);
+
+    /**
+     * Get paper height.
+     *
+     * @access public
+     * @return string
+     */
+    public function getPaperHeight();
+
+    /**
+     * Set paper size.
+     *
+     * @access public
+     * @param  string $width
+     * @param  string $height
+     * @return void
+     */
+    public function setPaperSize($width, $height);
+
+    /**
+     * Set format.
+     *
+     * @access public
+     * @param  string $format
+     * @return void
+     */
+    public function setFormat($format);
+
+    /**
+     * Get format.
+     *
+     * @access public
+     * @return string
+     */
+    public function getFormat();
+
+    /**
+     * Set orientation.
+     *
+     * @access public
+     * @param  string $orientation
+     * @return void
+     */
+    public function setOrientation($orientation);
+
+    /**
+     * Get orientation.
+     *
+     * @access public
+     * @return string
+     */
+    public function getOrientation();
+
+    /**
+     * Set margin.
+     *
+     * @access public
+     * @param  string $margin
+     * @return void
+     */
+    public function setMargin($margin);
+
+    /**
+     * Get margin.
+     *
+     * @access public
+     * @return string
+     */
+    public function getMargin();
+}

+ 1 - 0
src/JonnyW/PhantomJs/Http/RequestInterface.php

@@ -26,6 +26,7 @@ interface RequestInterface
 
 
     const REQUEST_TYPE_DEFAULT = 'default';
     const REQUEST_TYPE_DEFAULT = 'default';
     const REQUEST_TYPE_CAPTURE = 'capture';
     const REQUEST_TYPE_CAPTURE = 'capture';
+    const REQUEST_TYPE_PDF     = 'pdf';
 
 
     /**
     /**
      * Get request type
      * Get request type

+ 6 - 1
src/JonnyW/PhantomJs/Resources/procedures/http_default.proc

@@ -18,10 +18,15 @@ var page       = require('webpage').create(),
 [[ engine.load('global_variables') ]]
 [[ engine.load('global_variables') ]]
 
 
 /**
 /**
- * Define width & height of screenshot
+ * Define width & height of capture
  */
  */
 [[ engine.load('page_clip_rect') ]]
 [[ engine.load('page_clip_rect') ]]
 
 
+/**
+ * Define paper size.
+ */
+[[ engine.load('page_paper_size') ]]
+
 /**
 /**
  * Define viewport size.
  * Define viewport size.
  */
  */

+ 11 - 11
src/JonnyW/PhantomJs/Resources/procedures/page_clip_rect.partial

@@ -1,20 +1,20 @@
 
 
-{% if input.getType() == 'capture' %}
+{% if input.getType() == 'capture' or input.getType() == 'pdf' %}
 
 
-var top    = {{ input.getRectTop() }},
-    left   = {{ input.getRectLeft() }},
-    width  = {{ input.getRectWidth() }},
-    height = {{ input.getRectHeight() }};
+var rectTop    = {{ input.getRectTop() }},
+    rectLeft   = {{ input.getRectLeft() }},
+    rectWidth  = {{ input.getRectWidth() }},
+    rectHeight = {{ input.getRectHeight() }};
 
 
-if(width && height) {
+if(rectWidth && rectHeight) {
     
     
-    debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set capture clipping size ~ top: ' + top + ' left: ' + left + ' ' + width + 'x' + height);
+    debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set capture clipping size ~ top: ' + rectTop + ' left: ' + rectLeft + ' ' + rectWidth + 'x' + rectHeight);
     
     
     page.clipRect = {
     page.clipRect = {
-        top: top,
-        left: left,
-        width: width,
-        height: height
+        top: rectTop,
+        left: rectLeft,
+        width: rectWidth,
+        height: rectHeight
     };
     };
 }
 }
 
 

+ 32 - 0
src/JonnyW/PhantomJs/Resources/procedures/page_paper_size.partial

@@ -0,0 +1,32 @@
+
+{% if input.getType() == 'pdf' %}
+
+    var paperWidth       = '{{ input.getPaperWidth() }}',
+        paperHeight      = '{{ input.getPaperHeight() }}',
+        paperFormat      = '{{ input.getFormat() }}',
+        paperOrientation = '{{ input.getOrientation() }}',
+        paperMargin      = '{{ input.getMargin() }}';
+    
+    if(paperWidth && paperHeight) {
+        
+        debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set page size ~ width: ' + paperWidth + ' height: ' + paperHeight + ' margin: ' + paperMargin);
+        
+        page.paperSize = { 
+            width:  paperWidth, 
+            height: paperHeight, 
+            margin: paperMargin 
+        };
+
+    } else {
+        
+        debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set page size ~ format: ' + paperFormat + ' orientation: ' + paperOrientation + ' margin: ' + paperMargin);
+        
+        page.paperSize = { 
+            format:      paperFormat, 
+            orientation: paperOrientation, 
+            margin:      paperMargin 
+        };
+        
+    }
+
+{% endif %}

+ 6 - 6
src/JonnyW/PhantomJs/Resources/procedures/page_viewport_size.partial

@@ -1,14 +1,14 @@
 
 
-var width  = {{ input.getViewportWidth() }},
-    height = {{ input.getViewportHeight() }};
+var viewportWidth  = {{ input.getViewportWidth() }},
+    viewportHeight = {{ input.getViewportHeight() }};
 
 
-if(width && height) {
+if(viewportWidth && viewportHeight) {
     
     
-    debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set viewport size ~ width: ' + width + ' height: ' + height);
+    debug.push(new Date().toISOString().slice(0, -5) + ' [INFO] PhantomJS - Set viewport size ~ width: ' + viewportWidth + ' height: ' + viewportHeight);
     
     
     page.viewportSize = {
     page.viewportSize = {
-        width: width,
-        height: height
+        width: viewportWidth,
+        height: viewportHeight
     };
     };
 }
 }
 
 

+ 1 - 1
src/JonnyW/PhantomJs/Resources/procedures/procedure_capture.partial

@@ -3,7 +3,7 @@ if (status === 'success') {
     
     
     try {
     try {
     
     
-        page.render('{{ input.getCaptureFile() }}');
+        page.render('{{ input.getOutputFile() }}');
         
         
         response.content = page.evaluate(function () {
         response.content = page.evaluate(function () {
             return document.getElementsByTagName('html')[0].innerHTML
             return document.getElementsByTagName('html')[0].innerHTML

+ 25 - 0
src/JonnyW/PhantomJs/Resources/procedures/procedure_pdf.partial

@@ -0,0 +1,25 @@
+
+if (status === 'success') {
+    
+    try {
+    
+        page.render('{{ input.getOutputFile() }}');
+        
+        response.content = page.evaluate(function () {
+            return document.getElementsByTagName('html')[0].innerHTML
+        });
+    
+    } catch(e) {
+
+        response.status  = 500;
+        response.content = e.message;
+    }
+}
+
+response.console = logs;
+
+system.stderr.write(debug.join('\\n') + '\\n');
+system.stdout.write(JSON.stringify(response, undefined, 4));
+
+phantom.exit();
+

+ 134 - 2
src/JonnyW/PhantomJs/Tests/Integration/ClientTest.php

@@ -289,7 +289,7 @@ EOF;
 
 
         $request->setMethod('GET');
         $request->setMethod('GET');
         $request->setUrl('http://jonnyw.kiwi/tests/test-console-error.php');
         $request->setUrl('http://jonnyw.kiwi/tests/test-console-error.php');
-        $request->setCaptureFile($file);
+        $request->setOutputFile($file);
 
 
         $client->send($request, $response);
         $client->send($request, $response);
 
 
@@ -318,7 +318,7 @@ EOF;
 
 
         $request->setMethod('GET');
         $request->setMethod('GET');
         $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php');
         $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php');
-        $request->setCaptureFile($file);
+        $request->setOutputFile($file);
         $request->setCaptureDimensions($width, $height);
         $request->setCaptureDimensions($width, $height);
 
 
         $client->send($request, $response);
         $client->send($request, $response);
@@ -329,6 +329,138 @@ EOF;
         $this->assertEquals($height, $imageInfo[1]);
         $this->assertEquals($height, $imageInfo[1]);
     }
     }
 
 
+    /**
+     * 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);
+
+        $client = $this->getClient();
+
+        $request  = $client->getMessageFactory()->createPdfRequest();
+        $response = $client->getMessageFactory()->createResponse();
+
+        $request->setMethod('GET');
+        $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php');
+        $request->setOutputFile($file);
+
+        $client->send($request, $response);
+
+        $this->assertTrue(file_exists($file));
+    }
+
+    /**
+     * Test capture 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);
+
+        $width  = 20;
+        $height = 30;
+
+        $client = $this->getClient();
+
+        $request  = $client->getMessageFactory()->createPdfRequest();
+        $response = $client->getMessageFactory()->createResponse();
+
+        $request->setMethod('GET');
+        $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php');
+        $request->setOutputFile($file);
+        $request->setPaperSize(sprintf('%scm', $width), sprintf('%scm', $height));
+        $request->setMargin('0cm');
+
+        $client->send($request, $response);
+
+        $pdf = \ZendPdf\PdfDocument::load($file);
+
+        $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
+     * disk with correct format size.
+     *
+     * @access public
+     * @return void
+     */
+    public function testPdfRequestSavesFileToDiskWithCorrectFormatSize()
+    {
+        $this->filename = 'test.pdf';
+        $file = ($this->directory . '/' . $this->filename);
+
+        $client = $this->getClient();
+
+        $request  = $client->getMessageFactory()->createPdfRequest();
+        $response = $client->getMessageFactory()->createResponse();
+
+        $request->setMethod('GET');
+        $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php');
+        $request->setOutputFile($file);
+        $request->setFormat('A4');
+        $request->setMargin('0cm');
+
+        $client->send($request, $response);
+
+        $pdf = \ZendPdf\PdfDocument::load($file);
+
+        $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
+     * disk with correct orientation.
+     *
+     * @access public
+     * @return void
+     */
+    public function testPdfRequestSavesFileToDiskWithCorrectOrientation()
+    {
+        $this->filename = 'test.pdf';
+        $file = ($this->directory . '/' . $this->filename);
+
+        $client = $this->getClient();
+
+        $request  = $client->getMessageFactory()->createPdfRequest();
+        $response = $client->getMessageFactory()->createResponse();
+
+        $request->setMethod('GET');
+        $request->setUrl('http://jonnyw.kiwi/tests/test-capture.php');
+        $request->setOutputFile($file);
+        $request->setFormat('A4');
+        $request->setOrientation('landscape');
+        $request->setMargin('0cm');
+
+        $client->send($request, $response);
+
+        $pdf = \ZendPdf\PdfDocument::load($file);
+
+        $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 set viewport size sets
      * Test set viewport size sets
      * size of viewport in default
      * size of viewport in default

+ 8 - 8
src/JonnyW/PhantomJs/Tests/Unit/Http/CaptureRequestTest.php

@@ -481,35 +481,35 @@ class CaptureRequestTest extends \PHPUnit_Framework_TestCase
 
 
     /**
     /**
      * Test not writable exception is thrown if
      * Test not writable exception is thrown if
-     * capture path is not writable.
+     * output path is not writable.
      *
      *
      * @access public
      * @access public
      * @return void
      * @return void
      */
      */
-    public function tesNotWritableExceptonIsThrownIfCapturePathIsNotWritable()
+    public function tesNotWritableExceptonIsThrownIfOutputPathIsNotWritable()
     {
     {
         $this->setExpectedException('\JonnyW\PhantomJs\Exception\NotWritableException');
         $this->setExpectedException('\JonnyW\PhantomJs\Exception\NotWritableException');
 
 
         $invalidPath = '/invalid/path';
         $invalidPath = '/invalid/path';
 
 
         $captureRequest = $this->getCaptureRequest();
         $captureRequest = $this->getCaptureRequest();
-        $captureRequest->setCaptureFile($invalidPath);
+        $captureRequest->setOutputFile($invalidPath);
     }
     }
 
 
     /**
     /**
-     * Test can set capture file.
+     * Test can set output file.
      *
      *
      * @access public
      * @access public
      * @return void
      * @return void
      */
      */
-    public function testCanSetCaptureFile()
+    public function testCanSetOutputFile()
     {
     {
-        $captureFile = sprintf('%s/test.jpg', sys_get_temp_dir());
+        $outputFile = sprintf('%s/test.jpg', sys_get_temp_dir());
 
 
         $captureRequest = $this->getCaptureRequest();
         $captureRequest = $this->getCaptureRequest();
-        $captureRequest->setCaptureFile($captureFile);
+        $captureRequest->setOutputFile($outputFile);
 
 
-        $this->assertSame($captureFile, $captureRequest->getCaptureFile());
+        $this->assertSame($outputFile, $captureRequest->getOutputFile());
     }
     }
 
 
     /**
     /**

+ 532 - 0
src/JonnyW/PhantomJs/Tests/Unit/Http/PdfRequestTest.php

@@ -0,0 +1,532 @@
+<?php
+
+/*
+ * This file is part of the php-phantomjs.
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+namespace JonnyW\PhantomJs\Tests\Unit\Http;
+
+use JonnyW\PhantomJs\Http\PdfRequest;
+use JonnyW\PhantomJs\Http\RequestInterface;
+
+/**
+ * PHP PhantomJs
+ *
+ * @author Jon Wenmoth <contact@jonnyw.me>
+ */
+class PdfRequestTest extends \PHPUnit_Framework_TestCase
+{
+
+/** +++++++++++++++++++++++++++++++++++ **/
+/** ++++++++++++++ TESTS ++++++++++++++ **/
+/** +++++++++++++++++++++++++++++++++++ **/
+
+    /**
+     * Test PDF type is returned by default
+     * if no type is set.
+     *
+     * @access public
+     * @return void
+     */
+    public function testPdfTypeIsReturnedByDefaultIfNotTypeIsSet()
+    {
+        $pdfRequest = $this->getPdfRequest();
+
+        $this->assertSame(RequestInterface::REQUEST_TYPE_PDF, $pdfRequest->getType());
+    }
+
+    /**
+     * Test custom type can be set.
+     *
+     * @access public
+     * @return void
+     */
+    public function testCustomTypeCanBeSet()
+    {
+        $requestType = 'testType';
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setType($requestType);
+
+        $this->assertSame($requestType, $pdfRequest->getType());
+    }
+
+    /**
+     * Test URL can be set via constructor.
+     *
+     * @access public
+     * @return void
+     */
+    public function testUrlCanBeSetViaConstructor()
+    {
+        $url            = 'http://test.com';
+        $pdfRequest = $this->getPdfRequest($url);
+
+        $this->assertSame($url, $pdfRequest->getUrl());
+    }
+
+    /**
+     * Test method can be set via constructor.
+     *
+     * @access public
+     * @return void
+     */
+    public function testMethodCanBeSetViaConstructor()
+    {
+        $method         = 'GET';
+        $pdfRequest = $this->getPdfRequest(null, $method);
+
+        $this->assertSame($method, $pdfRequest->getMethod());
+    }
+
+    /**
+     * Test timeout can be set via constructor.
+     *
+     * @access public
+     * @return void
+     */
+    public function testTimeoutCanBeSetViaConstructor()
+    {
+        $timeout        = 100000;
+        $pdfRequest = $this->getPdfRequest('http://test.com', 'GET', $timeout);
+
+        $this->assertSame($timeout, $pdfRequest->getTimeout());
+    }
+
+    /**
+     * Test invalid method is thrown if method
+     * is invalid.
+     *
+     * @access public
+     * @return void
+     */
+    public function testInvalidMethodIsThrownIfMethodIsInvalid()
+    {
+        $this->setExpectedException('\JonnyW\PhantomJs\Exception\InvalidMethodException');
+
+        $pdfRequest = $this->getPdfRequest();
+        $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.
+     *
+     * @access public
+     * @return void
+     */
+    public function testUrlDoesNotContainQueryParamsIfMethodIsNotHeadOrGet()
+    {
+        $url = 'http://test.com';
+
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('POST');
+        $pdfRequest->setUrl($url);
+        $pdfRequest->setRequestData($data);
+
+        $this->assertSame($url, $pdfRequest->getUrl());
+    }
+
+    /**
+     * Test URL does contain query params if mehthod
+     * is GET.
+     *
+     * @access public
+     * @return void
+     */
+    public function testUrlDoesContainQueryParamsIfMethodIsGet()
+    {
+        $url = 'http://test.com';
+
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('GET');
+        $pdfRequest->setUrl($url);
+        $pdfRequest->setRequestData($data);
+
+        $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2';
+
+        $this->assertSame($expectedUrl, $pdfRequest->getUrl());
+    }
+
+    /**
+     * Test URL does contain query params if method
+     * is HEAD.
+     *
+     * @access public
+     * @return void
+     */
+    public function testUrlDoesContainQueryParamsIfMethodIsHead()
+    {
+        $url = 'http://test.com';
+
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('HEAD');
+        $pdfRequest->setUrl($url);
+        $pdfRequest->setRequestData($data);
+
+        $expectedUrl = $url . '?test_param1=Testing1&test_param2=Testing2';
+
+        $this->assertSame($expectedUrl, $pdfRequest->getUrl());
+    }
+
+    /**
+     * Test query params are appended to URL if
+     * URL contains existng query params.
+     *
+     * @access public
+     * @return void
+     */
+    public function testQueryParamsAreAppendedToUrlIfUrlContainsExistingQueryParams()
+    {
+        $url = 'http://test.com?existing_param=Existing';
+
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('GET');
+        $pdfRequest->setUrl($url);
+        $pdfRequest->setRequestData($data);
+
+        $expectedUrl = $url . '&test_param1=Testing1&test_param2=Testing2';
+
+        $this->assertSame($expectedUrl, $pdfRequest->getUrl());
+    }
+
+    /**
+     * Test request contains no body if method
+     * is GET.
+     *
+     * @access public
+     * @return void
+     */
+    public function testRequestContainsNoBodyIfMethodIsGet()
+    {
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('GET');
+        $pdfRequest->setRequestData($data);
+
+        $this->assertSame('', $pdfRequest->getBody());
+    }
+
+    /**
+     * Test request contains no body if method
+     * is HEAD.
+     *
+     * @access public
+     * @return void
+     */
+    public function testRequestContainsNoBodyIfMethodIsHead()
+    {
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('HEAD');
+        $pdfRequest->setRequestData($data);
+
+        $this->assertSame('', $pdfRequest->getBody());
+    }
+
+    /**
+     * Test request contains a body if method is
+     * not HEAD or GET.
+     *
+     * @access public
+     * @return void
+     */
+    public function testRequestContainsABodyIfMethodIsNotHeadOrGet()
+    {
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => 'Testing2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setMethod('POST');
+        $pdfRequest->setRequestData($data);
+
+        $body = 'test_param1=Testing1&test_param2=Testing2';
+
+        $this->assertSame($body, $pdfRequest->getBody());
+    }
+
+    /**
+     * Test request data can be flattened.
+     *
+     * @access public
+     * @return void
+     */
+    public function testRequestDataCanBeFalttened()
+    {
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => array(
+                'Testing2',
+                'Testing3'
+            )
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setRequestData($data);
+
+        $flatData = array(
+            'test_param1'    => 'Testing1',
+            'test_param2[0]' => 'Testing2',
+            'test_param2[1]' => 'Testing3'
+        );
+
+        $this->assertSame($flatData, $pdfRequest->getRequestData(true));
+    }
+
+    /**
+     * Test raw request data can be accessed.
+     *
+     * @access public
+     * @return void
+     */
+    public function testRawRequestDataCanBeAccessed()
+    {
+        $data = array(
+            'test_param1' => 'Testing1',
+            'test_param2' => array(
+                'Testing2',
+                'Testing3'
+            )
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setRequestData($data);
+
+        $this->assertSame($data, $pdfRequest->getRequestData(false));
+    }
+
+    /**
+     * Test headers can be added.
+     *
+     * @access public
+     * @return void
+     */
+    public function testHeadersCanBeAdded()
+    {
+        $existingHeaders = array(
+            'Header1' => 'Header 1'
+        );
+
+        $newHeaders = array(
+            'Header2' => 'Header 2',
+            'Header3' => 'Header 3'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setHeaders($existingHeaders);
+        $pdfRequest->addHeaders($newHeaders);
+
+        $expectedHeaders = array_merge($existingHeaders, $newHeaders);
+
+        $this->assertSame($expectedHeaders, $pdfRequest->getHeaders());
+    }
+
+    /**
+     * Test headers can be accessed in
+     * JSON format
+     *
+     * @access public
+     * @return void
+     */
+    public function testHeadersCanBeAccessedInJsonFormat()
+    {
+        $headers = array(
+            'Header1' => 'Header 1',
+            'Header2' => 'Header 2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setHeaders($headers);
+
+        $expectedHeaders = json_encode($headers);
+
+        $this->assertSame($expectedHeaders, $pdfRequest->getHeaders('json'));
+    }
+
+    /**
+     * Test raw headers can be accessed.
+     *
+     * @access public
+     * @return void
+     */
+    public function testRawHeadersCanBeAccessed()
+    {
+        $headers = array(
+            'Header1' => 'Header 1',
+            'Header2' => 'Header 2'
+        );
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setHeaders($headers);
+
+        $this->assertSame($headers, $pdfRequest->getHeaders('default'));
+    }
+
+    /**
+     * Test not writable exception is thrown if
+     * output path is not writable.
+     *
+     * @access public
+     * @return void
+     */
+    public function tesNotWritableExceptonIsThrownIfOutputPathIsNotWritable()
+    {
+        $this->setExpectedException('\JonnyW\PhantomJs\Exception\NotWritableException');
+
+        $invalidPath = '/invalid/path';
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setOutputFile($invalidPath);
+    }
+
+    /**
+     * Test can set output file.
+     *
+     * @access public
+     * @return void
+     */
+    public function testCanSetOutputFile()
+    {
+        $outputFile = sprintf('%s/test.jpg', sys_get_temp_dir());
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setOutputFile($outputFile);
+
+        $this->assertSame($outputFile, $pdfRequest->getOutputFile());
+    }
+
+    /**
+     * Test can set viewport width.
+     *
+     * @access public
+     * @return void
+     */
+    public function testCanSetViewportWidth()
+    {
+        $width  = 100;
+        $height = 200;
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setViewportSize($width, $height);
+
+        $this->assertSame($width, $pdfRequest->getViewportWidth());
+    }
+
+    /**
+     * Test can set viewport height.
+     *
+     * @access public
+     * @return void
+     */
+    public function testCanSetViewportHeight()
+    {
+        $width  = 100;
+        $height = 200;
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setViewportSize($width, $height);
+
+        $this->assertSame($height, $pdfRequest->getViewportHeight());
+    }
+
+    /**
+     * Test can set paper width.
+     *
+     * @access public
+     * @return void
+     */
+    public function testCanSetPaperWidth()
+    {
+        $width  = '10cm';
+        $height = '20cm';
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setPaperSize($width, $height);
+
+        $this->assertSame($width, $pdfRequest->getPaperWidth());
+    }
+
+    /**
+     * Test can set paper height.
+     *
+     * @access public
+     * @return void
+     */
+    public function testCanSetPaperHeight()
+    {
+        $width  = '10cm';
+        $height = '20cm';
+
+        $pdfRequest = $this->getPdfRequest();
+        $pdfRequest->setPaperSize($width, $height);
+
+        $this->assertSame($height, $pdfRequest->getPaperHeight());
+    }
+
+/** +++++++++++++++++++++++++++++++++++ **/
+/** ++++++++++ TEST ENTITIES ++++++++++ **/
+/** +++++++++++++++++++++++++++++++++++ **/
+
+    /**
+     * Get PDF request instance.
+     *
+     * @access protected
+     * @param  string                            $url     (default: null)
+     * @param  string                            $method  (default: RequestInterface::METHOD_GET)
+     * @param  int                               $timeout (default: 5000)
+     * @return \JonnyW\PhantomJs\Http\PdfRequest
+     */
+    protected function getPdfRequest($url = null, $method = RequestInterface::METHOD_GET, $timeout = 5000)
+    {
+        $pdfRequest = new PdfRequest($url, $method, $timeout);
+
+        return $pdfRequest;
+    }
+}