From PHP

The library the command line and the browser app are built on.

The library, rmb32/barntree, is what the command line and the browser app are built on. Use it directly to build, edit and check Trees in your own code. The examples below were run as written, against the released package.

composer require rmb32/barntree

Build a Tree, edit it and be refused #

TreeFactory builds a Tree from a document, as PHP arrays. TreeEditorFactory edits one by the path of names to an item, and returns a new Tree. The one you passed in is unchanged.

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Rmb32\Barntree\Api\Exception\Tree\DuplicateMemberNameException;
use Rmb32\Barntree\Api\Factory\TextProjectorFactory;
use Rmb32\Barntree\Api\Factory\TreeEditorFactory;
use Rmb32\Barntree\Api\Factory\TreeFactory;
use Rmb32\Barntree\Api\ValueObject\ItemName;
use Rmb32\Barntree\Api\ValueObject\ItemPath;

$tree = new TreeFactory()->create([
    'formatVersion' => 1,
    'name' => 'Allotment',
    'description' => 'A plot of ground, rented to grow food on.',
    'root' => 'Allotment',
    'types' => [
        'Allotment' => [
            'name' => 'Allotment',
            'meaning' => 'The whole plot.',
            'kind' => 'map',
            'of' => ['Beds', 'Shed'],
        ],
        'Beds' => [
            'name' => 'Beds',
            'meaning' => 'The raised beds.',
            'kind' => 'list',
            'of' => 'Bed',
        ],
        'Bed' => ['name' => 'Bed', 'meaning' => 'One raised bed.', 'kind' => 'leaf'],
        'Shed' => ['name' => 'Shed', 'meaning' => 'Where the tools are kept.', 'kind' => 'leaf'],
    ],
]);

$editor = new TreeEditorFactory()->create();
$beds = new ItemPath('Beds');
$tree = $editor->addMember($tree, $beds, new ItemName('Beans'));
$tree = $editor->addMember($tree, $beds, new ItemName('Leeks'));

echo new TextProjectorFactory()->create()->project($tree), PHP_EOL;

try {
    $editor->addMember($tree, $beds, new ItemName('Beans'));
} catch (DuplicateMemberNameException $e) {
    echo 'Refused: a second ', $e->name, PHP_EOL;
}

echo 'Beans is item ', $tree->find(new ItemPath('Beds', 'Beans'))->id(), PHP_EOL;
Allotment
|
+--Beds
   |
   +--Beans
   +--Leeks
+--Shed

Refused: a second Beans
Beans is item afdf58a93cb2a8e6

The editor’s operations:

  • addMember($tree, $list, $name) adds a member to the list item at $list, with its own skeleton.
  • removeMember($tree, $member) removes a member and everything below it.
  • renameMember($tree, $member, $name) renames a list member, keeping its id, kind and children.
  • changeTypes($tree, $root, $types) gives the Tree new types and fits its tree to them. Compare the trees before and after to see what would be dropped, and keep the result only if that is what you want.
  • $tree->find($path) returns the item at a path, and new ItemPath() is the root.

Refusals #

A document that doesn’t fit the shape is refused with one TreeNotWellFormedException, whose faults lists every problem at once, each with the path that caused it. A document that fits the shape but breaks a rule, or an edit that would, is refused with the exception for that rule. Each extends TreeException, is checked, and carries what it is about as public read-only properties, as $e->name above.

Templates and Constructions #

TemplateHistoryStoreFactory keeps Templates and their revisions in a barn. RevisionWorkspaceFactory makes and saves Constructions. Both open a barn from BarnPaths::at() with forBarn(). This script reads the Allotment Template and makes a Construction from it:

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Rmb32\Barntree\Api\Factory\RevisionWorkspaceFactory;
use Rmb32\Barntree\Api\Factory\TemplateHistoryStoreFactory;
use Rmb32\Barntree\Api\Factory\TreeFactory;
use Rmb32\Barntree\Api\ValueObject\DocumentKind;
use Rmb32\BarnPaths\Api\ValueObject\BarnPaths;

$paths = BarnPaths::at($argv[1]);
$templates = new TemplateHistoryStoreFactory()->forBarn($paths);
$workspace = new RevisionWorkspaceFactory()->forBarn($paths);

$checkout = $templates->checkout('Allotment');
echo 'Template: revision ', $checkout->revision->number, PHP_EOL;

$draft = $workspace->newConstruction($checkout->revision->documentId, 'Plot 14');
$saved = $workspace->save($draft);
echo 'Plot 14: revision ', $saved->number, ', made from revision ', $saved->source->number, PHP_EOL;

foreach ($workspace->history(DocumentKind::Construction, $saved->documentId) as $revision) {
    echo '  revision ', $revision->number, ': ', $revision->reason === '' ? '(no reason)' : $revision->reason, PHP_EOL;
}
Template: revision 1
Plot 14: revision 1, made from revision 1
  revision 1: (no reason)

Starting and editing a draft writes nothing. Edit its content with the same editor, pass the result to draft->withContent($edited), and call save() when ready. A stale base is refused instead of overwriting a newer save. A save can carry a reason, saveTemplate($name, $content, $token, 'Why'), which the revision returns as reason. The app and the command line don’t set or show it.

inDirectory('/my/folder') on either factory keeps a catalogue apart from the barn’s. TemplateHistoryStoreFactory::lockFiles() lists the lock files a catalogue writes, as patterns relative to its folder, so you can keep them out of version control.

Projections #

A projector turns a Tree into text without touching the disk. ProjectorRegistryFactory holds the four built in, as text, markdown, folder and mermaid, in that order, and with() adds your own. A projector you register appears in the app with no change to it.

Stores #

TreeStoreFactory gives a store over one directory of .barntree.json files, found by the name inside each file, not by where they are. It offers names(), has(), read(), write() and delete(). With writable: false it refuses to write, which is how a shipped catalogue is read.

Listen to changes #

A store can tell your code of each change it writes, so your code can react without the store knowing about it. Make a registry with ListenerRegistryFactory, register a listener for a kind of change, before the write or after it, and pass the registry to the store’s factory as listeners:. This script keeps a diary of the beds, and refuses to clear one that is still growing:

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Rmb32\Barntree\Api\Contract\ListenerFailureHandlerInterface;
use Rmb32\Barntree\Api\Contract\ListenerInterface;
use Rmb32\Barntree\Api\Exception\Event\VetoedException;
use Rmb32\Barntree\Api\Factory\ListenerRegistryFactory;
use Rmb32\Barntree\Api\Factory\TreeEditorFactory;
use Rmb32\Barntree\Api\Factory\TreeFactory;
use Rmb32\Barntree\Api\Factory\TreeStoreFactory;
use Rmb32\Barntree\Api\ValueObject\Event\Change\MemberAdded;
use Rmb32\Barntree\Api\ValueObject\Event\Change\MemberChangeInterface;
use Rmb32\Barntree\Api\ValueObject\Event\Change\MemberRemoved;
use Rmb32\Barntree\Api\ValueObject\Event\Event;
use Rmb32\Barntree\Api\ValueObject\ItemName;
use Rmb32\Barntree\Api\ValueObject\ItemPath;

/** @implements ListenerInterface<MemberChangeInterface> */
final readonly class Diary implements ListenerInterface
{
    public function handle(Event $event): void
    {
        $change = $event->payload;
        if ($change instanceof MemberAdded) {
            echo 'Planted ', $change->path, PHP_EOL;
        }
        if ($change instanceof MemberRemoved) {
            echo 'Cleared ', $change->path, PHP_EOL;
        }
    }
}

/** @implements ListenerInterface<MemberRemoved> */
final readonly class StillGrowing implements ListenerInterface
{
    public function handle(Event $event): void
    {
        if ((string) $event->payload->path === 'Beds/Beans') {
            throw new VetoedException('the beans are still growing');
        }
    }
}

final readonly class Report implements ListenerFailureHandlerInterface
{
    public function failed(Event $event, Throwable $failure): void
    {
        echo 'A listener failed: ', $failure->getMessage(), PHP_EOL;
    }
}

$listeners = new ListenerRegistryFactory()->create(new Report());
$listeners->after(MemberChangeInterface::class, new Diary());
$listeners->before(MemberRemoved::class, new StillGrowing());

$store = new TreeStoreFactory()->create($argv[1], listeners: $listeners);
$tree = new TreeFactory()->create([
    'formatVersion' => 1,
    'name' => 'Allotment',
    'description' => 'A plot of ground, rented to grow food on.',
    'root' => 'Allotment',
    'types' => [
        'Allotment' => ['name' => 'Allotment', 'meaning' => 'The whole plot.', 'kind' => 'map', 'of' => ['Beds']],
        'Beds' => ['name' => 'Beds', 'meaning' => 'The raised beds.', 'kind' => 'list', 'of' => 'Bed'],
        'Bed' => ['name' => 'Bed', 'meaning' => 'One raised bed.', 'kind' => 'leaf'],
    ],
]);
$store->write($tree);

$editor = new TreeEditorFactory()->create();
$beds = new ItemPath('Beds');
$tree = $editor->addMember($tree, $beds, new ItemName('Beans'));
$tree = $editor->addMember($tree, $beds, new ItemName('Leeks'));
$store->write($tree);

try {
    $store->write($editor->removeMember($tree, new ItemPath('Beds', 'Beans')));
} catch (VetoedException $e) {
    echo 'Refused: ', $e->reason, PHP_EOL;
}
$store->write($editor->removeMember($tree, new ItemPath('Beds', 'Leeks')));

Run with an empty folder, it prints:

Planted Beds/Beans
Planted Beds/Leeks
Refused: the beans are still growing
Cleared Beds/Leeks
  • A listener hears each change as its own event: a member added, removed, renamed or moved, a type added or renamed, a tag declared, and so on. It can listen for one kind, or for a whole group such as MemberChangeInterface. TreeWrite holds the whole Tree before and after the write.
  • Each event carries the Tree’s name, where the write came from (origin: on the factory: the command line, the app, your code or an import), and, for a Template or Construction, its reason and revision.
  • A listener before the write may refuse it by throwing VetoedException, and nothing is written. The store may still refuse a write after that, for its own reasons, so do your work after.
  • A listener after the write can’t undo it. If it fails, the failure goes to the handler you gave the registry, and the other listeners still hear.
  • A listener may not write the Tree it is being told about.
  • The Template and Construction factories, forBarn() and inDirectory(), take the same listeners: and origin:. Without them, nothing listens.

More examples #

The package carries runnable examples in its examples/ folder, each with the output it prints: quickstart, house, projections, refusals, storage, revisions and events.