1 | <?php |
||
2 | declare(strict_types = 1); |
||
3 | /** |
||
4 | * /src/Service/Version.php |
||
5 | * |
||
6 | * @author TLe, Tarmo Leppänen <[email protected]> |
||
7 | */ |
||
8 | |||
9 | namespace App\Service; |
||
10 | |||
11 | use App\Utils\JSON; |
||
12 | use Closure; |
||
13 | use Psr\Log\LoggerInterface; |
||
14 | use Symfony\Component\DependencyInjection\Attribute\Autowire; |
||
15 | use Symfony\Contracts\Cache\CacheInterface; |
||
16 | use Symfony\Contracts\Cache\ItemInterface; |
||
17 | use Throwable; |
||
18 | use function array_key_exists; |
||
19 | use function assert; |
||
20 | use function is_array; |
||
21 | use function is_string; |
||
22 | |||
23 | /** |
||
24 | * Class Version |
||
25 | * |
||
26 | * @package App\Service |
||
27 | * @author TLe, Tarmo Leppänen <[email protected]> |
||
28 | */ |
||
29 | class Version |
||
30 | { |
||
31 | 598 | public function __construct( |
|
32 | #[Autowire('%kernel.project_dir%')] |
||
33 | private readonly string $projectDir, |
||
34 | private readonly CacheInterface $appCacheApcu, |
||
35 | private readonly LoggerInterface $logger |
||
36 | ) { |
||
37 | 598 | } |
|
38 | |||
39 | /** |
||
40 | * Method to get application version from cache or create new entry to |
||
41 | * cache with version value from composer.json file. |
||
42 | */ |
||
43 | 598 | public function get(): string |
|
44 | { |
||
45 | 598 | $output = '0.0.0'; |
|
46 | |||
47 | try { |
||
48 | 598 | $output = (string)$this->appCacheApcu->get('application_version', $this->getClosure()); |
|
49 | 1 | } catch (Throwable $exception) { |
|
50 | 1 | $this->logger->error($exception->getMessage(), $exception->getTrace()); |
|
51 | } |
||
52 | |||
53 | 598 | return $output; |
|
54 | } |
||
55 | |||
56 | 598 | private function getClosure(): Closure |
|
57 | { |
||
58 | 598 | return function (ItemInterface $item): string { |
|
59 | // One year |
||
60 | 596 | $item->expiresAfter(31_536_000); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
61 | |||
62 | 596 | $composerData = JSON::decode((string)file_get_contents($this->projectDir . '/composer.json'), true); |
|
63 | |||
64 | assert(is_array($composerData)); |
||
65 | |||
66 | 596 | return array_key_exists('version', $composerData) && is_string($composerData['version']) |
|
67 | 596 | ? $composerData['version'] |
|
68 | 596 | : '0.0.0'; |
|
69 | 598 | }; |
|
70 | } |
||
71 | } |
||
72 |