First fully working version of saving snips content with git control

This commit is contained in:
Tim
2023-04-04 23:23:53 +02:00
parent 1a7c9bb25a
commit 842c936d8c
12 changed files with 170 additions and 17 deletions

View File

@ -0,0 +1,55 @@
<?php
namespace App\Service;
use App\Entity\Snip;
use App\Entity\User;
use CzProject\GitPhp\Git;
use CzProject\GitPhp\GitRepository;
class SnipService
{
private GitRepository $repo;
public function __construct(
Snip $snip,
string $snipBasePath,
private readonly User $user,
)
{
$git = new Git();
$repoPath = sprintf('%s/%s', $snipBasePath, $snip->getId());
if (!is_dir($repoPath)) {
$this->repo = $git->init($repoPath);
} else {
$this->repo = $git->open($repoPath);
}
}
private function snipExists(): bool
{
return file_exists($this->getSnipPath());
}
private function getSnipPath(): string
{
return sprintf('%s/snip.txt', $this->repo->getRepositoryPath());
}
public function update(string $snipContents): void
{
file_put_contents($this->getSnipPath(), $snipContents);
$this->repo->addFile('snip.txt');
if ($this->repo->hasChanges()) {
$this->repo->commit(sprintf('Updated snip at %s by %s', date('Y-m-d H:i:s'), $this->user));
}
}
public function get(): string
{
if (!$this->snipExists()) {
return '';
}
return file_get_contents($this->getSnipPath());
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Service;
use App\Entity\Snip;
use Symfony\Bundle\SecurityBundle\Security;
class SnipServiceFactory
{
public function __construct(
private readonly string $snipBasePath,
private readonly Security $security,
)
{
}
public function create(Snip $snip): SnipService
{
return new SnipService($snip, $this->snipBasePath, $this->security->getUser());
}
}