You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
77 lines
2.4 KiB
PHP
77 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace jrosset\CliProgram;
|
|
|
|
/**
|
|
* An application managing commands with auto prefix
|
|
*/
|
|
trait AutoPrefixApplication {
|
|
/**
|
|
* @var IAutoPrefixManager[] The lists of manager for commands auto prefix
|
|
*/
|
|
private array $autoPrefixManagers;
|
|
|
|
/**
|
|
* The lists of manager for commands auto prefix
|
|
*
|
|
* @return IAutoPrefixManager[] The lists of manager for commands auto prefix
|
|
*/
|
|
public function getAutoPrefixManagers (): array {
|
|
return $this->autoPrefixManagers;
|
|
}
|
|
/**
|
|
* Set The lists of manager for commands auto prefix
|
|
*
|
|
* @param IAutoPrefixManager[] $autoPrefixManagers The lists of manager for commands auto prefix
|
|
*
|
|
* @return $this
|
|
*/
|
|
public function setAutoPrefixManagers (array $autoPrefixManagers): self {
|
|
$this->autoPrefixManagers = $autoPrefixManagers;
|
|
return $this;
|
|
}
|
|
/**
|
|
* Add a manager for commands auto prefix
|
|
*
|
|
* @param IAutoPrefixManager $manager The manager
|
|
* @param IAutoPrefixManager ...$extraManagers Extra managers to add
|
|
*
|
|
* @return $this
|
|
*/
|
|
public function addAutoPrefixManagers (IAutoPrefixManager $manager, IAutoPrefixManager ...$extraManagers): self {
|
|
$this->autoPrefixManagers[] = $manager;
|
|
foreach ($extraManagers as $extraNamespace) {
|
|
$this->autoPrefixManagers[] = $extraNamespace;
|
|
}
|
|
return $this;
|
|
}
|
|
|
|
/**
|
|
* Apply commands auto prefixes
|
|
*
|
|
* @return $this
|
|
*/
|
|
public function applyAutoPrefixes (): self {
|
|
$commands = array_unique($this->all(), SORT_REGULAR); // Remove commands duplicate caused by aliases
|
|
foreach ($commands as $command) {
|
|
foreach ($this->getAutoPrefixManagers() as $autoPrefixManager) {
|
|
if (($namesPrefix = $autoPrefixManager->getCommandPrefix($command)) !== null) {
|
|
if (mb_strlen($namesPrefix) > 0) {
|
|
$namesPrefix .= ':';
|
|
}
|
|
|
|
$command->setName($namesPrefix . $command->getName());
|
|
|
|
$aliases = $command->getAliases();
|
|
foreach ($aliases as &$alias) {
|
|
$alias = $namesPrefix . $alias;
|
|
}
|
|
$command->setAliases($aliases);
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
return $this;
|
|
}
|
|
} |