Skip to content

Instantly share code, notes, and snippets.

@tarlepp
Created November 19, 2020 19:07
Show Gist options
  • Save tarlepp/b3bd164dc988ea515b01b9ebf68c9f02 to your computer and use it in GitHub Desktop.
Save tarlepp/b3bd164dc988ea515b01b9ebf68c9f02 to your computer and use it in GitHub Desktop.
<?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