ProviderPluginBase.php in Video Embed Field 8
File
src/ProviderPluginBase.php
View source
<?php
namespace Drupal\video_embed_field;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\PluginBase;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class ProviderPluginBase extends PluginBase implements ProviderPluginInterface, ContainerFactoryPluginInterface {
protected $thumbsDirectory = 'public://video_thumbnails';
protected $videoId;
protected $input;
protected $httpClient;
protected $fileSystem;
public function __construct($configuration, $plugin_id, $plugin_definition, ClientInterface $http_client) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
if (!static::isApplicable($configuration['input'])) {
throw new \Exception('Tried to create a video provider plugin with invalid input.');
}
$this->input = $configuration['input'];
$this->videoId = $this
->getIdFromInput($configuration['input']);
$this->httpClient = $http_client;
}
protected function getVideoId() {
return $this->videoId;
}
protected function getFileSystem() {
if (!isset($this->fileSystem)) {
$this->fileSystem = \Drupal::service('file_system');
}
return $this->fileSystem;
}
protected function getInput() {
return $this->input;
}
public static function isApplicable($input) {
$id = static::getIdFromInput($input);
return !empty($id);
}
public function renderThumbnail($image_style, $link_url) {
$output = [
'#theme' => 'image',
'#uri' => $this
->getLocalThumbnailUri(),
];
if (!empty($image_style)) {
$output['#theme'] = 'image_style';
$output['#style_name'] = $image_style;
}
if ($link_url) {
$output = [
'#type' => 'link',
'#title' => $output,
'#url' => $link_url,
];
}
return $output;
}
public function downloadThumbnail() {
$local_uri = $this
->getLocalThumbnailUri();
if (!file_exists($local_uri)) {
$this
->getFileSystem()
->prepareDirectory($this->thumbsDirectory, FileSystemInterface::CREATE_DIRECTORY);
try {
$thumbnail = $this->httpClient
->request('GET', $this
->getRemoteThumbnailUrl());
$this
->getFileSystem()
->saveData((string) $thumbnail
->getBody(), $local_uri);
} catch (\Exception $e) {
}
}
}
public function getLocalThumbnailUri() {
return $this->thumbsDirectory . '/' . $this
->getVideoId() . '.jpg';
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('http_client'));
}
public function getName() {
return $this
->t('@provider Video (@id)', [
'@provider' => $this
->getPluginDefinition()['title'],
'@id' => $this
->getVideoId(),
]);
}
}