This commit is contained in:
lubiana 2022-04-14 07:48:16 +02:00 committed by Andre Lubian
parent ececd7dcb5
commit 00c31259f8
595 changed files with 0 additions and 49207 deletions

View file

View file

@ -1,31 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Action;
use Lubian\NoFramework\Service\Time\Now;
use Lubian\NoFramework\Template\Renderer;
use Psr\Http\Message\ResponseInterface;
final class Hello
{
public function __invoke(
ResponseInterface $response,
Now $now,
Renderer $renderer,
string $name = 'Stranger',
): ResponseInterface {
$body = $response->getBody();
$data = [
'now' => $now()->format('H:i:s'),
'name' => $name,
];
$content = $renderer->render('hello', $data);
$body->write($content);
return $response
->withStatus(200)
->withBody($body);
}
}

View file

@ -1,16 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Action;
use Lubian\NoFramework\Template\MarkdownParser;
use Psr\Http\Message\ResponseInterface;
final class Other
{
public function someFunctionName(ResponseInterface $response, MarkdownParser $parser): ResponseInterface
{
$html = $parser->parse('This *works* **too!**');
$response->getBody()->write($html);
return $response->withStatus(200);
}
}

View file

@ -1,60 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Action;
use Lubian\NoFramework\Model\MarkdownPage;
use Lubian\NoFramework\Repository\MarkdownPageRepo;
use Lubian\NoFramework\Template\MarkdownParser;
use Lubian\NoFramework\Template\Renderer;
use Psr\Http\Message\ResponseInterface;
use function array_map;
use function assert;
use function is_string;
use function preg_replace;
use function str_replace;
class Page
{
public function __construct(
private ResponseInterface $response,
private MarkdownParser $parser,
private Renderer $renderer,
private MarkdownPageRepo $repo,
) {
}
public function show(
string $page,
): ResponseInterface {
$page = $this->repo->byName($page);
// fix the next and previous buttons to work with our routing
$content = preg_replace('/\(\d\d-/m', '(', $page->content);
assert(is_string($content));
$content = str_replace('.md)', ')', $content);
$data = [
'title' => $page->title,
'content' => $this->parser->parse($content),
];
$html = $this->renderer->render('page/show', $data);
$this->response->getBody()->write($html);
return $this->response;
}
public function list(): ResponseInterface
{
$pages = array_map(function (MarkdownPage $page) {
return [
'id' => $page->id,
'title' => $page->title,
];
}, $this->repo->all());
$html = $this->renderer->render('page/list', ['pages' => $pages]);
$this->response->getBody()->write($html);
return $this->response;
}
}

View file

@ -1,40 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework;
use Lubian\NoFramework\Factory\FileSystemSettingsProvider;
use Lubian\NoFramework\Factory\SettingsContainerProvider;
use Throwable;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
use function assert;
use function error_log;
use function error_reporting;
use const E_ALL;
require __DIR__ . '/../vendor/autoload.php';
error_reporting(E_ALL);
$settingsProvider = new FileSystemSettingsProvider(__DIR__ . '/../config/settings.php');
$container = (new SettingsContainerProvider($settingsProvider))->getContainer();
$settings = $settingsProvider->getSettings();
$whoops = new Run;
if ($settings->environment === 'dev') {
$whoops->pushHandler(new PrettyPageHandler);
} else {
$whoops->pushHandler(function (Throwable $e): void {
error_log('Error: ' . $e->getMessage(), (int) $e->getCode());
echo 'An Error happened';
});
}
$whoops->register();
$app = $container->get(Kernel::class);
assert($app instanceof Kernel);
$app->run();

View file

@ -1,9 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Exception;
use Exception;
final class InternalServerError extends Exception
{
}

View file

@ -1,9 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Exception;
use Exception;
final class MethodNotAllowed extends Exception
{
}

View file

@ -1,9 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Exception;
use Exception;
final class NotFound extends Exception
{
}

View file

@ -1,10 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use Psr\Container\ContainerInterface;
interface ContainerProvider
{
public function getContainer(): ContainerInterface;
}

View file

@ -1,28 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use Laminas\Diactoros\ServerRequestFactory;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\UriInterface;
final class DiactorosRequestFactory implements RequestFactory
{
public function __construct(private readonly ServerRequestFactory $factory)
{
}
public function fromGlobals(): ServerRequestInterface
{
return $this->factory::fromGlobals();
}
/**
* @param UriInterface|string $uri
* @param array<mixed> $serverParams
*/
public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
{
return $this->factory->createServerRequest($method, $uri, $serverParams);
}
}

View file

@ -1,22 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use Lubian\NoFramework\Settings;
use function assert;
final class FileSystemSettingsProvider implements SettingsProvider
{
public function __construct(
private string $filePath
) {
}
public function getSettings(): Settings
{
$settings = require $this->filePath;
assert($settings instanceof Settings);
return $settings;
}
}

View file

@ -1,25 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use Lubian\NoFramework\Http\ContainerPipeline;
use Lubian\NoFramework\Http\Pipeline;
use Lubian\NoFramework\Http\RoutedRequestHandler;
use Lubian\NoFramework\Settings;
use Psr\Container\ContainerInterface;
class PipelineProvider
{
public function __construct(
private Settings $settings,
private RoutedRequestHandler $tip,
private ContainerInterface $container,
) {
}
public function getPipeline(): Pipeline
{
$middlewares = require $this->settings->middlewaresFile;
return new ContainerPipeline($middlewares, $this->tip, $this->container);
}
}

View file

@ -1,11 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
interface RequestFactory extends ServerRequestFactoryInterface
{
public function fromGlobals(): ServerRequestInterface;
}

View file

@ -1,26 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use DI\ContainerBuilder;
use Lubian\NoFramework\Settings;
use Psr\Container\ContainerInterface;
final class SettingsContainerProvider implements ContainerProvider
{
public function __construct(
private SettingsProvider $settingsProvider,
) {
}
public function getContainer(): ContainerInterface
{
$builder = new ContainerBuilder;
$settings = $this->settingsProvider->getSettings();
$dependencies = require $settings->dependenciesFile;
$dependencies[Settings::class] = $settings;
$builder->addDefinitions($dependencies);
// $builder->enableCompilation('/tmp');
return $builder->build();
}
}

View file

@ -1,10 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Factory;
use Lubian\NoFramework\Settings;
interface SettingsProvider
{
public function getSettings(): Settings;
}

View file

@ -1,38 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use Psr\Http\Message\ResponseInterface;
use function header;
use function sprintf;
use function strtolower;
final class BasicEmitter implements Emitter
{
public function emit(ResponseInterface $response, bool $withoutBody = false): void
{
foreach ($response->getHeaders() as $name => $values) {
$first = strtolower($name) !== 'set-cookie';
foreach ($values as $value) {
$header = sprintf('%s: %s', $name, $value);
header($header, $first);
$first = false;
}
}
$statusLine = sprintf(
'HTTP/%s %s %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
);
header($statusLine, true, $response->getStatusCode());
if ($withoutBody) {
return;
}
echo $response->getBody();
}
}

View file

@ -1,82 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function array_reverse;
use function assert;
use function is_string;
class ContainerPipeline implements Pipeline
{
/**
* @param array<MiddlewareInterface|class-string> $middlewares
* @param RequestHandlerInterface $tip
* @param ContainerInterface $container
*/
public function __construct(
private array $middlewares,
private RequestHandlerInterface $tip,
private ContainerInterface $container,
) {
}
public function dispatch(ServerRequestInterface $request): ResponseInterface
{
$this->buildStack();
return $this->tip->handle($request);
}
private function buildStack(): void
{
foreach (array_reverse($this->middlewares) as $middleware) {
$next = $this->tip;
if ($middleware instanceof MiddlewareInterface) {
$this->tip = $this->wrapMiddleware($middleware, $next);
}
if (is_string($middleware)) {
$this->tip = $this->wrapResolvedMiddleware($middleware, $next);
}
}
}
private function wrapResolvedMiddleware(string $middleware, RequestHandlerInterface $next): RequestHandlerInterface
{
return new class ($middleware, $next, $this->container) implements RequestHandlerInterface {
public function __construct(
private readonly string $middleware,
private readonly RequestHandlerInterface $handler,
private readonly ContainerInterface $container,
) {
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$middleware = $this->container->get($this->middleware);
assert($middleware instanceof MiddlewareInterface);
return $middleware->process($request, $this->handler);
}
};
}
private function wrapMiddleware(MiddlewareInterface $middleware, RequestHandlerInterface $next): RequestHandlerInterface
{
return new class ($middleware, $next) implements RequestHandlerInterface {
public function __construct(
private readonly MiddlewareInterface $middleware,
private readonly RequestHandlerInterface $handler,
) {
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->middleware->process($request, $this->handler);
}
};
}
}

View file

@ -1,10 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use Psr\Http\Message\ResponseInterface;
interface Emitter
{
public function emit(ResponseInterface $response, bool $withoutBody = false): void;
}

View file

@ -1,34 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use Invoker\InvokerInterface;
use Lubian\NoFramework\Exception\InternalServerError;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
final class InvokerRoutedHandler implements RoutedRequestHandler
{
public function __construct(
private readonly InvokerInterface $invoker,
private string $routeAttributeName = '__route_handler',
) {
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$handler = $request->getAttribute($this->routeAttributeName, false);
$vars = $request->getAttributes();
$vars['request'] = $request;
$response = $this->invoker->call($handler, $vars);
if (! $response instanceof ResponseInterface) {
throw new InternalServerError('Handler returned invalid response');
}
return $response;
}
public function setRouteAttributeName(string $routeAttributeName = '__route_handler'): void
{
$this->routeAttributeName = $routeAttributeName;
}
}

View file

@ -1,11 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
interface Pipeline
{
public function dispatch(ServerRequestInterface $request): ResponseInterface;
}

View file

@ -1,69 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use FastRoute\Dispatcher;
use Lubian\NoFramework\Exception\InternalServerError;
use Lubian\NoFramework\Exception\MethodNotAllowed;
use Lubian\NoFramework\Exception\NotFound;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;
final class RouteMiddleware implements MiddlewareInterface
{
public function __construct(
private readonly Dispatcher $dispatcher,
private readonly ResponseFactoryInterface $responseFactory,
private readonly string $routeAttributeName = '__route_handler',
) {
}
private function decorateRequest(
ServerRequestInterface $request,
): ServerRequestInterface {
$routeInfo = $this->dispatcher->dispatch(
$request->getMethod(),
$request->getUri()->getPath(),
);
if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
throw new MethodNotAllowed;
}
if ($routeInfo[0] === Dispatcher::FOUND) {
foreach ($routeInfo[2] as $attributeName => $attributeValue) {
$request = $request->withAttribute($attributeName, $attributeValue);
}
return $request->withAttribute(
$this->routeAttributeName,
$routeInfo[1]
);
}
throw new NotFound;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
try {
$request = $this->decorateRequest($request);
} catch (NotFound) {
$response = $this->responseFactory->createResponse(404);
$response->getBody()->write('Not Found');
return $response;
} catch (MethodNotAllowed) {
return $this->responseFactory->createResponse(405);
} catch (Throwable $t) {
throw new InternalServerError($t->getMessage(), $t->getCode(), $t);
}
if ($handler instanceof RoutedRequestHandler) {
$handler->setRouteAttributeName($this->routeAttributeName);
}
return $handler->handle($request);
}
}

View file

@ -1,10 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Http;
use Psr\Http\Server\RequestHandlerInterface;
interface RoutedRequestHandler extends RequestHandlerInterface
{
public function setRouteAttributeName(string $routeAttributeName = '__route_handler'): void;
}

View file

@ -1,32 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework;
use Lubian\NoFramework\Factory\RequestFactory;
use Lubian\NoFramework\Http\Emitter;
use Lubian\NoFramework\Http\Pipeline;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
final class Kernel implements RequestHandlerInterface
{
public function __construct(
private readonly RequestFactory $requestFactory,
private readonly Pipeline $pipeline,
private readonly Emitter $emitter,
) {
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->pipeline->dispatch($request);
}
public function run(): void
{
$request = $this->requestFactory->fromGlobals();
$response = $this->handle($request);
$this->emitter->emit($response);
}
}

View file

@ -1,38 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Middleware;
use Laminas\Diactoros\Response\Serializer;
use Lubian\NoFramework\Service\Cache\EasyCache;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use function assert;
use function base64_encode;
use function is_string;
final class Cache implements MiddlewareInterface
{
public function __construct(
private readonly EasyCache $cache,
private readonly Serializer $serializer,
) {
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
if ($request->getMethod() !== 'GET') {
return $handler->handle($request);
}
$keyHash = base64_encode($request->getUri()->getPath());
$result = $this->cache->get(
$keyHash,
fn () => $this->serializer::toString($handler->handle($request)),
300
);
assert(is_string($result));
return $this->serializer::fromString($result);
}
}

View file

@ -1,13 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Model;
class MarkdownPage
{
public function __construct(
public int |null $id = null,
public string $title,
public string $content,
) {
}
}

View file

@ -1,49 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Repository;
use Lubian\NoFramework\Model\MarkdownPage;
use Lubian\NoFramework\Service\Cache\EasyCache;
use function assert;
use function base64_encode;
use function is_array;
final class CachedMarkdownPageRepo implements MarkdownPageRepo
{
public function __construct(
private EasyCache $cache,
private MarkdownPageRepo $repo,
) {
}
/**
* @inheritDoc
*/
public function all(): array
{
$key = base64_encode(self::class . 'all');
$result = $this->cache->get(
$key,
fn () => $this->repo->all(),
300
);
assert(is_array($result));
foreach ($result as $page) {
assert($page instanceof MarkdownPage);
}
return $result;
}
public function byName(string $name): MarkdownPage
{
$key = base64_encode(self::class . 'byName' . $name);
$result = $this->cache->get(
$key,
fn () => $this->repo->byName($name),
300
);
assert($result instanceof MarkdownPage);
return $result;
}
}

View file

@ -1,61 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Repository;
use Lubian\NoFramework\Exception\InternalServerError;
use Lubian\NoFramework\Exception\NotFound;
use Lubian\NoFramework\Model\MarkdownPage;
use function array_filter;
use function array_map;
use function array_values;
use function count;
use function file_get_contents;
use function glob;
use function str_replace;
use function substr;
final class FileSystemMarkdownPageRepo implements MarkdownPageRepo
{
public function __construct(
private readonly string $dataPath
) {
}
/** @inheritDoc */
public function all(): array
{
$files = glob($this->dataPath . '*.md');
if ($files === false) {
throw new InternalServerError('cannot read pages');
}
return array_map(function (string $filename) {
$content = file_get_contents($filename);
if ($content === false) {
throw new InternalServerError('cannot read pages');
}
$idAndTitle = str_replace([$this->dataPath, '.md'], ['', ''], $filename);
return new MarkdownPage(
(int) substr($idAndTitle, 0, 2),
substr($idAndTitle, 3),
$content
);
}, $files);
}
public function byName(string $name): MarkdownPage
{
$pages = array_values(
array_filter(
$this->all(),
fn (MarkdownPage $p) => $p->title === $name,
)
);
if (count($pages) !== 1) {
throw new NotFound;
}
return $pages[0];
}
}

View file

@ -1,15 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Repository;
use Lubian\NoFramework\Exception\NotFound;
use Lubian\NoFramework\Model\MarkdownPage;
interface MarkdownPageRepo
{
/** @return MarkdownPage[] */
public function all(): array;
/** @throws NotFound */
public function byName(string $name): MarkdownPage;
}

View file

@ -1,21 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Service\Cache;
use function apcu_add;
use function apcu_fetch;
final class ApcuCache implements EasyCache
{
public function get(string $key, callable $callback, int $ttl = 0): mixed
{
$success = false;
$result = apcu_fetch($key, $success);
if ($success === true) {
return $result;
}
$result = $callback();
apcu_add($key, $result, $ttl);
return $result;
}
}

View file

@ -1,9 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Service\Cache;
interface EasyCache
{
/** @param callable(): mixed $callback */
public function get(string $key, callable $callback, int $ttl = 0): mixed;
}

View file

@ -1,10 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Service\Time;
use DateTimeImmutable;
interface Now
{
public function __invoke(): DateTimeImmutable;
}

View file

@ -1,13 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Service\Time;
use DateTimeImmutable;
final class SystemClockNow implements Now
{
public function __invoke(): DateTimeImmutable
{
return new DateTimeImmutable;
}
}

View file

@ -1,16 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework;
final class Settings
{
public function __construct(
public readonly string $environment,
public readonly string $dependenciesFile,
public readonly string $middlewaresFile,
public readonly string $templateDir,
public readonly string $templateExtension,
public readonly string $pagesPath,
) {
}
}

View file

@ -1,8 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Template;
interface MarkdownParser
{
public function parse(string $markdown): string;
}

View file

@ -1,17 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Template;
use Mustache_Engine;
final class MustacheRenderer implements Renderer
{
public function __construct(private Mustache_Engine $engine)
{
}
public function render(string $template, array $data = []): string
{
return $this->engine->render($template, $data);
}
}

View file

@ -1,17 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Template;
use Parsedown;
final class ParsedownParser implements MarkdownParser
{
public function __construct(private Parsedown $parser)
{
}
public function parse(string $markdown): string
{
return $this->parser->parse($markdown);
}
}

View file

@ -1,11 +0,0 @@
<?php declare(strict_types=1);
namespace Lubian\NoFramework\Template;
interface Renderer
{
/**
* @param array<string, mixed> $data
*/
public function render(string $template, array $data = []): string;
}