PHP code example of rlnks / php-mail-tree-builder

1. Go to this page and download the library: Download rlnks/php-mail-tree-builder 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/ */

    

rlnks / php-mail-tree-builder example snippets


use Nyholm\Psr7\Factory\Psr17Factory;
use Rlnks\MailTreeBuilder\BuilderConfig;
use Rlnks\MailTreeBuilder\BuilderHandler;

$factory = new Psr17Factory();

$handler = new BuilderHandler(
    config: new BuilderConfig(
        pathPrefix:  '/builder',
        corsOrigins: ['http://localhost:3000'],
        storage:     new MyStorage(),   // implements StorageInterface
    ),
    responseFactory: $factory,
);

// Slim 4
$app->any('/builder/{path:.*}', $handler);

// Vanilla PHP
$request  = $factory->createServerRequest($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
$response = $handler->handle($request);
http_response_code($response->getStatusCode());
foreach ($response->getHeaders() as $name => $values) {
    header($name . ': ' . implode(', ', $values));
}
echo $response->getBody();

use Rlnks\MailTreeBuilder\StorageInterface;

class DatabaseStorage implements StorageInterface
{
    public function save(?string $id, array $document): string
    {
        $id ??= uniqid('doc_', true);
        DB::table('builder_documents')->upsert(['id' => $id, 'data' => json_encode($document)], ['id']);
        return $id;
    }

    public function load(string $id): array
    {
        $row = DB::table('builder_documents')->find($id)
            ?? throw new \RuntimeException("Document {$id} not found.");
        return json_decode($row->data, true);
    }

    public function delete(string $id): void
    {
        DB::table('builder_documents')->delete($id);
    }

    public function list(): array
    {
        return DB::table('builder_documents')
            ->select('id', 'updated_at')
            ->orderByDesc('updated_at')
            ->get()
            ->toArray();
    }
}