1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Cache\Messenger;
13
14use Symfony\Component\Cache\Adapter\AdapterInterface;
15use Symfony\Component\Cache\CacheItem;
16use Symfony\Component\DependencyInjection\ReverseContainer;
17
18/**
19 * Conveys a cached value that needs to be computed.
20 */
21final class EarlyExpirationMessage
22{
23    private $item;
24    private $pool;
25    private $callback;
26
27    public static function create(ReverseContainer $reverseContainer, callable $callback, CacheItem $item, AdapterInterface $pool): ?self
28    {
29        try {
30            $item = clone $item;
31            $item->set(null);
32        } catch (\Exception $e) {
33            return null;
34        }
35
36        $pool = $reverseContainer->getId($pool);
37
38        if (\is_object($callback)) {
39            if (null === $id = $reverseContainer->getId($callback)) {
40                return null;
41            }
42
43            $callback = '@'.$id;
44        } elseif (!\is_array($callback)) {
45            $callback = (string) $callback;
46        } elseif (!\is_object($callback[0])) {
47            $callback = [(string) $callback[0], (string) $callback[1]];
48        } else {
49            if (null === $id = $reverseContainer->getId($callback[0])) {
50                return null;
51            }
52
53            $callback = ['@'.$id, (string) $callback[1]];
54        }
55
56        return new self($item, $pool, $callback);
57    }
58
59    public function getItem(): CacheItem
60    {
61        return $this->item;
62    }
63
64    public function getPool(): string
65    {
66        return $this->pool;
67    }
68
69    public function getCallback()
70    {
71        return $this->callback;
72    }
73
74    public function findPool(ReverseContainer $reverseContainer): AdapterInterface
75    {
76        return $reverseContainer->getService($this->pool);
77    }
78
79    public function findCallback(ReverseContainer $reverseContainer): callable
80    {
81        if (\is_string($callback = $this->callback)) {
82            return '@' === $callback[0] ? $reverseContainer->getService(substr($callback, 1)) : $callback;
83        }
84        if ('@' === $callback[0][0]) {
85            $callback[0] = $reverseContainer->getService(substr($callback[0], 1));
86        }
87
88        return $callback;
89    }
90
91    private function __construct(CacheItem $item, string $pool, $callback)
92    {
93        $this->item = $item;
94        $this->pool = $pool;
95        $this->callback = $callback;
96    }
97}
98