AutomatedCrop.php in Automated Crop 8
File
modules/automated_crop_crop_provider/src/EventSubscriber/AutomatedCrop.php
View source
<?php
namespace Drupal\automated_crop_crop_provider\EventSubscriber;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\crop\Events\AutomaticCrop;
use Drupal\crop\Events\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class AutomatedCrop implements EventSubscriberInterface {
protected $cropStorage;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->cropStorage = $entity_type_manager
->getStorage('crop');
}
public function generateAutomatedCrop(AutomaticCrop $event) {
if (!$this
->applies($event
->getConfiguration()['automatic_crop_provider'])) {
return;
}
$crop_type = $event
->getCropType();
$image = $event
->getImage();
$hard_limit = $crop_type
->getHardLimit();
$soft_limit = $crop_type
->getSoftLimit();
$configuration = [
'image' => $image,
'min_width' => isset($hard_limit['width']) ? $hard_limit['width'] : $soft_limit['width'],
'min_height' => isset($hard_limit['height']) ? $hard_limit['height'] : $soft_limit['height'],
'aspect_ratio' => !empty($crop_type
->getAspectRatio()) ? $crop_type
->getAspectRatio() : 'NaN',
];
$automated_crop = \Drupal::service('plugin.manager.automated_crop')
->createInstance($event
->getConfiguration()['automatic_crop_provider'], $configuration);
$values = [
'type' => $crop_type
->id(),
'uri' => $image
->getSource(),
'x' => $automated_crop
->anchor()['x'] + $automated_crop
->size()['width'] / 2,
'y' => $automated_crop
->anchor()['y'] + $automated_crop
->size()['height'] / 2,
'width' => $automated_crop
->size()['width'],
'height' => $automated_crop
->size()['height'],
];
$crop = $this->cropStorage
->create($values);
$crop
->save();
$event
->setCrop($crop);
}
private function applies($provider_name) {
return in_array($provider_name, array_keys(\Drupal::service('plugin.manager.automated_crop')
->getProviderOptionsList()));
}
public static function getSubscribedEvents() {
return [
Events::AUTOMATIC_CROP => [
[
'generateAutomatedCrop',
100,
],
],
];
}
}
Classes
Name |
Description |
AutomatedCrop |
A subscriber running automated crop after a crop is needed. |