Same filename and directory in other branches
- 8.9.x core/modules/image/src/Entity/ImageStyle.php
- 9 core/modules/image/src/Entity/ImageStyle.php
Namespace
Drupal\image\Entity
File
core/modules/image/src/Entity/ImageStyle.php
View source
<?php
namespace Drupal\image\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
use Drupal\Core\File\Exception\FileException;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Routing\RequestHelper;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\Url;
use Drupal\image\ImageEffectPluginCollection;
use Drupal\image\ImageEffectInterface;
use Drupal\image\ImageStyleInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
class ImageStyle extends ConfigEntityBase implements ImageStyleInterface, EntityWithPluginCollectionInterface {
protected $name;
protected $label;
protected $effects = [];
protected $effectsCollection;
public function id() {
return $this->name;
}
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
parent::postSave($storage, $update);
if ($update) {
if (!empty($this->original) && $this
->id() !== $this->original
->id()) {
$this->original
->flush();
if (!$this
->isSyncing()) {
static::replaceImageStyle($this);
}
}
else {
$this
->flush();
}
}
}
public static function postDelete(EntityStorageInterface $storage, array $entities) {
parent::postDelete($storage, $entities);
foreach ($entities as $style) {
$style
->flush();
$storage
->clearReplacementId($style
->id());
}
}
protected static function replaceImageStyle(ImageStyleInterface $style) {
if ($style
->id() != $style
->getOriginalId()) {
foreach (EntityViewDisplay::loadMultiple() as $display) {
foreach ($display
->getComponents() as $name => $options) {
if (isset($options['type']) && $options['type'] == 'image' && $options['settings']['image_style'] == $style
->getOriginalId()) {
$options['settings']['image_style'] = $style
->id();
$display
->setComponent($name, $options)
->save();
}
}
}
foreach (EntityFormDisplay::loadMultiple() as $display) {
foreach ($display
->getComponents() as $name => $options) {
if (isset($options['type']) && $options['type'] == 'image_image' && $options['settings']['preview_image_style'] == $style
->getOriginalId()) {
$options['settings']['preview_image_style'] = $style
->id();
$display
->setComponent($name, $options)
->save();
}
}
}
}
}
public function buildUri($uri) {
$source_scheme = $scheme = StreamWrapperManager::getScheme($uri);
$default_scheme = $this
->fileDefaultScheme();
if ($source_scheme) {
$path = StreamWrapperManager::getTarget($uri);
if ($source_scheme != $default_scheme) {
$class = $this
->getStreamWrapperManager()
->getClass($source_scheme);
$is_writable = NULL;
if ($class) {
$is_writable = $class::getType() & StreamWrapperInterface::WRITE;
}
$scheme = $is_writable ? $source_scheme : $default_scheme;
}
}
else {
$path = $uri;
$source_scheme = $scheme = $default_scheme;
}
return "{$scheme}://styles/{$this->id()}/{$source_scheme}/{$this->addExtension($path)}";
}
public function buildUrl($path, $clean_urls = NULL) {
$stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
$uri = $stream_wrapper_manager
->normalizeUri($this
->buildUri($path));
$token_query = [];
if (!\Drupal::config('image.settings')
->get('suppress_itok_output')) {
if (!$stream_wrapper_manager::getScheme($path)) {
$path = \Drupal::config('system.file')
->get('default_scheme') . '://' . $path;
}
$original_uri = $stream_wrapper_manager
->normalizeUri($path);
$token_query = [
IMAGE_DERIVATIVE_TOKEN => $this
->getPathToken($original_uri),
];
}
if ($clean_urls === NULL) {
$clean_urls = TRUE;
try {
$request = \Drupal::request();
$clean_urls = RequestHelper::isCleanUrl($request);
} catch (ServiceNotFoundException $e) {
}
}
if ($clean_urls === FALSE && $stream_wrapper_manager::getScheme($uri) == 'public' && !file_exists($uri)) {
$directory_path = $stream_wrapper_manager
->getViaUri($uri)
->getDirectoryPath();
return Url::fromUri('base:' . $directory_path . '/' . $stream_wrapper_manager::getTarget($uri), [
'absolute' => TRUE,
'query' => $token_query,
])
->toString();
}
$file_url_generator = \Drupal::service('file_url_generator');
$file_url = $file_url_generator
->generateAbsoluteString($uri);
if ($token_query) {
$file_url .= (str_contains($file_url, '?') ? '&' : '?') . UrlHelper::buildQuery($token_query);
}
return $file_url;
}
public function flush($path = NULL) {
$file_system = \Drupal::service('file_system');
if (isset($path)) {
$derivative_uri = $this
->buildUri($path);
if (file_exists($derivative_uri)) {
try {
$file_system
->delete($derivative_uri);
} catch (FileException $e) {
}
}
}
else {
$wrappers = $this
->getStreamWrapperManager()
->getWrappers(StreamWrapperInterface::WRITE_VISIBLE);
foreach ($wrappers as $wrapper => $wrapper_data) {
if (file_exists($directory = $wrapper . '://styles/' . $this
->id())) {
try {
$file_system
->deleteRecursive($directory);
} catch (FileException $e) {
}
}
}
}
$module_handler = \Drupal::moduleHandler();
$module_handler
->invokeAll('image_style_flush', [
$this,
$path,
]);
if (!isset($path)) {
\Drupal::service('theme.registry')
->reset();
Cache::invalidateTags($this
->getCacheTagsToInvalidate());
}
return $this;
}
public function createDerivative($original_uri, $derivative_uri) {
$image = $this
->getImageFactory()
->get($original_uri);
if (!$image
->isValid()) {
return FALSE;
}
$directory = \Drupal::service('file_system')
->dirname($derivative_uri);
if (!\Drupal::service('file_system')
->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
\Drupal::logger('image')
->error('Failed to create style directory: %directory', [
'%directory' => $directory,
]);
return FALSE;
}
foreach ($this
->getEffects() as $effect) {
$effect
->applyEffect($image);
}
if (!$image
->save($derivative_uri)) {
if (file_exists($derivative_uri)) {
\Drupal::logger('image')
->error('Cached image file %destination already exists. There may be an issue with your rewrite configuration.', [
'%destination' => $derivative_uri,
]);
}
return FALSE;
}
return TRUE;
}
public function transformDimensions(array &$dimensions, $uri) {
foreach ($this
->getEffects() as $effect) {
$effect
->transformDimensions($dimensions, $uri);
}
}
public function getDerivativeExtension($extension) {
foreach ($this
->getEffects() as $effect) {
$extension = $effect
->getDerivativeExtension($extension);
}
return $extension;
}
public function getPathToken($uri) {
return substr(Crypt::hmacBase64($this
->id() . ':' . $this
->addExtension($uri), $this
->getPrivateKey() . $this
->getHashSalt()), 0, 8);
}
public function deleteImageEffect(ImageEffectInterface $effect) {
$this
->getEffects()
->removeInstanceId($effect
->getUuid());
$this
->save();
return $this;
}
public function supportsUri($uri) {
return in_array(mb_strtolower(pathinfo($uri, PATHINFO_EXTENSION)), $this
->getImageFactory()
->getSupportedExtensions());
}
public function getEffect($effect) {
return $this
->getEffects()
->get($effect);
}
public function getEffects() {
if (!$this->effectsCollection) {
$this->effectsCollection = new ImageEffectPluginCollection($this
->getImageEffectPluginManager(), $this->effects);
$this->effectsCollection
->sort();
}
return $this->effectsCollection;
}
public function getPluginCollections() {
return [
'effects' => $this
->getEffects(),
];
}
public function addImageEffect(array $configuration) {
$configuration['uuid'] = $this
->uuidGenerator()
->generate();
$this
->getEffects()
->addInstanceId($configuration['uuid'], $configuration);
return $configuration['uuid'];
}
public function getReplacementID() {
$storage = $this
->entityTypeManager()
->getStorage($this
->getEntityTypeId());
return $storage
->getReplacementId($this
->id());
}
public function getName() {
return $this
->get('name');
}
public function setName($name) {
$this
->set('name', $name);
return $this;
}
protected function getImageEffectPluginManager() {
return \Drupal::service('plugin.manager.image.effect');
}
protected function getImageFactory() {
return \Drupal::service('image.factory');
}
protected function getPrivateKey() {
return \Drupal::service('private_key')
->get();
}
protected function getHashSalt() {
return Settings::getHashSalt();
}
protected function addExtension($path) {
$original_extension = pathinfo($path, PATHINFO_EXTENSION);
$extension = $this
->getDerivativeExtension($original_extension);
if ($original_extension !== $extension) {
$path .= '.' . $extension;
}
return $path;
}
protected function fileDefaultScheme() {
return \Drupal::config('system.file')
->get('default_scheme');
}
protected function getStreamWrapperManager() {
return \Drupal::service('stream_wrapper_manager');
}
}
Classes
Name |
Description |
ImageStyle |
Defines an image style configuration entity. |