Passed
Pull Request — main (#11)
by Stefano
12:48
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
 * BEdita, API-first content management framework
6
 * Copyright 2022 Atlas Srl, Chialab Srl
7
 *
8
 * This file is part of BEdita: you can redistribute it and/or modify
9
 * it under the terms of the GNU Lesser General Public License as published
10
 * by the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
14
 */
15
16
namespace BEdita\Chatlas\Command;
17
18
use BEdita\Chatlas\Client\ChatlasClient;
19
use BEdita\Chatlas\Utility\ReadCSVTrait;
20
use BEdita\Core\Model\Table\RolesTable;
21
use BEdita\Core\Model\Table\UsersTable;
22
use BEdita\Core\Utility\LoggedUser;
23
use Cake\Command\Command;
24
use Cake\Console\Arguments;
25
use Cake\Console\ConsoleIo;
26
use Cake\Console\ConsoleOptionParser;
27
use Cake\Log\LogTrait;
28
use Cake\Utility\Hash;
29
30
/**
31
 * Import CSV and create questions or documents
32
 */
33
class ImportCsvCommand extends Command
34
{
35
    use LogTrait;
36
    use ReadCSVTrait;
37
38
    /**
39
     * Chatlas API client
40
     *
41
     * @var \BEdita\Chatlas\Client\ChatlasClient
42
     */
43
    protected ChatlasClient $chatlas;
44
45
    /**
46
     * This object's default table alias.
47
     *
48
     * @var string|null
49
     */
50
    protected $defaultTable = 'Collections';
51
52
    /**
53
     * @inheritDoc
54
     */
55
    protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
56
    {
57
        return $parser->addOption('file', [
58
                'help' => 'Path of CSV file to import',
59
                'short' => 'f',
60
                'required' => true,
61
            ])
62
            ->addOption('type', [
63
                'help' => 'Type of object to import: documents or questions',
64
                'short' => 't',
65
                'default' => 'documents',
66
                'choices' => ['documents', 'questions'],
67
                'required' => true,
68
            ])
69
            ->addOption('collection', [
70
                'help' => 'Collection used to index, ID or unique name',
71
                'short' => 'c',
72
                'required' => true,
73
            ]);
74
    }
75
76
    /**
77
     * @inheritDoc
78
     */
79
    public function initialize(): void
80
    {
81
        $this->chatlas = new ChatlasClient();
82
    }
83
84
    /**
85
     * @inheritDoc
86
     */
87
    public function execute(Arguments $args, ConsoleIo $io)
88
    {
89
        $filepath = $args->getOption('file');
90
        if (!file_exists($filepath)) {
91
            $io->abort(sprintf('File not found: %s', $filepath));
92
        }
93
94
        $name = $args->getOption('collection');
95
        $response = $this->chatlas->get('/collections', compact('name'));
96
        $collectionId = Hash::get($response->getJson(), '0.cmetadata.id');
97
        if (empty($collectionId)) {
98
            $io->abort(sprintf('Collection ID not found: %s', $name));
99
        }
100
        $collection = $this->Collections->get($collectionId);
101
        $this->readCSVFile($filepath);
102
        $Table = $this->fetchTable($args->getOption('type'));
103
        $entities = [];
104
        LoggedUser::setUser(['id' => UsersTable::ADMIN_USER, 'roles' => [['id' => RolesTable::ADMIN_ROLE]]]);
105
        foreach ($this->csvData as $item) {
106
            $item['status'] = 'on';
107
            $entity = $Table->newEntity($item);
108
            $entities[] = $Table->saveOrFail($entity);
109
        }
110
        $this->Collections->addRelated($collection, 'has_documents', $entities);
111
112
        $io->out('Done');
113
114
        return null;
115
    }
116
}
117