Passed
Pull Request — main (#11)
by Stefano
01:16
created

ImportCsvCommand::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * Chatlas BEdita plugin
6
 *
7
 * Copyright 2023 Atlas Srl
8
 */
9
namespace BEdita\Chatlas\Command;
10
11
use BEdita\Chatlas\Client\ChatlasClient;
12
use BEdita\Chatlas\Utility\ReadCSVTrait;
13
use BEdita\Core\Model\Table\RolesTable;
14
use BEdita\Core\Model\Table\UsersTable;
15
use BEdita\Core\Utility\LoggedUser;
16
use Cake\Command\Command;
17
use Cake\Console\Arguments;
18
use Cake\Console\ConsoleIo;
19
use Cake\Console\ConsoleOptionParser;
20
use Cake\Log\LogTrait;
21
use Cake\Utility\Hash;
22
23
/**
24
 * Import CSV and create questions or documents
25
 *
26
 * @property \BEdita\Core\Model\Table\ObjectsTable $Collections
27
 */
28
class ImportCsvCommand extends Command
29
{
30
    use LogTrait;
31
    use ReadCSVTrait;
32
33
    /**
34
     * Chatlas API client
35
     *
36
     * @var \BEdita\Chatlas\Client\ChatlasClient
37
     */
38
    protected ChatlasClient $chatlas;
39
40
    /**
41
     * @inheritDoc
42
     */
43
    public $defaultTable = 'Collections';
44
45
    /**
46
     * @inheritDoc
47
     */
48
    protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
49
    {
50
        return $parser->addOption('file', [
51
                'help' => 'Path of CSV file to import',
52
                'short' => 'f',
53
                'required' => true,
54
            ])
55
            ->addOption('type', [
56
                'help' => 'Type of object to import: documents or questions',
57
                'short' => 't',
58
                'default' => 'documents',
59
                'choices' => ['documents', 'questions'],
60
                'required' => true,
61
            ])
62
            ->addOption('collection', [
63
                'help' => 'Collection used to index, ID or unique name',
64
                'short' => 'c',
65
                'required' => true,
66
            ]);
67
    }
68
69
    /**
70
     * @inheritDoc
71
     */
72
    public function initialize(): void
73
    {
74
        $this->chatlas = new ChatlasClient();
75
    }
76
77
    /**
78
     * @inheritDoc
79
     */
80
    public function execute(Arguments $args, ConsoleIo $io)
81
    {
82
        $filepath = $args->getOption('file');
83
        if (!file_exists($filepath)) {
84
            $io->abort(sprintf('File not found: %s', $filepath));
85
        }
86
87
        $name = $args->getOption('collection');
88
        $response = $this->chatlas->get('/collections', compact('name'));
89
        $collectionId = Hash::get($response->getJson(), '0.cmetadata.id');
90
        if (empty($collectionId)) {
91
            $io->abort(sprintf('Collection not found: %s', $name));
92
        }
93
        $collection = $this->Collections->get($collectionId);
94
        $this->readCSVFile($filepath);
95
        $Table = $this->fetchTable($args->getOption('type'));
96
        $entities = [];
97
        LoggedUser::setUser(['id' => UsersTable::ADMIN_USER, 'roles' => [['id' => RolesTable::ADMIN_ROLE]]]);
98
        foreach ($this->csvData as $item) {
99
            $item['status'] = 'on';
100
            $entity = $Table->newEntity($item);
101
            $entities[] = $Table->saveOrFail($entity);
102
        }
103
        $this->Collections->addRelated($collection, 'has_documents', $entities);
104
105
        $io->out('Done');
106
107
        return null;
108
    }
109
}
110