Skip to content

Commit

Permalink
3.0 (#15)
Browse files Browse the repository at this point in the history
* Updated dependencies, php compatibility, no longer tied to phantomjs

* Added docs for puppeteer

* Use composer's phpunit for travis

* Fixed phpunit test case namespace

* Fixed psr4 config
  • Loading branch information
Padam87 authored Dec 13, 2017
1 parent 4adc34b commit 8bae2c9
Show file tree
Hide file tree
Showing 15 changed files with 136 additions and 229 deletions.
5 changes: 2 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
language: php

php:
- 5.5
- 7.0
- 7.1

matrix:
fast_finish: true

before_script:
- composer update --dev

script: phpunit
script: vendor/bin/phpunit

after_script:
- php vendor/bin/coveralls -v
Expand Down
52 changes: 12 additions & 40 deletions ConfigHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,58 +7,30 @@

class ConfigHelper
{
/**
* @var array
*/
protected $config;
private $config;
private $projectDir;

/**
* @param array $config
*/
public function __construct(array $config)
public function __construct(string $projectDir, array $config)
{
$this->config = $config;
$this->projectDir = $projectDir;
}

/**
* @param InputStream $input
* @param array $arguments
*
* @return Process
*/
public function buildProcess($input, $arguments = array())
public function buildProcess(InputStream $input, array $arguments = []): Process
{
$process = new Process(
array_merge(
[$this->config['phantomjs']['callable']],
$this->processPhantomjsOptions(),
[ $this->config['script'] ],
[
$this->config['script']['callable'],
$this->projectDir . DIRECTORY_SEPARATOR . $this->config['script']['path']
],
array_values(array_merge($this->config['arguments'], $arguments))
),
null, [], $input
null,
[],
$input
);

return $process;
}

/**
* @return array
*/
protected function processPhantomjsOptions()
{
$options = array();

foreach ($this->config['phantomjs']['options'] as $name => $value) {
if (is_numeric($name)) {
$options[] = $value;
} else {
if (is_bool($value)) {
$value = ($value) ? 'true' : 'false';
}
$options[] = sprintf('%s=%s', $name, $value);
}
}

return $options;
}
}
44 changes: 14 additions & 30 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\HttpKernel\Kernel;

class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
Expand All @@ -17,38 +18,16 @@ public function getConfigTreeBuilder()

$rootNode
->children()
->arrayNode('phantomjs')
->arrayNode('script')
->addDefaultsIfNotSet()
->children()
->scalarNode('callable')->defaultValue('phantomjs')->end()
->arrayNode('options')
->info('http://phantomjs.org/api/command-line.html')
->defaultValue(
[
'--output-encoding' => $this->isWin() ? 'ISO-8859-1' : 'UTF-8',
]
)
->normalizeKeys(false)
->beforeNormalization()
->ifTrue(function ($v) {
return !isset($v['--output-encoding']);
})
->then(function ($v) {
return array_merge(
[
'--output-encoding' => $this->isWin() ? 'ISO-8859-1' : 'UTF-8',
],
$v
);
})
->end()
->prototype('scalar')->end()
->scalarNode('callable')->defaultValue('node')->end()
->scalarNode('path')
->defaultValue($this->getAssetsDir() . DIRECTORY_SEPARATOR . 'rasterize.js')
->info('Relative to project dir')
->end()
->end()
->end()
->scalarNode('script')
->defaultValue('../web/bundles/padam87rasterize/js/rasterize.js')->info('Relative to root dir')
->end()
->arrayNode('arguments')
->defaultValue(
[
Expand All @@ -71,8 +50,13 @@ public function getConfigTreeBuilder()
return $treeBuilder;
}

private function isWin()
private function getAssetsDir()
{
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
switch (Kernel::MAJOR_VERSION) {
case 4:
return 'assets';
default:
return 'web';
}
}
}
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,12 @@ $response = new Response(

[Configuration reference](Resources/docs/configuration_reference.md)

**Providers**
- [Puppeteer](Resources/docs/provider/puppeteer.md)
- [PhantomJS](Resources/docs/provider/phantomjs.md)
- [Other](Resources/docs/provider/other.md)

**How to...**
- [pass arguments to the javascript file?](Resources/docs/how_to_pass_arguments.md)
- [ignore SSL errors?](Resources/docs/how_to_ignore_ssl_errors.md)



30 changes: 3 additions & 27 deletions Rasterizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,16 @@

class Rasterizer
{
/**
* @var ConfigHelper
*/
protected $configHelper;

/**
* @var Stopwatch
*/
protected $stopwatch;

/**
* @var array
*/
protected $environment;

/**
* @param ConfigHelper $configHelper
* @param Stopwatch $stopwatch
* @param string $environment
*/
public function __construct(ConfigHelper $configHelper, Stopwatch $stopwatch = null, $environment)
public function __construct(ConfigHelper $configHelper, Stopwatch $stopwatch = null)
{
$this->configHelper = $configHelper;
$this->stopwatch = $stopwatch;
$this->environment = [ $environment ];
}

/**
* @param string $html
* @param array $arguments
*
* @return string
*/
public function rasterize($html, $arguments = array())
public function rasterize(string $html, $arguments = []): string
{
if ($this->stopwatch instanceof Stopwatch) {
$this->stopwatch->start('rasterizer');
Expand All @@ -49,7 +25,7 @@ public function rasterize($html, $arguments = array())
$input = new InputStream();

$process = $this->configHelper->buildProcess($input, $arguments);
$process->start(null, $this->environment);
$process->start(null, []);

$input->write($html);
$input->close();
Expand Down
2 changes: 1 addition & 1 deletion Resources/config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@

<services>
<service id="padam87_rasterize.config_helper" class="%padam87_rasterize.config_helper.class%">
<argument>%kernel.project_dir%</argument>
<argument>%padam87_rasterize.config%</argument>
</service>
<service id="padam87_rasterize.rasterizer" class="%padam87_rasterize.rasterizer.class%" public="true">
<argument type="service" id="padam87_rasterize.config_helper" />
<argument type="service" id="debug.stopwatch" on-invalid="null" />
<argument>%kernel.environment%</argument>
</service>
</services>
</container>
12 changes: 5 additions & 7 deletions Resources/docs/configuration_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,9 @@

```YAML
padam87_rasterize:
phantomjs:
callable: phantomjs
options: # http://phantomjs.org/api/command-line.html
'--output-encoding': 'UTF-8' # will default to ISO-8859-1 on windows
script: /bundles/padam87rasterize/js/rasterize.js # Relative to web dir
arguments: # You can define your own custom arguments. Will be added by default to every process.
format: pdf # Default, will always be added, even if you remove it from here.
script:
callable: node
path: web\rasterize.js # Relative to project dir
arguments:
format: pdf # Default, will always be added, even if you remove it from here.
```
12 changes: 0 additions & 12 deletions Resources/docs/how_to_ignore_ssl_errors.md

This file was deleted.

25 changes: 5 additions & 20 deletions Resources/docs/how_to_pass_arguments.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ First, the configuration should be changed

```yaml
padam87_rasterize:
script: /js/my-rasterize.js
arguments:
format: pdf
orientation: portrait
```
Expand All @@ -17,24 +15,11 @@ Note that the orientation argument has been added, by default it will be set as
A custom javascript is also necessary, to handle the newly received argument.

```js
var page = require('webpage').create(),
system = require('system'),
format;
format = system.args[1];
orientation = system.args[2];
system.stdin.setEncoding('UTF-8'); // force utf8 input encoding even when output is different
var content = system.stdin.read();
page.setContent(content, 'http://localhost');
page.viewportSize = { width: 1920, height: 1080 };
page.paperSize = { format: 'A4', orientation: orientation, border: '1cm' };
page.onLoadFinished = function(success) {
page.render('/dev/stdout', {format: 'pdf'});
phantom.exit();
};
// ...
const args = process.argv;
const format = args[2];
const orientation = args[3];
// ...
```

To change the orientation to `landscape`, you need to add one more parameter to the rasterizer call.
Expand Down
6 changes: 4 additions & 2 deletions Resources/docs/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ $bundles = array(
);
```

### Install assets ###
### Chose a provider ###

`php app/console assets:install`
- [Puppeteer](provider/puppeteer.md)
- [PhantomJS](provider/phantomjs.md)
- [Other](provider/other.md)
48 changes: 48 additions & 0 deletions Resources/docs/provider/puppeteer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Add puppeteer

`yarn add puppeteer` or `npm i puppeteer`

# Create a script
- **Symfony 4:** assets/rasterize.js
- **Symfony 3:** web/rasterize.js

```js
const puppeteer = require('puppeteer');
const fs = require('fs');

let stdinBuffer = fs.readFileSync(0 /* STDIN_FILENO */, 'utf8');
let html = stdinBuffer.toString();

const args = process.argv;
const format = args[2];

(async () => {
const browser = await puppeteer.launch({
ignoreHTTPSErrors: true
});
const page = await browser.newPage();

// https://github.com/GoogleChrome/puppeteer/issues/728
// await page.setContent(html);
// await page.waitForNavigation({ waitUntil: 'networkidle0' });

await page.goto('data:text/html,' + html, { waitUntil: 'networkidle0' });

if (format == 'pdf') {
await page.pdf({
path: 1, // STDOUT_FILENO
format: 'A4',
printBackground: true,
margin: { top: '1cm', right: '1cm', bottom: '1cm', left: '1cm' }
});
} else {
await page.screenshot({
path: 1, // STDOUT_FILENO
type: format,
quality: 100,
});
}

await browser.close();
})();
```
17 changes: 0 additions & 17 deletions Resources/public/js/rasterize.js

This file was deleted.

Loading

0 comments on commit 8bae2c9

Please sign in to comment.