Passed
Push — master ( d3a32c...c376fe )
by Kevin
27:18 queued 23:10
created

MakeFactory   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Test Coverage

Coverage 70.13%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 15
eloc 46
c 2
b 0
f 0
dl 0
loc 106
ccs 54
cts 77
cp 0.7013
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A configureDependencies() 0 2 1
A configureCommand() 0 9 1
A interact() 0 15 3
A __construct() 0 3 1
A getCommandName() 0 3 1
A generate() 0 42 5
A entityChoices() 0 13 3
1
<?php
2
3
namespace Zenstruck\Foundry\Bundle\Maker;
4
5
use Doctrine\Persistence\ManagerRegistry;
6
use Symfony\Bundle\MakerBundle\ConsoleStyle;
7
use Symfony\Bundle\MakerBundle\DependencyBuilder;
8
use Symfony\Bundle\MakerBundle\Exception\RuntimeCommandException;
9
use Symfony\Bundle\MakerBundle\Generator;
10
use Symfony\Bundle\MakerBundle\InputConfiguration;
11
use Symfony\Bundle\MakerBundle\Maker\AbstractMaker;
12
use Symfony\Component\Console\Command\Command;
13
use Symfony\Component\Console\Input\InputArgument;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
17
/**
18
 * @author Kevin Bond <[email protected]>
19
 */
20
final class MakeFactory extends AbstractMaker
21
{
22
    /** @var ManagerRegistry */
23
    private $managerRegistry;
24
25 20
    public function __construct(ManagerRegistry $managerRegistry)
26
    {
27 20
        $this->managerRegistry = $managerRegistry;
28 20
    }
29
30 4
    public static function getCommandName(): string
31
    {
32 4
        return 'make:factory';
33
    }
34
35 20
    public function configureCommand(Command $command, InputConfiguration $inputConfig): void
36
    {
37
        $command
38 20
            ->setDescription('Creates a Foundry model factory for a Doctrine entity class')
39 20
            ->addArgument('entity', InputArgument::OPTIONAL, 'Entity class to create a factory for')
40 20
            ->addOption('test', null, InputOption::VALUE_NONE, 'Create in <fg=yellow>tests/</> instead of <fg=yellow>src/</>')
41
        ;
42
43 20
        $inputConfig->setArgumentAsNonInteractive('entity');
44 20
    }
45
46 20
    public function interact(InputInterface $input, ConsoleStyle $io, Command $command): void
47
    {
48 20
        if ($input->getArgument('entity')) {
49 12
            return;
50
        }
51
52 8
        if (!$input->getOption('test')) {
53 4
            $io->text('// Note: pass <fg=yellow>--test</> if you want to generate factories in your <fg=yellow>tests/</> directory');
54 4
            $io->newLine();
55
        }
56
57 8
        $argument = $command->getDefinition()->getArgument('entity');
58 8
        $entity = $io->choice($argument->getDescription(), $this->entityChoices());
59
60 8
        $input->setArgument('entity', $entity);
61 8
    }
62
63 20
    public function generate(InputInterface $input, ConsoleStyle $io, Generator $generator): void
64
    {
65 20
        $class = $input->getArgument('entity');
66
67 20
        if (!\class_exists($class)) {
0 ignored issues
show
Bug introduced by
It seems like $class can also be of type string[]; however, parameter $class_name of class_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

67
        if (!\class_exists(/** @scrutinizer ignore-type */ $class)) {
Loading history...
68 4
            $class = $generator->createClassNameDetails($class, 'Entity\\')->getFullName();
0 ignored issues
show
Bug introduced by
It seems like $class can also be of type null and string[]; however, parameter $name of Symfony\Bundle\MakerBund...reateClassNameDetails() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

68
            $class = $generator->createClassNameDetails(/** @scrutinizer ignore-type */ $class, 'Entity\\')->getFullName();
Loading history...
69
        }
70
71 20
        if (!\class_exists($class)) {
72 4
            throw new RuntimeCommandException(\sprintf('Entity "%s" not found.', $input->getArgument('entity')));
0 ignored issues
show
Bug introduced by
It seems like $input->getArgument('entity') can also be of type string[]; however, parameter $args of sprintf() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

72
            throw new RuntimeCommandException(\sprintf('Entity "%s" not found.', /** @scrutinizer ignore-type */ $input->getArgument('entity')));
Loading history...
73
        }
74
75 16
        $entity = new \ReflectionClass($class);
76 16
        $factory = $generator->createClassNameDetails(
77 16
            $entity->getShortName(),
78 16
            $input->getOption('test') ? 'Tests\\Factory' : 'Factory',
79 16
            'Factory'
80
        );
81
82 16
        $repository = new \ReflectionClass($this->managerRegistry->getRepository($entity->getName()));
83
84 16
        if (0 !== \mb_strpos($repository->getName(), $generator->getRootNamespace())) {
85
            // not using a custom repository
86 16
            $repository = null;
87
        }
88
89 16
        $generator->generateClass(
90 16
            $factory->getFullName(),
91 16
            __DIR__.'/../Resources/skeleton/Factory.tpl.php',
92
            [
93 16
                'entity' => $entity,
94 16
                'repository' => $repository,
95
            ]
96
        );
97
98 16
        $generator->writeChanges();
99
100 16
        $this->writeSuccessMessage($io);
101
102 16
        $io->text([
103 16
            'Next: Open your new factory and set default values/states.',
104
            'Find the documentation at https://github.com/zenstruck/foundry#model-factories',
105
        ]);
106 16
    }
107
108 20
    public function configureDependencies(DependencyBuilder $dependencies): void
109
    {
110
        // noop
111 20
    }
112
113 8
    private function entityChoices(): array
114
    {
115 8
        $choices = [];
116
117 8
        foreach ($this->managerRegistry->getManagers() as $manager) {
118 8
            foreach ($manager->getMetadataFactory()->getAllMetadata() as $metadata) {
119 8
                $choices[] = $metadata->getName();
120
            }
121
        }
122
123 8
        \sort($choices);
124
125 8
        return $choices;
126
    }
127
}
128