Completed
Push — master ( 2f124c...66b0c2 )
by Mohamed
11:36 queued 09:28
created

CreateCardCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 13
ccs 0
cts 13
cp 0
rs 9.4286
cc 1
eloc 11
nc 1
nop 0
crap 2
1
<?php
2
3
/*
4
 * This file is part of the Moo\FlashCardBundle package.
5
 *
6
 * (c) Mohamed Alsharaf <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Moo\FlashCardBundle\Command;
13
14
use Moo\FlashCardBundle\Entity;
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
20
/**
21
 * CreateCardCommand is a command line class for creating a new card.
22
 *
23
 * @author Mohamed Alsharaf <[email protected]>
24
 */
25
class CreateCardCommand extends AbstractCommand
26
{
27
    /**
28
     * An instance of card entity
29
     *
30
     * @var Entity\Card
31
     */
32
    protected $entity;
33
34
    /**
35
     * Get a card entity
36
     *
37
     * @return Entity\Card
38
     */
39
    protected function getEntity()
40
    {
41
        if (null === $this->entity) {
42
            $this->entity = new Entity\Card();
43
        }
44
45
        return $this->entity;
46
    }
47
48
    /**
49
     * Command configuration
50
     * Create a new card
51
     *
52
     * @return void
53
     */
54
    protected function configure()
55
    {
56
        $this
57
            ->setName('flashcard:card:create')
58
            ->setDescription('Create a card')
59
            ->addArgument('title', InputArgument::REQUIRED, 'The title of the card.')
60
            ->addArgument('content', InputArgument::REQUIRED, 'The content of the card.')
61
            ->addArgument('category', InputArgument::REQUIRED, 'The category ID the card is belong to.')
62
            ->addArgument('keywords', InputArgument::OPTIONAL, 'Comma seperated keywords for the metadata tag.', null)
63
            ->addArgument('description', InputArgument::OPTIONAL, 'The metadata description.', null)
64
            ->addArgument('slug', InputArgument::OPTIONAL, 'The url slug of the card.', null)
65
            ->addOption('active', null, InputOption::VALUE_NONE, 'If set, the card is going to be active.');
66
    }
67
68
    /**
69
     * Enable interaction
70
     *
71
     * @param \Symfony\Component\Console\Input\InputInterface   $input
72
     * @param \Symfony\Component\Console\Output\OutputInterface $output
73
     */
74
    protected function interact(InputInterface $input, OutputInterface $output)
75
    {
76 View Code Duplication
        if (!$input->getArgument('title')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
            $value = $this->getHelper('dialog')->askAndValidate(
78
                $output,
79
                'Please enter (Title): ',
80
                [$this, 'validateTitle'],
81
                1
82
            );
83
            $input->setArgument('title', $value);
84
        }
85
86 View Code Duplication
        if (!$input->getArgument('content')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
87
            $value = $this->getHelper('dialog')->askAndValidate(
88
                $output,
89
                'Please enter (Content): ',
90
                [$this, 'validateContent'],
91
                1
92
            );
93
            $input->setArgument('content', $value);
94
        }
95
96 View Code Duplication
        if (!$input->getArgument('category')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
97
            $value = $this->getHelper('dialog')->askAndValidate(
98
                $output,
99
                'Please enter (Category ID): ',
100
                [$this, 'validateCategory'],
101
                1
102
            );
103
            $input->setArgument('category', $value);
104
        }
105
    }
106
107
    /**
108
     * Validate the card title
109
     *
110
     * @param string $value
111
     *
112
     * @return string
113
     *
114
     * @throws \Exception
115
     */
116 View Code Duplication
    public function validateTitle($value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
117
    {
118
        $this->getEntity()->setTitle($value);
119
120
        $error = $this->validate($this->entity, 'title');
121
        if ($error !== true) {
122
            throw new \InvalidArgumentException($error);
123
        }
124
125
        return $value;
126
    }
127
128
    /**
129
     * Validate the card content
130
     *
131
     * @param string $value
132
     *
133
     * @return string
134
     *
135
     * @throws \Exception
136
     */
137 View Code Duplication
    public function validateContent($value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
138
    {
139
        $this->getEntity()->setContent($value);
140
141
        $error = $this->validate($this->entity, 'content');
142
        if ($error !== true) {
143
            throw new \InvalidArgumentException($error);
144
        }
145
146
        return $value;
147
    }
148
149
    /**
150
     * Validate the card category
151
     *
152
     * @param int $value
153
     *
154
     * @return Entity\Category
155
     *
156
     * @throws \Exception
157
     */
158
    public function validateCategory($value)
159
    {
160
        $category = $this->getRepository('category')->find($value);
161
        if (!$category) {
162
            throw new \InvalidArgumentException('The category ID is invalid.');
163
        }
164
165
        $this->getEntity()->setCategory($category);
166
167
        $error = $this->validate($this->entity, 'category');
168
        if ($error !== true) {
169
            throw new \InvalidArgumentException($error);
170
        }
171
172
        return $value;
173
    }
174
175
    /**
176
     * Execute the command line to create a new card.
177
     *
178
     * @param \Symfony\Component\Console\Input\InputInterface   $input
179
     * @param \Symfony\Component\Console\Output\OutputInterface $output
180
     *
181
     * @return bool
182
     */
183
    protected function execute(InputInterface $input, OutputInterface $output)
184
    {
185
        // Setup card entity
186
        $card = $this->getEntity();
187
        $card->setCreated();
188
        $card->setTitle($input->getArgument('title'));
189
        $card->setContent($input->getArgument('content'));
190
        $card->setActive((boolean) $input->getOption('active'));
191
        $card->setMetaKeywords($input->getArgument('keywords'));
192
        $card->setMetaDescription($input->getArgument('description'));
193
        $card->setViews(0);
194
        if (!$input->isInteractive()) {
195
            $card->setCategory(
196
                $this->getRepository('category')->find($input->getArgument('category'))
197
            );
198
        }
199
        if (($slug = $input->getArgument('slug')) !== null) {
200
            $card->setSlug($slug);
201
        }
202
203
        // Valid category
204
        $errors = $this->getValidator()->validate($card);
205
        if (count($errors) > 0) {
206
            foreach ($errors as $error) {
207
                $this->error($output, $error);
208
            }
209
210
            return 1;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return 1; (integer) is incompatible with the return type documented by Moo\FlashCardBundle\Comm...ateCardCommand::execute of type boolean.

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...
211
        }
212
213
        // Insert category into the database
214
        $em = $this->getDoctrine()->getManager();
215
        $em->persist($card);
216
        $em->flush();
217
218
        return $this->success($output, 'Voila... You have created a new card.');
219
    }
220
}
221