-
Notifications
You must be signed in to change notification settings - Fork 554
/
Image.php
94 lines (75 loc) · 2.5 KB
/
Image.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
namespace A17\Twill\Services\Listings\Columns;
use A17\Twill\Models\Behaviors\HasMedias;
use A17\Twill\Models\Contracts\TwillModelContract;
use A17\Twill\Services\Listings\TableColumn;
use InvalidArgumentException;
class Image extends TableColumn
{
protected ?string $role = null;
protected ?string $crop = null;
protected ?array $mediaParams = null;
protected bool $rounded = false;
public static function make(): static
{
$column = parent::make();
$column->specificType = 'thumbnail';
$column->shrink();
return $column;
}
/**
* The image role that is defined in your model. Can be left out as it will take the first one available.
*/
public function role(?string $role): static
{
$this->role = $role;
return $this;
}
/**
* A specific crop to use for the image. Can be left out as it will take the first one available.
*/
public function crop(?string $crop): static
{
$this->crop = $crop;
return $this;
}
/**
* Optional array of media parameters for more control over the rendering.
*/
public function mediaParams(array $params): static
{
$this->mediaParams = $params;
return $this;
}
/**
* If enabled the image will be rounded instead of square.
*/
public function rounded(bool $rounded = true): static
{
$this->rounded = $rounded;
return $this;
}
public function toColumnArray(array $visibleColumns = [], bool $sortable = true): array
{
$data = parent::toColumnArray($visibleColumns, $sortable);
$data['variation'] = $this->rounded ? 'rounded' : 'square';
return $data;
}
protected function getRenderValue(TwillModelContract $model): string
{
if ($renderFunction = $this->render) {
return $renderFunction($model);
}
if (!classHasTrait($model::class, HasMedias::class)) {
throw new InvalidArgumentException('Cannot use image column on model not implementing HasMedias trait');
}
return $this->getThumbnail($model);
}
public function getThumbnail(TwillModelContract $model): ?string
{
$role = $this->role ?? head(array_keys($model->getMediasParams()));
$crop = $this->crop ?? head(array_keys($model->getMediasParams()[$role]));
$params = $this->mediaParams ?? ['w' => 80, 'h' => 80, 'fit' => 'crop'];
return $model->cmsImage($role, $crop, $params);
}
}