HandleClassNameWithoutSuffix::getMethodName()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Tactician\Handler\Mapping\MethodName;
6
7
use function strlen;
8
use function substr;
9
10
/**
11
 * Returns a method name that is handle + the last portion of the class name
12
 * but also without a given suffix, typically "Command". This allows you to
13
 * handle multiple commands on a single object but with slightly less annoying
14
 * method names.
15
 *
16
 * The string removal is case sensitive.
17
 *
18
 * Examples:
19
 *  - \CompleteTaskCommand     => $handler->handleCompleteTask()
20
 *  - \My\App\DoThingCommand   => $handler->handleDoThing()
21
 */
22
final class HandleClassNameWithoutSuffix implements MethodNameInflector
23
{
24
    private string $suffix;
25
26
    private int $suffixLength;
27
    private HandleLastPartOfClassName $handleLastPartOfClassName;
28
29
    /**
30
     * @param string $suffix The string to remove from end of each class name
31
     */
32 3
    public function __construct(string $suffix = 'Command')
33
    {
34 3
        $this->suffix                    = $suffix;
35 3
        $this->suffixLength              = strlen($suffix);
36 3
        $this->handleLastPartOfClassName = new HandleLastPartOfClassName();
37 3
    }
38
39 3
    public function getMethodName(string $commandClassName): string
40
    {
41 3
        $methodName = $this->handleLastPartOfClassName->getMethodName($commandClassName);
42
43 3
        if (substr($methodName, $this->suffixLength * -1) !== $this->suffix) {
44 1
            return $methodName;
45
        }
46
47 2
        return substr($methodName, 0, strlen($methodName) - $this->suffixLength);
48
    }
49
}
50