Completed
Push — master ( 86bd3f...855ec7 )
by Nuno
42:09 queued 35:58
created

ImportCommand   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 46
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 14 2
A resultMessage() 0 6 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 Laravel\Scout\Searchable;
17
use Illuminate\Console\Command;
18
use Algolia\ScoutExtended\Algolia;
19
use Illuminate\Support\Collection;
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
     * Prints last imported object ID to console output, if any.
59
     *
60
     * @param \Illuminate\Support\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 ($models->count() > 0) {
68 1
            $last = ObjectIdEncrypter::encrypt($models->last());
69
70 1
            $this->line('<comment>Imported ['.$searchable.'] models up to ID:</comment> '.$last);
71
        }
72 1
    }
73
}
74