PHP code example of nsrosenqvist / carte

1. Go to this page and download the library: Download nsrosenqvist/carte library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nsrosenqvist / carte example snippets


declare(strict_types=1);

solver;
use Carte\Content\PhpResolver;
use Carte\Content\RedirectResolver;
use Carte\Content\StreamResolver;
use Carte\Manifest;
use Carte\Router;
use GuzzleHttp\Psr7\HttpFactory;
use GuzzleHttp\Psr7\ServerRequest;

// Handle the request
$factory = new HttpFactory();
$manifest = new Manifest(__DIR__ . '/site.yml', __DIR__ . '/cache.php');
$router = new Router(
    responseFactory: $factory,
    streamFactory: $factory,
    manifest: $manifest,
    resolvers: [
        new StreamResolver(__DIR__ . '/content', $factory),
        new PhpResolver(__DIR__ . '/content'),
        new FileResolver(__DIR__ . '/content'),
        new RedirectResolver(),
    ],
);

$request = ServerRequest::fromGlobals();
$response = $router->dispatch($request);

// Emit the status code
http_response_code($response->getStatusCode());

// Emit the headers
foreach ($response->getHeaders() as $name => $values) {
    foreach ($values as $value) {
        header(sprintf('%s: %s', $name, $value), false);
    }
}

// Emit the body
echo $response->getBody();

/**
 * @param ResponseFactoryInterface   $responseFactory PSR-17 response factory
 * @param StreamFactoryInterface     $streamFactory   PSR-17 stream factory
 * @param Manifest                   $manifest        Route manifest
 */

declare(strict_types=1);

use Carte\Strategies\Strategy;
use MyFirstMiddleware;
use MySecondMiddleware;

class MyStrategy extends Strategy
{
    public function __construct() {
        parent::__construct([
            new MyFirstMiddleware(),
            new MySecondMiddleware(),
        ]);
    }
}

$resolver = new \Carte\Content\FileResolver(__DIR__ . '/content');

/**
 * @var \Carte\Routes\RouteCase                  $route
 * @var \Psr\Http\Message\ServerRequestInterface $request
 * @var int                                      $httpCode
 * @var array<string, string>                    $httpHeaders
 */

$resolver = new \Carte\Content\PhpResolver(__DIR__ . '/handlers');

$resolver = new \Carte\Content\RedirectResolver('under/root');

$factory = new \GuzzleHttp\Psr7\HttpFactory();
$resolver = new \Carte\Content\StreamResolver(__DIR__ . '/content', $factory);

declare(strict_types=1);

namespace Carte\Content;

use Carte\Content\ContentResolverInterface;
use Carte\Exceptions\FileNotFoundException;
use Carte\Routes\RouteCase;
use League\CommonMark\GithubFlavoredMarkdownConverter;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;

class FileResolver implements ContentResolverInterface
{
    protected $markdown;

    /**
     * @throws FileNotFoundException
     */
    public function __construct(
        protected string $resourceDirectory,
    ) {
        $this->markdown = new GithubFlavoredMarkdownConverter();
        $this->resourceDirectory = realpath($this->resourceDirectory) ?: '';

        if (! $this->resourceDirectory || ! is_dir($this->resourceDirectory)) {
            throw new FileNotFoundException("Resource directory not found: $resourceDirectory");
        }
    }

    public function resolve(RouteCase $route, ServerRequestInterface $request, int &$httpCode = 200, array &$httpHeaders = []): StreamInterface|string
    {
        $file = $route->body ?: '';
        $path = "{$this->resourceDirectory}/$file";

        if (! str_starts_with(realpath($path) ?: '', $this->resourceDirectory)) {
            throw new FileNotFoundException("File not found: $file");
        }

        $contents = file_get_contents($path);

        if ($contents === false) {
            throw new FileNotFoundException("File could not be read: $file");
        }

        return $this->markdown->convert($contents);
    }

    public function supports(RouteCase $route): bool
    {
        return true;
    }
}

$path = __DIR__ . '/site.yml';
$cache = __DIR__ . '/cache.php';

if (filemtime($cache) < filemtime($path)) {
    unlink($cache);
}

$manifest = new \Carte\Manifest($path, $cache);
yaml
index:
  body: 'Welcome!'
blog/*:
  body: 'php://handler.php'
about:
  routes:
    me:
      body: 'md://who-am-i.md'
    writings:
      body: 'md://writings.md'
contact:
  - body: 'php://mailer.php'
    match:
      method: POST
  - body: 'file://contact.html'
    match:
      method: GET
subscribers:
  strategy: auth
  body: 'Thank you!'