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.
PhpCliProgram/src/CliProgram/AutoPrefixNamespaceManager.php

107 lines
2.9 KiB
PHP

<?php
namespace jrosset\CliProgram;
use ReflectionClass;
use Symfony\Component\Console\Command\Command;
/**
* A manager of commands auto prefix base on class namespace
*/
class AutoPrefixNamespaceManager implements IAutoPrefixManager {
/**
* @var string The base namespace
*/
private string $namespace;
/**
* @var string|null The initial prefix, Null if none
*/
private ?string $initialPrefix;
/**
* Initialization
*
* @param string $namespace The base namespace
* @param string|null $initialPrefix The initial prefix, Null if none
*/
public function __construct (string $namespace, ?string $initialPrefix = null) {
$this->setNamespace($namespace);
$this->setInitialPrefix($initialPrefix);
}
/**
* The base namespace
*
* @return string The base namespace
*/
public function getNamespace (): string {
return $this->namespace;
}
/**
* Set the base namespace
*
* @param string $namespace The base namespace
*
* @return $this
*/
public function setNamespace (string $namespace): self {
if (mb_substr($namespace, 0, 1) !== '\\') {
$namespace = '\\' . $namespace;
}
$this->namespace = $namespace;
return $this;
}
/**
* The initial prefix, Null if none
*
* @return string|null The initial prefix, Null if none
*/
public function getInitialPrefix (): ?string {
return $this->initialPrefix;
}
/**
* Set the initial prefix, Null if none
*
* @param string|null $initialPrefix The initial prefix, Null if none
*
* @return $this
*/
public function setInitialPrefix (?string $initialPrefix): self {
$this->initialPrefix = $initialPrefix;
return $this;
}
/**
* @inheritDoc
*/
public function getCommandPrefix (Command $command): ?string {
$commandClass = new ReflectionClass($command);
$commandNamespace = '\\' . $commandClass->getNamespaceName();
if ($commandNamespace !== $this->getNamespace() && mb_substr($commandNamespace, mb_strlen($this->getNamespace() . '\\')) !== $this->getNamespace() . '\\') {
return null;
}
return implode(
':',
array_filter(
[
$this->getInitialPrefix(),
mb_strtolower(
preg_replace(
[
'/^' . preg_quote($this->getNamespace(), '/') . '(?:\\\\|$)/',
'/\\\\/',
],
[
'',
':',
],
$commandNamespace
)
),
]
)
);
}
}