janmartenjongerius/transaction

Create operation chain

Closed this issue · 0 comments

Create a class to chain multiple operations.
This benefits the following use case:

<?php
use Johmanx10\Transaction\OperationInterface;
use Johmanx10\Transaction\OperationChain;
use Johmanx10\Transaction\Filesystem\Operation\RemoveFile;

class Filesystem
{
    public static function remove(string $path): OperationInterface
    {
        $info       = new SplFileInfo($path);
        $operations = [];
        
        if ($info->isDir()) {
            $operations = array_reduce(
                scandir($info->getPathname()),
                function (string $entry) use ($info): OperationInterface
                {
                    if (!in_array($entry, ['.', '..'], true) {
                        $operations[] = static::remove(
                            implode(
                                DIRECTORY_SEPARATOR,
                                [$info->getPathname(), $entry]
                            )
                        );
                    }

                    return $operations;
                },
                $operations
            );
        }

        $operations[] = new RemoveFile($path);

        return new OperationChain(...$operations);
    }
}