Completed
Push — master ( c72a1f...5e0e31 )
by Christopher
01:10
created

SetupCommand   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 227
Duplicated Lines 9.69 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 7
dl 22
loc 227
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 18 3
A createDirectories() 0 10 3
A exportViews() 0 15 4
A buildController() 0 10 3
A exportController() 0 7 1
A compileControllerStub() 0 8 1
A registerRoutes() 0 10 2
B seed() 22 68 4

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
namespace Chriscreates\Blog\Console\Commands;
4
5
use Canvas\Post;
6
use Canvas\Tag;
7
use Canvas\Topic;
8
use Faker\Generator;
9
use Illuminate\Console\Command;
10
use Illuminate\Console\DetectsApplicationNamespace;
11
use Illuminate\Foundation\Auth\User;
12
use Illuminate\Support\Facades\Route;
13
use Illuminate\Support\Str;
14
use Ramsey\Uuid\Uuid;
15
16
class SetupCommand extends Command
17
{
18
    use DetectsApplicationNamespace;
19
20
    /**
21
     * The name and signature of the console command.
22
     *
23
     * @var string
24
     */
25
    protected $signature = 'canvas:setup {--data : Specifies that demo data should be seeded}';
26
27
    /**
28
     * The console command description.
29
     *
30
     * @var string
31
     */
32
    protected $description = 'Scaffold basic blog views and routes';
33
34
    /**
35
     * The views that need to be exported.
36
     *
37
     * @var array
38
     */
39
    protected $views = [
40
        'layouts/app.stub' => 'layouts/app.blade.php',
41
        'partials/navbar.stub' => 'partials/navbar.blade.php',
42
        'partials/styles.stub' => 'partials/styles.blade.php',
43
        'index.stub' => 'index.blade.php',
44
        'show.stub' => 'show.blade.php',
45
    ];
46
47
    /**
48
     * Execute the console command.
49
     *
50
     * @return void
51
     * @throws \Exception
52
     */
53
    public function handle()
54
    {
55
        $this->createDirectories();
56
        $this->exportViews();
57
        $this->buildController();
58
        $this->registerRoutes();
59
60
        // Optionally seed the database with demo data
61
        if ($this->option('data')) {
62
            if (User::find(1)) {
63
                $this->seed();
64
            } else {
65
                $this->error('No users found. Please create a user and re-run the setup.');
66
            }
67
        }
68
69
        $this->info('Setup complete. Head over to <comment>'.url('/blog').'</comment> to get started.');
70
    }
71
72
    /**
73
     * Create the view directories.
74
     *
75
     * @return void
76
     */
77
    private function createDirectories()
78
    {
79
        if ( ! is_dir($directory = resource_path('views/blog/layouts'))) {
80
            mkdir($directory, 0755, true);
81
        }
82
83
        if ( ! is_dir($directory = resource_path('views/blog/partials'))) {
84
            mkdir($directory, 0755, true);
85
        }
86
    }
87
88
    /**
89
     * Export the default blog views.
90
     *
91
     * @return void
92
     */
93
    private function exportViews()
94
    {
95
        foreach ($this->views as $key => $value) {
96
            if (file_exists($view = resource_path('views/blog/'.$value))) {
97
                if ( ! $this->confirm("The [blog/{$value}] view already exists. Do you want to replace it?")) {
98
                    continue;
99
                }
100
            }
101
102
            copy(
103
                sprintf('%s/resources/stubs/views/blog/%s', dirname(__DIR__, 2), $key),
104
                $view
105
            );
106
        }
107
    }
108
109
    /**
110
     * Build the new controller.
111
     *
112
     * @return void
113
     */
114
    private function buildController()
115
    {
116
        if ( ! file_exists($controller = app_path('Http/Controllers/BlogController.php'))) {
117
            $this->exportController();
118
        } else {
119
            if ($this->confirm('The [Http/Controllers/BlogController.php] already exists. Do you want to replace it?')) {
120
                $this->exportController();
121
            }
122
        }
123
    }
124
125
    /**
126
     * Export the new controller.
127
     *
128
     * @return void
129
     */
130
    private function exportController()
131
    {
132
        file_put_contents(
133
            app_path('Http/Controllers/BlogController.php'),
134
            $this->compileControllerStub()
135
        );
136
    }
137
138
    /**
139
     * Compile the default controller stub.
140
     *
141
     * @return string
142
     */
143
    private function compileControllerStub()
144
    {
145
        return str_replace(
146
            '{{namespace}}',
147
            $this->getAppNamespace(),
148
            file_get_contents(dirname(__DIR__, 2).'/resources/stubs/controllers/BlogController.stub')
149
        );
150
    }
151
152
    /**
153
     * Register the new routes.
154
     *
155
     * @return void
156
     */
157
    private function registerRoutes()
158
    {
159
        if ( ! Route::has('blog.index')) {
160
            file_put_contents(
161
                base_path('routes/web.php'),
162
                file_get_contents(dirname(__DIR__, 2).'/resources/stubs/routes.stub'),
163
                FILE_APPEND
164
            );
165
        }
166
    }
167
168
    /**
169
     * Run the demo data seeder.
170
     *
171
     * @return void
172
     * @throws \Exception
173
     */
174
    private function seed()
175
    {
176
        /** @var \Faker\Generator $faker */
177
        $faker = resolve(Generator::class);
178
179
        // Seed the posts data
180
        $posts = collect();
181
        $post_counter = 1;
182
        while ($post_counter < 6) {
183
            $title = $faker->words(3, true);
184
            $post_id = Uuid::uuid4();
185
            $post = Post::create([
186
                'id' => $post_id,
187
                'slug' => "post-{$post_id}",
188
                'title' => ucfirst($title),
189
                'summary' => $faker->sentence,
190
                'body' => $faker->realText(500),
191
                'published_at' => now()->toDateTimeString(),
192
                'featured_image' => 'https://source.unsplash.com/random/640x480',
193
                'featured_image_caption' => ucfirst($title),
194
                'user_id' => User::first()->id,
195
            ]);
196
197
            $posts->push($post);
198
            $post_counter++;
199
        }
200
201
        // Seed the tags data
202
        $tags = collect();
203
        $tag_counter = 1;
204 View Code Duplication
        while ($tag_counter < 10) {
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...
205
            $name = ucfirst($faker->words(2, true));
206
            $tag = Tag::create([
207
                'id' => Uuid::uuid4(),
208
                'slug' => Str::slug($name),
209
                'name' => $name,
210
            ]);
211
212
            $tags->push($tag);
213
            $tag_counter++;
214
        }
215
216
        // Seed the topics data
217
        $topics = collect();
218
        $topic_counter = 1;
219 View Code Duplication
        while ($topic_counter < 10) {
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...
220
            $name = ucfirst($faker->words(2, true));
221
            $topic = Topic::create([
222
                'id' => Uuid::uuid4(),
223
                'slug' => Str::slug($name),
224
                'name' => $name,
225
            ]);
226
227
            $topics->push($topic);
228
            $topic_counter++;
229
        }
230
231
        // Associate tags and topics with the posts
232
        $posts->each(function ($post) use ($tags, $topics) {
233
            $post->tags()->attach(
234
                $tags->random(rand(1, 3))->pluck('id')->toArray()
235
            );
236
237
            $post->topic()->attach(
238
                $topics->random(1)->pluck('id')->toArray()
239
            );
240
        });
241
    }
242
}
243