View source
<?php
namespace Drupal\focal_point;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\crop\CropInterface;
use Drupal\crop\Entity\Crop;
use Drupal\file\FileInterface;
class FocalPointManager implements FocalPointManagerInterface {
const FOCAL_POINT_VALIDATION_REGEXP = '/^(100|[0-9]{1,2})(,)(100|[0-9]{1,2})$/';
protected $cropStorage;
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->cropStorage = $entity_type_manager
->getStorage('crop');
}
public function validateFocalPoint($focal_point) {
return (bool) preg_match(static::FOCAL_POINT_VALIDATION_REGEXP, $focal_point);
}
public function relativeToAbsolute($x, $y, $width, $height) {
return [
'x' => (int) round($x / 100.0 * $width),
'y' => (int) round($y / 100.0 * $height),
];
}
public function absoluteToRelative($x, $y, $width, $height) {
return [
'x' => $width ? (int) round($x / $width * 100) : 0,
'y' => $height ? (int) round($y / $height * 100) : 0,
];
}
public function getCropEntity(FileInterface $file, $crop_type) {
if (Crop::cropExists($file
->getFileUri(), $crop_type)) {
$crop = Crop::findCrop($file
->getFileUri(), $crop_type);
}
else {
$values = [
'type' => $crop_type,
'entity_id' => $file
->id(),
'entity_type' => 'file',
'uri' => $file
->getFileUri(),
];
$crop = $this->cropStorage
->create($values);
}
return $crop;
}
public function saveCropEntity($x, $y, $width, $height, CropInterface $crop) {
$absolute = $this
->relativeToAbsolute($x, $y, $width, $height);
$anchor = $crop
->anchor();
if ($anchor['x'] != $absolute['x'] || $anchor['y'] != $absolute['y']) {
$crop
->setPosition($absolute['x'], $absolute['y']);
$crop
->save();
}
return $crop;
}
}