ew_deployer_config/Classes/Tasks/AbstractTasks.php
2025-04-18 14:11:54 +02:00

105 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Evoweb\DeployerConfig\Tasks;
use Deployer\Deployer;
use Deployer\Task\GroupTask;
use Deployer\Task\Task;
use Evoweb\DeployerConfig\Config\Deployment;
use InvalidArgumentException;
use phpDocumentor\Reflection\DocBlockFactory;
use ReflectionMethod;
use function Deployer\get;
use function Deployer\has;
use function Deployer\set;
use function Deployer\testLocally;
abstract class AbstractTasks
{
protected array $tasks = [];
public function __construct()
{
$this->setDefaultConfiguration();
$this->initializeTasks();
}
protected function setDefaultConfiguration(): void
{
}
protected function initializeTasks(): void
{
array_walk($this->tasks, [$this, 'registerTask']);
}
protected function registerTask(array|string $body, string $name): void
{
if (!is_array($body)) {
$name = $body;
$body = lcfirst(str_replace('_', '', ucwords(strtolower(preg_replace('/[^:]+:/', '', $body)), '_')));
if (!method_exists($this, $body)) {
print_r('not found ' . $body . "\n");
}
}
if (is_callable([$this, $body])) {
$task = new Task($name, [$this, $body]);
$description = $this->getFunctionSummary($body);
if ($description) {
$task->desc($description);
}
} elseif (is_array($body)) {
$task = new GroupTask($name, $body);
} else {
throw new InvalidArgumentException('Task body should be a function or an array.');
}
$deployer = Deployer::get();
$deployer->tasks->set($name, $task);
}
protected function getFunctionSummary(string $function): string
{
$summary = '';
try {
$reflector = new ReflectionMethod(Deployment::class, $function);
$comment = $reflector->getDocComment();
if ($comment) {
$summary = DocBlockFactory::createInstance()->create($comment)->getSummary();
}
} catch (\Exception) {
}
return $summary;
}
protected function commandExist(string $command): bool
{
return testLocally("hash $command 2>/dev/null");
}
protected function set(string $name, $value): void
{
set($name, $value);
}
protected function get(string $name, $default = null)
{
return get($name, $default);
}
protected function has(string $name): bool
{
return has($name);
}
protected function hasArray(string $name): bool
{
return $this->has($name) && is_array($this->get($name));
}
}