Skip to content

Commit

Permalink
139 resolve actions via service container (#141)
Browse files Browse the repository at this point in the history
  • Loading branch information
benbjurstrom authored Jan 26, 2025
1 parent 23d4842 commit 4ff9692
Show file tree
Hide file tree
Showing 36 changed files with 357 additions and 189 deletions.
2 changes: 1 addition & 1 deletion phpstan-baseline.neon
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
parameters:
ignoreErrors:
-
message: "#^Parameter \\#1 \\$currentSlugs of static method BenBjurstrom\\\\Prezet\\\\Actions\\\\UpdateIndex\\:\\:removeDeletedDocuments\\(\\) expects array\\<int, string\\>, array given\\.$#"
message: "#^Parameter \\#1 \\$currentSlugs of method BenBjurstrom\\\\Prezet\\\\Actions\\\\UpdateIndex\\:\\:removeDeletedDocuments\\(\\) expects array\\<int, string\\>, array given\\.$#"
count: 1
path: src/Actions/UpdateIndex.php
10 changes: 5 additions & 5 deletions src/Actions/CreateIndex.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

class CreateIndex
{
public static function handle(): void
public function handle(): void
{
$originalPath = Config::string('database.connections.prezet.database');
$tempPath = sys_get_temp_dir().'/prezet_'.uniqid().'.sqlite';
Expand All @@ -22,8 +22,8 @@ public static function handle(): void
Config::set('database.connections.prezet.database', $tempPath);
DB::purge('prezet');

self::runMigrations($tempPath);
self::ensureDirectoryExists($originalPath);
$this->runMigrations($tempPath);
$this->ensureDirectoryExists($originalPath);

if (! rename($tempPath, $originalPath)) {
throw new \RuntimeException("Failed to move database from {$tempPath} to {$originalPath}");
Expand All @@ -48,7 +48,7 @@ public static function handle(): void
}
}

protected static function ensureDirectoryExists(string $path): void
protected function ensureDirectoryExists(string $path): void
{
$dir = dirname($path);
if (! is_dir($dir)) {
Expand All @@ -58,7 +58,7 @@ protected static function ensureDirectoryExists(string $path): void
}
}

protected static function runMigrations(string $path): void
protected function runMigrations(string $path): void
{
if (! Schema::connection('prezet')->hasTable('migrations')) {
Schema::connection('prezet')->create('migrations', function ($table) {
Expand Down
8 changes: 4 additions & 4 deletions src/Actions/GenerateOgImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

namespace BenBjurstrom\Prezet\Actions;

use BenBjurstrom\Prezet\Prezet;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\Browsershot\Browsershot as SpatieBrowsershot;

class GenerateOgImage
{
public static function handle(string $mdPath): string
public function handle(string $mdPath): string
{

$url = route('prezet.ogimage', ['slug' => $mdPath]);

$screenshot = SpatieBrowsershot::url($url)
Expand All @@ -21,10 +21,10 @@ public static function handle(string $mdPath): string

$filename = Str::slug(str_replace('/', '-', $mdPath)).'.webp';
$filepath = 'images/ogimages/'.$filename;
Storage::disk(GetPrezetDisk::handle())->put($filepath, $screenshot);
Storage::disk(Prezet::getPrezetDisk())->put($filepath, $screenshot);

$imageUrl = route('prezet.image', 'ogimages/'.$filename, false);
SetOgImage::handle($mdPath, $imageUrl);
Prezet::setOgImage($mdPath, $imageUrl);

return $imageUrl;
}
Expand Down
9 changes: 5 additions & 4 deletions src/Actions/GetAllDocsFromFiles.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace BenBjurstrom\Prezet\Actions;

use BenBjurstrom\Prezet\Data\DocumentData;
use BenBjurstrom\Prezet\Prezet;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;

Expand All @@ -11,17 +12,17 @@ class GetAllDocsFromFiles
/**
* @return Collection<int,DocumentData>
*/
public static function handle(): Collection
public function handle(): Collection
{
$files = collect(Storage::disk(GetPrezetDisk::handle())
->allFiles('content'));
$disk = Prezet::getPrezetDisk();
$files = collect(Storage::disk($disk)->allFiles('content'));

return $files
->filter(function ($filePath) {
return pathinfo($filePath, PATHINFO_EXTENSION) === 'md';
})
->map(function ($filePath) {
return GetDocFromFile::handle($filePath);
return Prezet::getDocFromFile($filePath);
})
->sortByDesc('createdAt');
}
Expand Down
30 changes: 19 additions & 11 deletions src/Actions/GetDocFromFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,46 @@
use BenBjurstrom\Prezet\Exceptions\InvalidConfigurationException;
use BenBjurstrom\Prezet\Exceptions\MissingConfigurationException;
use BenBjurstrom\Prezet\Models\Document;
use BenBjurstrom\Prezet\Prezet;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Storage;

class GetDocFromFile
{
private Filesystem $storage;

public function __construct()
{
$this->storage = Storage::disk(Prezet::getPrezetDisk());
}

/**
* @throws FrontmatterMissingException
* @throws InvalidConfigurationException
* @throws FileNotFoundException
* @throws MissingConfigurationException
*/
public static function handle(string $filePath): DocumentData
public function handle(string $filePath): DocumentData
{
$docClass = self::getDocumentDataClass();
$storage = Storage::disk(GetPrezetDisk::handle());
$content = self::getFileContent($filePath, $storage);
$docClass = $this->getDocumentDataClass();
$content = $this->getFileContent($filePath);

$hash = md5($content);
$slug = self::getSlug($filePath);
$slug = $this->getSlug($filePath);
$doc = Document::query()->where([
'hash' => $hash,
'slug' => $slug,
])->first();

if ($doc) {
$docData = $docClass::fromModel($doc);
$docData->content = $content;

return $docData;
}

$fm = ParseFrontmatter::handle($content, $filePath);
$fm = Prezet::parseFrontmatter($content, $filePath);

return $docClass::fromArray([
'slug' => $slug,
Expand All @@ -48,22 +56,22 @@ public static function handle(string $filePath): DocumentData
'content' => $content,
'category' => $fm->category,
'frontmatter' => $fm,
'updatedAt' => $storage->lastModified($filePath),
'updatedAt' => $this->storage->lastModified($filePath),
'createdAt' => $fm->date,
]);
}

protected static function getSlug(string $filePath): string
protected function getSlug(string $filePath): string
{
$relativePath = trim(str_replace('content', '', $filePath), '/');
$slug = pathinfo($relativePath, PATHINFO_DIRNAME).'/'.pathinfo($relativePath, PATHINFO_FILENAME);

return trim($slug, './');
}

protected static function getFileContent(string $filePath, Filesystem $storage): string
protected function getFileContent(string $filePath): string
{
$content = $storage->get($filePath);
$content = $this->storage->get($filePath);
if (! $content) {
throw new FileNotFoundException($filePath);
}
Expand All @@ -74,7 +82,7 @@ protected static function getFileContent(string $filePath, Filesystem $storage):
/**
* @throws InvalidConfigurationException
*/
protected static function getDocumentDataClass(): string
protected function getDocumentDataClass(): string
{
$key = 'prezet.data.document';
$fmClass = Config::string($key);
Expand Down
10 changes: 5 additions & 5 deletions src/Actions/GetFlatHeadings.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,19 @@ class GetFlatHeadings
/**
* @return array<int, array<string, int|string>>
*/
public static function handle(string $html): array
public function handle(string $html): array
{
$dom = new DOMDocument;
$html = '<?xml encoding="UTF-8"><div>'.$html.'</div>'; // Wrapper to handle h2 as first element
@$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

return self::extractHeadings($dom);
return $this->extractHeadings($dom);
}

/**
* @return array<int, array<string, string|int>>
*/
private static function extractHeadings(DOMDocument $dom): array
private function extractHeadings(DOMDocument $dom): array
{
$xpath = new DOMXPath($dom);
$headingElements = $xpath->query('//h2 | //h3');
Expand All @@ -39,7 +39,7 @@ private static function extractHeadings(DOMDocument $dom): array
continue;
}

$headingText = self::cleanHeadingText($headingElement->textContent);
$headingText = $this->cleanHeadingText($headingElement->textContent);

$headingLevel = (int) substr(strtolower($headingElement->tagName), 1);
if ($headingLevel === 2) {
Expand All @@ -56,7 +56,7 @@ private static function extractHeadings(DOMDocument $dom): array
return $headings;
}

private static function cleanHeadingText(string $text): string
private function cleanHeadingText(string $text): string
{
return trim((string) preg_replace('/^\s*#*\s*|\s*#*\s*$/', '', $text));
}
Expand Down
10 changes: 5 additions & 5 deletions src/Actions/GetHeadings.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,19 @@ class GetHeadings
/**
* @return array<int, array<string, array<int, array<string, string>>|string>>
*/
public static function handle(string $html): array
public function handle(string $html): array
{
$html = '<?xml encoding="UTF-8">'.$html;
$dom = new DOMDocument;
@$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

return self::extractHeadings($dom);
return $this->extractHeadings($dom);
}

/**
* @return array<int, array<string, array<int, array<string, string>>|string>>
*/
private static function extractHeadings(DOMDocument $dom): array
private function extractHeadings(DOMDocument $dom): array
{
$xpath = new DOMXPath($dom);
$h2Elements = $xpath->query('//h2');
Expand All @@ -36,7 +36,7 @@ private static function extractHeadings(DOMDocument $dom): array
}

foreach ($h2Elements as $h2Element) {
$children = self::extractChildHeadings($h2Element, 'h3');
$children = $this->extractChildHeadings($h2Element, 'h3');

$result[] = [
'id' => 'content-'.Str::slug($h2Element->textContent, language: null),
Expand All @@ -51,7 +51,7 @@ private static function extractHeadings(DOMDocument $dom): array
/**
* @return array<int, array<string, string>>
*/
private static function extractChildHeadings(DOMNode $parentElement, string $childTagName): array
private function extractChildHeadings(DOMNode $parentElement, string $childTagName): array
{
$nextSibling = $parentElement->nextSibling;
$children = [];
Expand Down
29 changes: 15 additions & 14 deletions src/Actions/GetImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,30 @@
namespace BenBjurstrom\Prezet\Actions;

use BenBjurstrom\Prezet\Exceptions\InvalidConfigurationException;
use BenBjurstrom\Prezet\Prezet;
use GdImage;
use Illuminate\Support\Facades\Storage;

class GetImage
{
public static function handle(string $path): string
public function handle(string $path): string
{
$extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
self::validateFileExtension($extension);
$this->validateFileExtension($extension);

$size = self::extractSize($path);
$path = self::removeSize($path);
$size = $this->extractSize($path);
$path = $this->removeSize($path);

$image = self::loadImage($path);
$image = $this->loadImage($path);

if (isset($size)) {
$image = self::resizeImage($image, $size);
$image = $this->resizeImage($image, $size);
}

return self::outputImage($image, $extension);
return $this->outputImage($image, $extension);
}

protected static function validateFileExtension(string $extension): void
protected function validateFileExtension(string $extension): void
{
$allowedExtensions = ['png', 'jpg', 'jpeg', 'webp'];

Expand All @@ -34,9 +35,9 @@ protected static function validateFileExtension(string $extension): void
}
}

protected static function loadImage(string $path): GdImage
protected function loadImage(string $path): GdImage
{
$imageStr = Storage::disk(GetPrezetDisk::handle())->get('images/'.$path);
$imageStr = Storage::disk(Prezet::getPrezetDisk())->get('images/'.$path);
if (! $imageStr) {
abort(404);
}
Expand All @@ -49,7 +50,7 @@ protected static function loadImage(string $path): GdImage
return $image;
}

private static function extractSize(string $path): ?int
private function extractSize(string $path): ?int
{
$allowedWidths = config('prezet.image.widths');
if (! is_array($allowedWidths)) {
Expand All @@ -65,7 +66,7 @@ private static function extractSize(string $path): ?int
return null;
}

private static function removeSize(string $path): string
private function removeSize(string $path): string
{
$pattern = '/(.+)-(\d+)w\.(\w+)$/';

Expand All @@ -78,7 +79,7 @@ private static function removeSize(string $path): string
return $result;
}

private static function resizeImage(GdImage $image, int $size): GdImage
private function resizeImage(GdImage $image, int $size): GdImage
{
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
Expand All @@ -91,7 +92,7 @@ private static function resizeImage(GdImage $image, int $size): GdImage
return $resizedImage;
}

private static function outputImage(GdImage $image, string $extension): string
private function outputImage(GdImage $image, string $extension): string
{
ob_start();
switch ($extension) {
Expand Down
10 changes: 5 additions & 5 deletions src/Actions/GetLinkedData.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ class GetLinkedData
/**
* @return array<string, string|array<string, string>>
*/
public static function handle(DocumentData $document): array
public function handle(DocumentData $document): array
{
$fm = $document->frontmatter;
$author = self::getAuthor($fm);
$image = self::getImage($fm);
$author = $this->getAuthor($fm);
$image = $this->getImage($fm);
$publisher = Config::array('prezet.publisher');

return [
Expand All @@ -33,7 +33,7 @@ public static function handle(DocumentData $document): array
/**
* @return array<string, string>
*/
private static function getAuthor(FrontmatterData $fm): array
private function getAuthor(FrontmatterData $fm): array
{
$authors = Config::array('prezet.authors');

Expand All @@ -46,7 +46,7 @@ private static function getAuthor(FrontmatterData $fm): array
return reset($authors);
}

private static function getImage(FrontmatterData $fm): string
private function getImage(FrontmatterData $fm): string
{
$publisher = Config::array('prezet.publisher');

Expand Down
Loading

0 comments on commit 4ff9692

Please sign in to comment.