AddingCommandInMappingSubscriber::normalizeBody()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: thales
5
 * Date: 22/01/2019
6
 * Time: 11:16
7
 */
8
9
namespace Saci\Console\Infrastructure\Domain\Services;
10
11
12
use cristianoc72\codegen\model\PhpClass;
13
use Saci\Console\Domain\Entity\Command;
14
use Saci\Console\Domain\Events\CommandWasCreated;
15
use Saci\Console\Domain\Services\ClassCommandHandlerMakerSubscriber;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Saci\Console\Infrastruct...dHandlerMakerSubscriber. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
16
use Saci\Console\Domain\Services\Exception\MappingNotFoundException;
17
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
18
use Symfony\Component\Filesystem\Filesystem;
19
20
class AddingCommandInMappingSubscriber implements ClassCommandHandlerMakerSubscriber, EventSubscriberInterface
21
{
22
23 1
    public static function getSubscribedEvents()
24
    {
25 1
        return [CommandWasCreated::NAME => 'create'];
26
    }
27
28
    /**
29
     * @param CommandWasCreated $commandWasCreated
30
     * @return bool
31
     * @throws MappingNotFoundException
32
     */
33
    public function create(CommandWasCreated $commandWasCreated)
34
    {
35
        $moduleName = $commandWasCreated->getCommand()->getModule()->getName();
36
        $commandName = $commandWasCreated->getCommand()->getClassNameCommand();
37
        $commandHandlerName = $commandWasCreated->getCommand()->getClassNameCommandHandler();
38
39
        if (!$commandWasCreated->getCommand()->getModule()->mappingExists()) {
40
            throw new MappingNotFoundException('O arquivo Mapping não foi encontrado! Crie primeiro o arquivo Mapping.php para depois criar os Commands!');
41
        }
42
43
        $class = PhpClass::fromFile($commandWasCreated->getCommand()->getModule()->getLocalMapping());
44
45
        $method = $class->getMethod('__invoke');
46
47
        $body = $this->createBody($method->getBody(), $commandWasCreated->getCommand());
48
49
        $method->setBody($body);
50
51
        $class->declareUses(
52
            "Saci\\{$moduleName}\\UseCase\\{$commandName}",
53
            "Saci\\{$moduleName}\\UseCase\\{$commandHandlerName}"
54
        );
55
56
        $generator = GeneratorClassFactory::create();
57
        $stringClass = $generator->generate($class);
58
59
        $stringClass = "<?php\n" . $stringClass;
60
61
        (new Filesystem())->dumpFile($commandWasCreated->getCommand()->getModule()->getLocalMapping(), $stringClass);
62
63
        return true;
64
    }
65
66
    private function createBody(string $body, Command $command): string
67
    {
68
        $bodyNormalized = $this->normalizeBody($body);
69
        $bodyArray = $this->bodyToArray($bodyNormalized);
70
71
        $string = '';
72
        foreach ($bodyArray as $key => $value) {
73
            if ($key > 0 && !$value) {
74
                $string .= "\n\t";
75
            }
76
77
            $string .= $value ? "$value," : "";
78
        }
79
80
        return $body = <<<BODY
0 ignored issues
show
Unused Code introduced by
The assignment to $body is dead and can be removed.
Loading history...
81
return [
82
     {$string}
83
     {$command->getClassNameCommand()}::class => {$command->getClassNameCommandHandler()}::class,
84
];
85
BODY;
86
87
    }
88
89
    private function normalizeBody(string $body): string
90
    {
91
        return str_replace(['return [', '];'], ['', ''], $body);
92
    }
93
94
    private function bodyToArray(string $body): array
95
    {
96
        return explode(',', $body);
97
    }
98
}