Completed
Push — master ( 05902f...9e6322 )
by mark
01:41 queued 11s
created

SeedCreate   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Test Coverage

Coverage 69.57%

Importance

Changes 0
Metric Value
wmc 16
lcom 2
cbo 8
dl 0
loc 174
ccs 48
cts 69
cp 0.6957
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 13 1
A getCreateSeedDirectoryQuestion() 0 4 1
B execute() 0 65 8
A getSelectSeedPathQuestion() 0 4 1
A getSeedPath() 0 37 5
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace Phinx\Console\Command;
9
10
use Exception;
11
use InvalidArgumentException;
12
use Phinx\Config\NamespaceAwareInterface;
13
use Phinx\Util\Util;
14
use RuntimeException;
15
use Symfony\Component\Console\Input\InputArgument;
16
use Symfony\Component\Console\Input\InputInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Console\Question\ChoiceQuestion;
20
use Symfony\Component\Console\Question\ConfirmationQuestion;
21
22
class SeedCreate extends AbstractCommand
23
{
24
    /**
25
     * @var string
26
     */
27
    protected static $defaultName = 'seed:create';
28
29
    /**
30
     * {@inheritDoc}
31
     *
32
     * @return void
33
     */
34
    protected function configure()
35
    {
36
        parent::configure();
37
38
        $this->setDescription('Create a new database seeder')
39
            ->addArgument('name', InputArgument::REQUIRED, 'What is the name of the seeder?')
40
            ->addOption('path', null, InputOption::VALUE_REQUIRED, 'Specify the path in which to create this seeder')
41
            ->setHelp(sprintf(
42
                '%sCreates a new database seeder%s',
43
                PHP_EOL,
44
                PHP_EOL
45 35
            ));
46
    }
47 35
48
    /**
49 35
     * Get the confirmation question asking if the user wants to create the
50 35
     * seeds directory.
51 35
     *
52 35
     * @return \Symfony\Component\Console\Question\ConfirmationQuestion
53 35
     */
54 35
    protected function getCreateSeedDirectoryQuestion()
55 35
    {
56
        return new ConfirmationQuestion('Create seeds directory? [y]/n ', true);
57 35
    }
58 35
59
    /**
60
     * Get the question that allows the user to select which seed path to use.
61
     *
62
     * @param string[] $paths Paths
63
     *
64
     * @return \Symfony\Component\Console\Question\ChoiceQuestion
65
     */
66
    protected function getSelectSeedPathQuestion(array $paths)
67
    {
68
        return new ChoiceQuestion('Which seeds path would you like to use?', $paths, 0);
69
    }
70
71
    /**
72
     * Returns the seed path to create the seeder in.
73
     *
74
     * @param \Symfony\Component\Console\Input\InputInterface $input Input
75
     * @param \Symfony\Component\Console\Output\OutputInterface $output Output
76
     *
77
     * @throws \Exception
78
     *
79
     * @return string
80
     */
81
    protected function getSeedPath(InputInterface $input, OutputInterface $output)
82
    {
83
        // First, try the non-interactive option:
84
        $path = $input->getOption('path');
85
86
        if (!empty($path)) {
87
            return $path;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $path; (string|string[]|boolean) is incompatible with the return type documented by Phinx\Console\Command\SeedCreate::getSeedPath of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
88
        }
89
90 2
        $paths = $this->getConfig()->getSeedPaths();
91
92
        // No paths? That's a problem.
93 2
        if (empty($paths)) {
94
            throw new Exception('No seed paths set in your Phinx configuration file.');
95 2
        }
96
97
        $paths = Util::globAll($paths);
98
99 2
        if (empty($paths)) {
100
            throw new Exception(
101
                'You probably used curly braces to define seed path in your Phinx configuration file, ' .
102 2
                'but no directories have been matched using this pattern. ' .
103
                'You need to create a seed directory manually.'
104
            );
105
        }
106 2
107
        // Only one path set, so select that:
108 2
        if (count($paths) === 1) {
109
            return array_shift($paths);
110
        }
111
112
        /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
113
        $helper = $this->getHelper('question');
114
        $question = $this->getSelectSeedPathQuestion($paths);
115
116
        return $helper->ask($input, $output, $question);
117 2
    }
118 2
119
    /**
120
     * Create the new seeder.
121
     *
122
     * @param \Symfony\Component\Console\Input\InputInterface $input Input
123
     * @param \Symfony\Component\Console\Output\OutputInterface $output Output
124
     *
125
     * @throws \RuntimeException
126
     * @throws \InvalidArgumentException
127
     *
128
     * @return int 0 on success
129
     */
130
    protected function execute(InputInterface $input, OutputInterface $output)
131
    {
132
        $this->bootstrap($input, $output);
133
134
        // get the seed path from the config
135
        $path = $this->getSeedPath($input, $output);
136
137 2
        if (!file_exists($path)) {
138
            /** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
139 2
            $helper = $this->getHelper('question');
140
            $question = $this->getCreateSeedDirectoryQuestion();
141
142 2
            if ($helper->ask($input, $output, $question)) {
143
                mkdir($path, 0755, true);
144 2
            }
145
        }
146
147
        $this->verifySeedDirectory($path);
148
149
        $path = realpath($path);
150
        $className = $input->getArgument('name');
151
152
        if (!Util::isValidPhinxClassName($className)) {
0 ignored issues
show
Bug introduced by
It seems like $className defined by $input->getArgument('name') on line 150 can also be of type array<integer,string> or null; however, Phinx\Util\Util::isValidPhinxClassName() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
153 2
            throw new InvalidArgumentException(sprintf(
154
                'The seed class name "%s" is invalid. Please use CamelCase format',
155 2
                $className
156 2
            ));
157
        }
158 2
159 1
        // Compute the file path
160 1
        $filePath = $path . DIRECTORY_SEPARATOR . $className . '.php';
161
162 1
        if (is_file($filePath)) {
163
            throw new InvalidArgumentException(sprintf(
164
                'The file "%s" already exists',
165
                basename($filePath)
166 1
            ));
167
        }
168 1
169 1
        // inject the class names appropriate to this seeder
170 1
        $contents = file_get_contents($this->getSeedTemplateFilename());
171 1
172 1
        $config = $this->getConfig();
173
        $namespace = $config instanceof NamespaceAwareInterface ? $config->getSeedNamespaceByPath($path) : null;
174
        $classes = [
175
            '$namespaceDefinition' => $namespace !== null ? ('namespace ' . $namespace . ';') : '',
176 1
            '$namespace' => $namespace,
177
            '$useClassName' => $config->getSeedBaseClassName(false),
178 1
            '$className' => $className,
179 1
            '$baseClassName' => $config->getSeedBaseClassName(true),
180
        ];
181 1
        $contents = strtr($contents, $classes);
182 1
183 1
        if (file_put_contents($filePath, $contents) === false) {
184 1
            throw new RuntimeException(sprintf(
185 1
                'The file "%s" could not be written to',
186 1
                $path
187 1
            ));
188
        }
189 1
190
        $output->writeln('<info>using seed base class</info> ' . $classes['$useClassName']);
191
        $output->writeln('<info>created</info> .' . str_replace(getcwd(), '', $filePath));
192
193
        return self::CODE_SUCCESS;
194
    }
195
}
196