Passed
Pull Request — master (#109)
by
unknown
04:29
created

ImportCommand   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 49
ccs 13
cts 14
cp 0.9286
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A resultMessage() 0 9 2
A handle() 0 14 2
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 Illuminate\Support\Collection;
17
use Laravel\Scout\Searchable;
18
use Illuminate\Console\Command;
19
use Algolia\ScoutExtended\Algolia;
20
use Laravel\Scout\Events\ModelsImported;
21
use Illuminate\Contracts\Events\Dispatcher;
22
use Algolia\ScoutExtended\Helpers\SearchableFinder;
23
use Algolia\ScoutExtended\Searchable\ObjectIdEncrypter;
24
25
final class ImportCommand extends Command
26
{
27
    /**
28
     * {@inheritdoc}
29
     */
30
    protected $signature = 'scout:import {searchable? : The name of the searchable}';
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    protected $description = 'Import the given searchable into the search index';
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 1
    public function handle(Dispatcher $events, SearchableFinder $searchableFinder): void
41
    {
42 1
        foreach ($searchableFinder->fromCommand($this) as $searchable) {
43 1
            $this->call('scout:flush', ['searchable' => $searchable]);
44
45
            $events->listen(ModelsImported::class, function ($event) use ($searchable) {
46 1
                $this->resultMessage($event->models, $searchable);
47 1
            });
48
49 1
            $searchable::makeAllSearchable();
50
51 1
            $events->forget(ModelsImported::class);
52
53 1
            $this->output->success('All ['.$searchable.'] records have been imported.');
54
        }
55 1
    }
56
57
    /**
58
     * Add last imported object ID (if available) to console output.
59
     *
60
     * @param Collection $models
61
     * @param string $searchable
62
     *
63
     * @return void
64
     */
65 1
    private function resultMessage(Collection $models, string $searchable): void
66
    {
67 1
        if (0 === $models->count()) {
68
            return;
69
        }
70
71 1
        $last = ObjectIdEncrypter::encrypt($models->last());
72
73 1
        $this->line('<comment>Imported [' . $searchable . '] models up to ID:</comment> ' . $last);
74 1
    }
75
}
76