You are here

public function PhantomJSCaptureHelper::capture in PhantomJS Capture 8

Captures a screen shot using PhantomJS by calling the program.

Parameters

Url $url: An instance of Drupal\Core\Url, the address you want to capture.

string $destination: The destination for the file (e.g. public://screenshot).

string $filename: The filename to store the file as.

string $element: The id of the DOM element to render in the document.

Return value

bool Returns TRUE if the screen shot was taken else FALSE on error.

Overrides PhantomJSCaptureHelperInterface::capture

File

src/PhantomJSCaptureHelper.php, line 91

Class

PhantomJSCaptureHelper

Namespace

Drupal\phantomjs_capture

Code

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);
  }

  // Check that destination is writable.
  // @todo: would be nice to throw an exception instead of return FALSE
  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);
  }

  // Check that PhantomJS was able to load the page.
  if ($output[0] == '500') {
    $this->loggerFactory
      ->get('phantomjs_capture')
      ->error('PhantomJS could not capture the URL %url.', [
      '%url' => $url,
    ]);
    return FALSE;
  }
  return TRUE;
}