ImportCommand::handle()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 2
b 0
f 0
nc 2
nop 2
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * This file is part of Scout Extended.
7
 *
8
 * (c) Algolia Team <[email protected]>
9
 *
10
 *  For the full copyright and license information, please view the LICENSE
11
 *  file that was distributed with this source code.
12
 */
13
14
namespace Algolia\ScoutExtended\Console\Commands;
15
16
use Algolia\ScoutExtended\Helpers\SearchableFinder;
17
use Algolia\ScoutExtended\Searchable\ObjectIdEncrypter;
18
use Illuminate\Console\Command;
19
use Illuminate\Contracts\Events\Dispatcher;
20
use Illuminate\Support\Collection;
21
use Laravel\Scout\Events\ModelsImported;
22
23
final class ImportCommand extends Command
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    protected $signature = 'scout:import {searchable? : The name of the searchable}';
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    protected $description = 'Import the given searchable into the search index';
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 1
    public function handle(Dispatcher $events, SearchableFinder $searchableFinder): void
39
    {
40 1
        foreach ($searchableFinder->fromCommand($this) as $searchable) {
41 1
            $this->call('scout:flush', ['searchable' => $searchable]);
42
43
            $events->listen(ModelsImported::class, function ($event) use ($searchable) {
44 1
                $this->resultMessage($event->models, $searchable);
45 1
            });
46
47 1
            $searchable::makeAllSearchable();
48
49 1
            $events->forget(ModelsImported::class);
50
51 1
            $this->output->success('All ['.$searchable.'] records have been imported.');
52
        }
53 1
    }
54
55
    /**
56
     * Prints last imported object ID to console output, if any.
57
     *
58
     * @param \Illuminate\Support\Collection $models
59
     * @param string $searchable
60
     *
61
     * @return void
62
     */
63 1
    private function resultMessage(Collection $models, string $searchable): void
64
    {
65 1
        if ($models->count() > 0) {
66 1
            $last = ObjectIdEncrypter::encrypt($models->last());
67
68 1
            $this->line('<comment>Imported ['.$searchable.'] models up to ID:</comment> '.$last);
69
        }
70 1
    }
71
}
72