|
| 1 | +<?php |
| 2 | + |
| 3 | +use Kirby\Cms\Nest; |
| 4 | +use Kirby\Form\OptionsApi; |
| 5 | +use Kirby\Toolkit\Query; |
| 6 | + |
| 7 | +class ImageBoxesOptionsApi extends OptionsApi { |
| 8 | + /** |
| 9 | + * @var string |
| 10 | + */ |
| 11 | + protected $image = '{{ item.image }}'; |
| 12 | + |
| 13 | + /** |
| 14 | + * @return array |
| 15 | + * @throws \Exception |
| 16 | + * @throws \Kirby\Exception\InvalidArgumentException |
| 17 | + */ |
| 18 | + public function options(): array |
| 19 | + { |
| 20 | + if (is_array($this->options) === true) { |
| 21 | + return $this->options; |
| 22 | + } |
| 23 | + |
| 24 | + if (Url::isAbsolute($this->url()) === true) { |
| 25 | + // URL, request via cURL |
| 26 | + $data = Remote::get($this->url())->json(); |
| 27 | + } else { |
| 28 | + // local file, get contents locally |
| 29 | + |
| 30 | + // ensure the file exists before trying to load it as the |
| 31 | + // file_get_contents() warnings need to be suppressed |
| 32 | + if (is_file($this->url()) !== true) { |
| 33 | + throw new Exception('Local file ' . $this->url() . ' was not found'); |
| 34 | + } |
| 35 | + |
| 36 | + $content = @file_get_contents($this->url()); |
| 37 | + |
| 38 | + if (is_string($content) !== true) { |
| 39 | + throw new Exception('Unexpected read error'); // @codeCoverageIgnore |
| 40 | + } |
| 41 | + |
| 42 | + if (empty($content) === true) { |
| 43 | + return []; |
| 44 | + } |
| 45 | + |
| 46 | + $data = json_decode($content, true); |
| 47 | + } |
| 48 | + |
| 49 | + if (is_array($data) === false) { |
| 50 | + throw new InvalidArgumentException('Invalid options format'); |
| 51 | + } |
| 52 | + |
| 53 | + $result = (new Query($this->fetch(), Nest::create($data)))->result(); |
| 54 | + $options = []; |
| 55 | + |
| 56 | + foreach ($result as $item) { |
| 57 | + // dump($item); |
| 58 | + $data = array_merge($this->data(), ['item' => $item]); |
| 59 | + |
| 60 | + $options[] = [ |
| 61 | + 'text' => $this->field('text', $data), |
| 62 | + 'value' => $this->field('value', $data), |
| 63 | + // added this ↓ |
| 64 | + 'image' => $this->field('image', $data), |
| 65 | + ]; |
| 66 | + } |
| 67 | + |
| 68 | + return $options; |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * @param string $text |
| 73 | + * @return $this |
| 74 | + */ |
| 75 | + protected function setImage(?string $image = null) |
| 76 | + { |
| 77 | + $this->image = $image; |
| 78 | + return $this; |
| 79 | + } |
| 80 | + |
| 81 | + /** |
| 82 | + * @return string |
| 83 | + */ |
| 84 | + public function image(): string |
| 85 | + { |
| 86 | + return $this->image; |
| 87 | + } |
| 88 | +} |
0 commit comments