Skip to content

Instantly share code, notes, and snippets.

@sroehrl
Created August 17, 2022 18:54
Show Gist options
  • Save sroehrl/56d4ae1330461acff6b826ca88f8960d to your computer and use it in GitHub Desktop.
Save sroehrl/56d4ae1330461acff6b826ca88f8960d to your computer and use it in GitHub Desktop.
Source files for https://youtu.be/bDjd0EsuTV4
<?php
namespace App\Transformers;
use Josantonius\Session\Facades\Session;
use Neoan\Enums\Direction;
use Neoan\Model\Interfaces\Transformation;
class AttachUser implements Transformation
{
public function __invoke(array $inputOutput, Direction $direction, string $property): array
{
if($direction == Direction::IN && !isset($inputOutput[$property]) && Session::has('userId')){
$inputOutput[$property] = Session::get('userId');
}
return $inputOutput;
}
}
<?php
namespace App\Model;
use App\Transformers\AttachUser;
use App\Transformers\Slug;
use Neoan\Model\Attributes\IsPrimaryKey;
use Neoan\Model\Attributes\IsUnique;
use Neoan\Model\Attributes\Transform;
use Neoan\Model\Attributes\Type;
use Neoan\Model\Model;
use Neoan\Model\Traits\TimeStamps;
class BlogEntry extends Model
{
#[IsPrimaryKey]
public int $id;
#[Transform(AttachUser::class)]
public int $userId;
#[IsUnique, Transform(Slug::class)]
public string $slug;
public string $title;
#[Type('Text')]
public ?string $content;
use TimeStamps;
}
<?php
namespace App\Controller\Blog;
use App\Model\BlogEntry;
use Neoan\Request\Request;
use Neoan\Routing\Routable;
class CreateBlog implements Routable
{
public function __invoke(array $provided): BlogEntry|array
{
$blog = new BlogEntry(Request::getInputs());
try{
$blog->store();
} catch (\Exception $e){
return ['error' => $e->getMessage()];
}
return $blog;
}
}
<?php
namespace App\Controller\Blog;
use App\Model\BlogEntry;
use Neoan\Errors\NotFound;
use Neoan\Request\Request;
use Neoan\Routing\Routable;
use League\CommonMark\CommonMarkConverter;
class ReadBlog implements Routable
{
public function __invoke(array $provided): array
{
$slug = Request::getParameter('slug');
$blog = BlogEntry::retrieveOne(['slug' => $slug, 'deletedAt' => null]);
if(!$blog){
new NotFound('/blog/' . $slug);
}
$converter = new CommonMarkConverter();
return [
'blog' => $blog,
'converted' =>$converter->convert($blog->content)
];
}
}
<?php
namespace App\Transformers;
use Neoan\Enums\Direction;
use Neoan\Model\Interfaces\Transformation;
class Slug implements Transformation
{
function __construct()
{
}
function __invoke(array $context, Direction $direction, string $property): array
{
if($direction == Direction::IN && !isset($context[$property])){
$context[$property] = preg_replace('/[^a-z0-9]/i','-',$context['title']);
}
return $context;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment