Created
November 19, 2020 19:07
-
-
Save tarlepp/b3bd164dc988ea515b01b9ebf68c9f02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types = 1); | |
namespace App\Service; | |
use App\Utils\JSON; | |
use Closure; | |
use Psr\Log\LoggerInterface; | |
use stdClass; | |
use Symfony\Contracts\Cache\CacheInterface; | |
use Symfony\Contracts\Cache\ItemInterface; | |
use Throwable; | |
class Version | |
{ | |
private string $projectDir; | |
private CacheInterface $cache; | |
private LoggerInterface $logger; | |
public function __construct(string $projectDir, CacheInterface $appCacheApcu, LoggerInterface $logger) | |
{ | |
$this->projectDir = $projectDir; | |
$this->cache = $appCacheApcu; | |
$this->logger = $logger; | |
} | |
public function get(): string | |
{ | |
$output = '0.0.0'; | |
try { | |
/** @noinspection PhpUnhandledExceptionInspection */ | |
$output = $this->cache->get('application_version', $this->getClosure()); | |
} catch (Throwable $exception) { | |
$this->logger->error($exception->getMessage(), $exception->getTrace()); | |
} | |
return $output; | |
} | |
private function getClosure(): Closure | |
{ | |
return function (ItemInterface $item): string { | |
// One year | |
$item->expiresAfter(31536000); | |
/** @var stdClass $composerData */ | |
$composerData = JSON::decode((string)file_get_contents($this->projectDir . '/composer.json')); | |
return (string)($composerData->version ?? '0.0.0'); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment