-
-
Notifications
You must be signed in to change notification settings - Fork 322
/
Copy pathOneRandomImage.php
41 lines (32 loc) · 1.14 KB
/
OneRandomImage.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
<?php
namespace Frontend\Modules\MediaLibrary\Widgets;
use Backend\Modules\MediaLibrary\Domain\MediaGroupMediaItem\MediaGroupMediaItem;
use Frontend\Modules\MediaLibrary\Widgets\Base\FrontendMediaWidget;
class OneRandomImage extends FrontendMediaWidget
{
public function execute(): void
{
$this->loadData();
// We need to have a MediaGroup to show this widget
if (!$this->mediaGroup) {
return;
}
parent::execute();
$this->loadTemplate();
$this->parse();
}
protected function parse(): void
{
/** @var MediaGroupMediaItem $randomConnectedItem */
$randomConnectedItem = $this->mediaGroup->getConnectedItems()->get(
array_rand($this->mediaGroup->getConnectedItems()->toArray())
);
if ($randomConnectedItem === null) {
return;
}
// Add OpenGraph image
$this->header->addOpenGraphImage($randomConnectedItem->getItem()->getAbsoluteWebPath());
// Assign item (and their source and other custom resolutions)
$this->template->assign('mediaItem', $randomConnectedItem->getItem());
}
}