1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Shopware\Storefront\Theme\Subscriber; |
4
|
|
|
|
5
|
|
|
use Shopware\Core\Content\Media\Event\UnusedMediaSearchEvent; |
6
|
|
|
use Shopware\Core\Framework\Context; |
7
|
|
|
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository; |
8
|
|
|
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria; |
9
|
|
|
use Shopware\Core\Framework\Log\Package; |
10
|
|
|
use Shopware\Core\Framework\Uuid\Uuid; |
11
|
|
|
use Shopware\Storefront\Theme\ThemeService; |
12
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @internal |
16
|
|
|
*/ |
17
|
|
|
#[Package('storefront')] |
18
|
|
|
class UnusedMediaSubscriber implements EventSubscriberInterface |
19
|
|
|
{ |
20
|
|
|
public function __construct( |
21
|
|
|
private readonly EntityRepository $themeRepository, |
22
|
|
|
private readonly ThemeService $themeService |
23
|
|
|
) { |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public static function getSubscribedEvents(): array |
27
|
|
|
{ |
28
|
|
|
return [ |
29
|
|
|
UnusedMediaSearchEvent::class => 'removeUsedMedia', |
30
|
|
|
]; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function removeUsedMedia(UnusedMediaSearchEvent $event): void |
34
|
|
|
{ |
35
|
|
|
$context = Context::createDefaultContext(); |
36
|
|
|
/** @var array<string> $allThemeIds */ |
37
|
|
|
$allThemeIds = $this->themeRepository->searchIds(new Criteria(), $context)->getIds(); |
38
|
|
|
|
39
|
|
|
$mediaIds = []; |
40
|
|
|
foreach ($allThemeIds as $themeId) { |
41
|
|
|
$config = $this->themeService->getThemeConfiguration($themeId, false, $context); |
42
|
|
|
|
43
|
|
|
foreach ($config['fields'] ?? [] as $data) { |
44
|
|
|
if ($data['type'] === 'media' && $data['value'] && Uuid::isValid($data['value'])) { |
45
|
|
|
$mediaIds[] = $data['value']; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$event->markAsUsed(array_unique($mediaIds)); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|