generated from spatie/package-skeleton-php
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScaleCrop.php
80 lines (65 loc) · 2.7 KB
/
ScaleCrop.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace Vormkracht10\UploadcareTransformations\Transformations;
use Vormkracht10\UploadcareTransformations\Traits\Validations;
use Vormkracht10\UploadcareTransformations\Transformations\Enums\Offset;
use Vormkracht10\UploadcareTransformations\Transformations\Interfaces\TransformationInterface;
class ScaleCrop implements TransformationInterface
{
use Validations;
final public const WIDTH = 'width';
final public const HEIGHT = 'height';
final public const OFFSET_X = 'offset_x';
final public const OFFSET_Y = 'offset_y';
final public const ALIGN = 'align';
public static function transform(...$args): array
{
$width = $args[0];
$height = $args[1];
$offsetX = $args[2] ?? null;
$offsetY = $args[3] ?? null;
if ($offsetX && ! self::validate('offset_x', $offsetX)) {
throw new \InvalidArgumentException('Invalid offset X');
}
if ($offsetY && ! self::validate('offset_y', $offsetY)) {
throw new \InvalidArgumentException('Invalid offset Y');
}
if (! $offsetY) {
return [
self::WIDTH => $width,
self::HEIGHT => $height,
self::ALIGN => $offsetX,
];
}
return [
self::WIDTH => $width,
self::HEIGHT => $height,
self::OFFSET_X => $offsetX,
self::OFFSET_Y => $offsetY,
];
}
public static function validate(string $key, ...$args): bool
{
$value = $args[0];
if ($key === self::OFFSET_X) {
return Offset::tryFrom($value) || self::isValidPercentage($value);
}
if ($key === self::OFFSET_Y) {
return self::isValidPercentage($value);
}
return false;
}
public static function generateUrl(string $url, array $values): string
{
if (! isset($values['offset_x']) && ! isset($values['offset_y']) && ! isset($values['align'])) {
// -/scale_crop/:dimensions/
$url .= '-/scale_crop/' . $values['width'] . 'x' . $values['height'] . '/';
} elseif (isset($values['width']) && isset($values['height']) && isset($values['align'])) {
// -/scale_crop/:dimensions/:alignment/
$url .= '-/scale_crop/' . $values['width'] . 'x' . $values['height'] . '/' . $values['align'] . '/';
} elseif (isset($values['width']) && isset($values['height']) && isset($values['offset_x']) && isset($values['offset_y'])) {
// -/scale_crop/:dimensions/:alignment/
$url .= '-/scale_crop/' . $values['width'] . 'x' . $values['height'] . '/' . $values['offset_x'] . ',' . $values['offset_y'] . '/';
}
return $url;
}
}