Completed
Push — add/changelog-tooling ( 7f5585...86359e )
by
unknown
58:45 queued 48:46
created

CommandLoader   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 52
rs 10
c 0
b 0
f 0
wmc 7
lcom 0
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A get_class_name() 0 3 1
A has() 0 3 1
A get() 0 7 2
A getNames() 0 9 3
1
<?php // phpcs:ignore WordPress.Files.FileName
2
/**
3
 * Command loader for the changelogger tool CLI.
4
 *
5
 * @package automattic/jetpack-changelogger
6
 */
7
8
namespace Automattic\Jetpack\Changelogger;
9
10
use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
11
use Symfony\Component\Console\Exception\CommandNotFoundException;
12
13
/**
14
 * Command loader for the changelogger tool CLI.
15
 */
16
class CommandLoader implements CommandLoaderInterface {
17
18
	/**
19
	 * Get the class name for a command.
20
	 *
21
	 * @param string $name Command name.
22
	 * @return string Class name.
23
	 */
24
	private function get_class_name( $name ) {
25
		return __NAMESPACE__ . '\\' . ucfirst( $name ) . 'Command';
26
	}
27
28
	/**
29
	 * Checks if a command exists.
30
	 *
31
	 * @param string $name Command name.
32
	 * @return bool
33
	 */
34
	public function has( $name ) {
35
		return class_exists( $this->get_class_name( $name ) );
36
	}
37
38
	/**
39
	 * Loads a command.
40
	 *
41
	 * @param string $name Command name.
42
	 * @return Command
43
	 * @throws CommandNotFoundException If the command is not found.
44
	 */
45
	public function get( $name ) {
46
		$class = $this->get_class_name( $name );
47
		if ( ! class_exists( $class ) ) {
48
			throw new CommandNotFoundException( "Command \"$name\" does not exist." );
49
		}
50
		return new $class();
51
	}
52
53
	/**
54
	 * Return all command names.
55
	 *
56
	 * @return string[] All registered command names
57
	 */
58
	public function getNames() {
59
		$names = array();
60
		foreach ( new \DirectoryIterator( __DIR__ ) as $file ) {
61
			if ( substr( $file->getBasename(), -11 ) === 'Command.php' ) {
62
				$names[] = lcfirst( substr( $file->getBasename(), 0, -11 ) );
63
			}
64
		}
65
		return $names;
66
	}
67
}
68