PHP code example of caseyamcl / sortable-tasks

1. Go to this page and download the library: Download caseyamcl/sortable-tasks 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/ */

    

caseyamcl / sortable-tasks example snippets



use SortableTasks\SortableTask;

abstract class SetupStep implements SortableTask
{
    abstract public function __invoke(): bool;
}
 


use SortableTasks\SortableTask;

abstract class SetupStep implements SortableTask
{
    abstract public function __invoke(): bool;

    // Provide default implementations of `dependsOn` and `mustRunBefore` that return empty arrays
    public static function dependsOn() : iterable
    {
        return [];
    }
    public static function mustRunBefore() : iterable
    {
        return [];
    }
}


class CheckConfigStep extends SetupStep
{
    public static function dependsOn(): iterable
    {
       return []; // depends on nothing; can run anytime in the order of operations
    }
    
    public function __invoke(): bool
    {
        // do stuff, then..
        return true;
    }
}

class CheckDbConnectionStep extends SetupStep
{
    private DbConnector $dbConnector;
    
    public function __construct(DbConnector $dbConnector)
    {    
        $this->dbConnector = $dbConnector;
    }

    public static function dependsOn(): iterable
    {
        return [CheckConfigStep::class];
    }

    public static function mustRunBefore(): iterable
    {
        return [BuildContainerStep::class];
    }

    public function __invoke(): bool
    {
        // do stuff, then..
        return $this->dbConnector->checkConnection();
    }
}

class BuildContainerStep extends SetupStep
{
    private ContainerBuilder $containerBuilder;

    public function __construct(ContainerBuilder $containerBuilder)
    {
        $this->containerBuilder = $containerBuilder;
    }

    public static function dependsOn(): iterable
    {
        return [CheckConfigStep::class, CheckDbConnection::class];
    }

    public function __invoke(): bool
    {
        // do stuff, then..
        return $this->containerBuilder->buildContainer();
    }
}


use SortableTasks\SortableTasksIterator;

$iterator = new SortableTasksIterator();

// Notice that it doesn't matter in what order we add the steps; they will get sorted at runtime
$iterator->add(new BuildContainerStep());
$iterator->add(new CheckDbConnectionStep());
$iterator->add(new CheckConfigStep());

// Tasks are sorted upon calling the iterator
// Class names are the keys
foreach ($iterator as $setupStepClassName => $setupStep) {
    if (! $setupStep()->__invoke()) {
        throw new SetupFailedException('Setup failed on step: ' . $setupStepClassName);
    }
}