PhantomJSCaptureHelper.php in PhantomJS Capture 8
File
src/PhantomJSCaptureHelper.php
View source
<?php
namespace Drupal\phantomjs_capture;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\File\FileSystemInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
use Drupal\phantomjs_capture\PhantomJSCaptureHelperInterface;
use Drupal\Core\Url;
class PhantomJSCaptureHelper implements PhantomJSCaptureHelperInterface {
private $configFactory;
private $loggerFactory;
private $fileSystem;
private $config;
public function __construct(ConfigFactoryInterface $config_factory, FileSystemInterface $file_system, LoggerChannelFactoryInterface $logger) {
$this->configFactory = $config_factory;
$this->fileSystem = $file_system;
$this->loggerFactory = $logger;
$this->config = $this->configFactory
->get('phantomjs_capture.settings');
}
public function binaryExists($path) {
if (is_null($path) || !file_exists($path)) {
throw new FileNotFoundException($path);
}
return TRUE;
}
public function getVersion() {
$binary = $this->config
->get('binary');
if ($this
->binaryExists($binary)) {
$output = [];
exec($binary . ' -v', $output);
return $output[0];
}
return FALSE;
}
public function capture(Url $url, $destination, $filename, $element = NULL) {
$binary = $this->config
->get('binary');
$script = $this->fileSystem
->realpath($this->config
->get('script'));
if (!$this
->binaryExists($binary)) {
throw new FileNotFoundException($binary);
}
if (!file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
$this->loggerFactory
->get('phantomjs_capture')
->error('The directory %directory for the file %filename could not be created or is not accessible.', [
'%directory' => $destination,
'%filename' => $filename,
]);
return FALSE;
}
$url = $url
->toUriString();
$destination = $this->fileSystem
->realpath($destination . '/' . $filename);
$output = [];
if ($element) {
exec($binary . ' ' . $script . ' "' . $url . '" ' . $destination . ' ' . escapeshellarg($element), $output);
}
else {
exec($binary . ' ' . $script . ' "' . $url . '" ' . $destination, $output);
}
if ($output[0] == '500') {
$this->loggerFactory
->get('phantomjs_capture')
->error('PhantomJS could not capture the URL %url.', [
'%url' => $url,
]);
return FALSE;
}
return TRUE;
}
}