Completed
Push — master ( 759a3c...0a5dc9 )
by Mohamed
04:06
created

CreateCardCommand   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 196
Duplicated Lines 25 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 20
c 3
b 0
f 0
lcom 1
cbo 6
dl 49
loc 196
ccs 78
cts 78
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getEntity() 0 8 2
A configure() 0 13 1
B interact() 27 32 4
A validateTitle() 11 11 2
A validateContent() 11 11 2
A validateCategory() 0 16 3
B execute() 0 37 6

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 6
    protected function getEntity()
40
    {
41 6
        if (null === $this->entity) {
42 6
            $this->entity = new Entity\Card();
43
        }
44
45 6
        return $this->entity;
46
    }
47
48
    /**
49
     * Command configuration
50
     * Create a new card
51
     *
52
     * @return void
53
     */
54 12
    protected function configure()
55
    {
56
        $this
57 12
            ->setName('flashcard:card:create')
58 12
            ->setDescription('Create a card')
59 12
            ->addArgument('title', InputArgument::REQUIRED, 'The title of the card.')
60 12
            ->addArgument('content', InputArgument::REQUIRED, 'The content of the card.')
61 12
            ->addArgument('category', InputArgument::REQUIRED, 'The category ID the card is belong to.')
62 12
            ->addArgument('keywords', InputArgument::OPTIONAL, 'Comma seperated keywords for the metadata tag.', null)
63 12
            ->addArgument('description', InputArgument::OPTIONAL, 'The metadata description.', null)
64 12
            ->addArgument('slug', InputArgument::OPTIONAL, 'The url slug of the card.', null)
65 12
            ->addOption('active', null, InputOption::VALUE_NONE, 'If set, the card is going to be active.');
66 12
    }
67
68
    /**
69
     * Enable interaction
70
     *
71
     * @param \Symfony\Component\Console\Input\InputInterface   $input
72
     * @param \Symfony\Component\Console\Output\OutputInterface $output
73
     */
74 4
    protected function interact(InputInterface $input, OutputInterface $output)
75
    {
76 4 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 4
            $value = $this->getHelper('dialog')->askAndValidate(
78
                $output,
79 4
                'Please enter (Title): ',
80 4
                [$this, 'validateTitle'],
81 4
                1
82
            );
83 3
            $input->setArgument('title', $value);
84
        }
85
86 3 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 3
            $value = $this->getHelper('dialog')->askAndValidate(
88
                $output,
89 3
                'Please enter (Content): ',
90 3
                [$this, 'validateContent'],
91 3
                1
92
            );
93 2
            $input->setArgument('content', $value);
94
        }
95
96 2 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 2
            $value = $this->getHelper('dialog')->askAndValidate(
98
                $output,
99 2
                'Please enter (Category ID): ',
100 2
                [$this, 'validateCategory'],
101 2
                1
102
            );
103 1
            $input->setArgument('category', $value);
104
        }
105 1
    }
106
107
    /**
108
     * Validate the card title
109
     *
110
     * @param string $value
111
     *
112
     * @return string
113
     *
114
     * @throws \Exception
115
     */
116 4 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 4
        $this->getEntity()->setTitle($value);
119
120 4
        $error = $this->validate($this->entity, 'title');
121 4
        if ($error !== true) {
122 1
            throw new \InvalidArgumentException($error);
123
        }
124
125 3
        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 3 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 3
        $this->getEntity()->setContent($value);
140
141 3
        $error = $this->validate($this->entity, 'content');
142 3
        if ($error !== true) {
143 1
            throw new \InvalidArgumentException($error);
144
        }
145
146 2
        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 2
    public function validateCategory($value)
159
    {
160 2
        $category = $this->getRepository('category')->find($value);
161 2
        if (!$category) {
162 1
            throw new \InvalidArgumentException('The category ID is invalid.');
163
        }
164
165 1
        $this->getEntity()->setCategory($category);
166
167 1
        $error = $this->validate($this->entity, 'category');
168 1
        if ($error !== true) {
169
            throw new \InvalidArgumentException($error);
170
        }
171
172 1
        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 3
    protected function execute(InputInterface $input, OutputInterface $output)
184
    {
185
        // Setup card entity
186 3
        $card = $this->getEntity();
187 3
        $card->setCreated();
188 3
        $card->setTitle($input->getArgument('title'));
189 3
        $card->setContent($input->getArgument('content'));
190 3
        $card->setActive((boolean) $input->getOption('active'));
191 3
        $card->setMetaKeywords($input->getArgument('keywords'));
192 3
        $card->setMetaDescription($input->getArgument('description'));
193 3
        $card->setViews(0);
194 3
        if (!$input->isInteractive() || !$card->getCategory()) {
195 3
            $card->setCategory(
196 3
                $this->getRepository('category')->find($input->getArgument('category'))
197
            );
198
        }
199 3
        if (($slug = $input->getArgument('slug')) !== null) {
200 1
            $card->setSlug($slug);
201
        }
202
203
        // Valid category
204 3
        $errors = $this->getValidator()->validate($card);
205 3
        if (count($errors) > 0) {
206 1
            foreach ($errors as $error) {
207 1
                $this->error($output, $error);
208
            }
209
210 1
            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 2
        $em = $this->getDoctrine()->getManager();
215 2
        $em->persist($card);
216 2
        $em->flush();
217
218 2
        return $this->success($output, 'Voila... You have created a new card.');
219
    }
220
}
221