zend-blog-3-backend
115 строк · 2.4 Кб
1<?php
2
3namespace App\Model;
4
5use App\Service\ImageManager;
6
7class SrcSet
8{
9private ?SrcSetItem $origin = null;
10private ?SrcSetItem $webp = null;
11private ?SrcSetItem $avif = null;
12
13/**
14* @return SrcSetItem|null
15*/
16public function getOrigin(): ?SrcSetItem
17{
18return $this->origin;
19}
20
21/**
22* @param array $items
23*
24* @return SrcSet
25*/
26public function setOrigin(array $items): SrcSet
27{
28$this->origin = new SrcSetItem($items);
29
30return $this;
31}
32
33/**
34* @return SrcSetItem|null
35*/
36public function getWebp(): ?SrcSetItem
37{
38return $this->webp;
39}
40
41/**
42* @param array $items
43*
44* @return SrcSet
45*/
46public function setWebp(array $items): SrcSet
47{
48$this->webp = new SrcSetItem($items);
49if ($this->origin && !$this->isSizeSmaller($items)) {
50$this->webp = null;
51}
52
53return $this;
54}
55
56/**
57* @return SrcSetItem|null
58*/
59public function getAvif(): ?SrcSetItem
60{
61return $this->avif;
62}
63
64/**
65* @param array $items
66*
67* @return SrcSet
68*/
69public function setAvif(array $items): SrcSet
70{
71$this->avif = new SrcSetItem($items);
72if ($this->origin && !$this->isSizeSmaller($items)) {
73$this->avif = null;
74}
75
76return $this;
77}
78
79public function isSizeSmaller(array $items)
80{
81if (!$this->origin) {
82return true;
83}
84
85$firstItemSize = 0;
86foreach ($items as $item) {
87$firstItemSize = filesize(ImageManager::getUploadsDir() . '/' . $item['path']);
88break;
89}
90
91$originItemSize = 0;
92foreach ($this->origin->getItems() as $item) {
93$originItemSize = filesize(ImageManager::getUploadsDir() . '/' . $item['path']);
94break;
95}
96
97return $firstItemSize < $originItemSize;
98}
99
100public function toArray(): array
101{
102$data = [];
103if ($this->origin && count($this->origin->getItems())) {
104$data['origin'] = $this->origin->toArray();
105}
106if ($this->avif && count($this->avif->getItems())) {
107$data['avif'] = $this->avif->toArray();
108}
109if ($this->webp && count($this->webp->getItems())) {
110$data['webp'] = $this->webp->toArray();
111}
112
113return $data;
114}
115}
116