Completed
Push — 1.4 ( ec73d9...094b7b )
by Rafał
14:01 queued 04:41
created

ImportUserCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 194
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 8

Importance

Changes 0
Metric Value
wmc 9
lcom 2
cbo 8
dl 0
loc 194
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A configure() 0 16 1
B execute() 0 60 7
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2018 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2018 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Command;
18
19
use FOS\UserBundle\Util\UserManipulator;
20
use JsonSchema\Validator;
21
use SWP\Bundle\CoreBundle\Model\UserInterface;
22
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
23
use Symfony\Component\Console\Input\InputArgument;
24
use Symfony\Component\Console\Input\InputInterface;
25
use Symfony\Component\Console\Output\OutputInterface;
26
use Symfony\Component\Finder\Finder;
27
28
class ImportUserCommand extends ContainerAwareCommand
29
{
30
    private $schema = <<<'JSON'
31
{
32
  "definitions": {},
33
  "$schema": "http://json-schema.org/draft-07/schema#",
34
  "$id": "http://example.com/root.json",
35
  "type": "object",
36
  "title": "The Root Schema",
37
  "required": [
38
    "display_name",
39
    "name",
40
    "email",
41
    "created",
42
    "is_staff",
43
    "is_active"
44
  ],
45
  "properties": {
46
    "display_name": {
47
      "$id": "#/properties/display_name",
48
      "type": "string",
49
      "title": "The Display_name Schema",
50
      "default": "",
51
      "examples": [
52
        "doe"
53
      ],
54
      "pattern": "^(.*)$"
55
    },
56
    "name": {
57
      "$id": "#/properties/name",
58
      "type": "object",
59
      "title": "The Name Schema",
60
      "required": [
61
        "first",
62
        "last"
63
      ],
64
      "properties": {
65
        "first": {
66
          "$id": "#/properties/name/properties/first",
67
          "type": "string",
68
          "title": "The First Schema",
69
          "default": "",
70
          "examples": [
71
            "John"
72
          ],
73
          "pattern": "^(.*)$"
74
        },
75
        "last": {
76
          "$id": "#/properties/name/properties/last",
77
          "type": "string",
78
          "title": "The Last Schema",
79
          "default": "",
80
          "examples": [
81
            "Doe"
82
          ],
83
          "pattern": "^(.*)$"
84
        }
85
      }
86
    },
87
    "email": {
88
      "$id": "#/properties/email",
89
      "type": "string",
90
      "title": "The Email Schema",
91
      "default": "",
92
      "examples": [
93
        "[email protected]"
94
      ],
95
      "pattern": "^(.*)$"
96
    },
97
    },
98
    "created": {
99
      "$id": "#/properties/created",
100
      "type": "string",
101
      "title": "The Created Schema",
102
      "default": "",
103
      "examples": [
104
        "2017-12-13T10:47:40"
105
      ],
106
      "pattern": "^(.*)$"
107
    },
108
    "is_staff": {
109
      "$id": "#/properties/is_staff",
110
      "type": "boolean",
111
      "title": "The Is_staff Schema",
112
      "default": false,
113
      "examples": [
114
        true
115
      ]
116
    },
117
    "is_active": {
118
      "$id": "#/properties/is_active",
119
      "type": "boolean",
120
      "title": "The Is_active Schema",
121
      "default": false,
122
      "examples": [
123
        true
124
      ]
125
    }
126
  }
127
}
128
JSON;
129
130
    protected static $defaultName = 'swp:import:user';
131
132
    /**
133
     * @var UserManipulator
134
     */
135
    private $userManipulator;
136
137
    public function __construct(UserManipulator $userManipulator)
138
    {
139
        parent::__construct();
140
141
        $this->userManipulator = $userManipulator;
142
    }
143
144
    protected function configure()
145
    {
146
        $this
147
            ->setName('swp:import:user')
148
            ->setDescription('Import users from JSON files.')
149
            ->addArgument('path', InputArgument::REQUIRED, 'Path to JSON files.')
150
            ->setHelp(<<<'EOT'
151
The <info>swp:import:user</info> command imports users data from JSON files:
152
153
  <info>php %command.full_name% /home/jack/users/</info>
154
155
  <info>path</info> argument is the absolute path to the directory with the JSON files.
156
157
EOT
158
            );
159
    }
160
161
    protected function execute(InputInterface $input, OutputInterface $output)
162
    {
163
        $path = $input->getArgument('path');
164
        $finder = new Finder();
165
        $finder->files()->in($path);
166
167
        $objectManager = $this->getContainer()->get('swp.object_manager.user');
168
        $userRepository = $this->getContainer()->get('swp.repository.user');
169
        $validator = new Validator();
170
171
        foreach ($finder as $file) {
172
            $filePath = $file->getRelativePath();
173
            $data = json_decode($file->getContents(), true);
174
            $validator->validate($data, $this->schema);
175
176
            if (!$validator->isValid()) {
177
                $output->writeln("<bg=red;options=bold>$filePath skipped. JSON not valid.</>");
178
179
                continue;
180
            }
181
182
            $userEmail = strtolower($data['email']);
183
            $userId = null;
184
185
            if (isset($data['id'])) {
186
                $userId = $data['id'];
187
            }
188
189
            $existingUser = $userRepository->findOneByEmail($userEmail);
190
191
            if (null !== $existingUser) {
192
                $output->writeln("<bg=yellow;options=bold>$userEmail already exists. Skipping.</>");
193
194
                continue;
195
            }
196
197
            /** @var UserInterface $user */
198
            $user = $this->userManipulator->create($data['display_name'], uniqid('', true), $userEmail, $data['is_active'], $data['is_staff']);
199
200
            if (null !== $userId) {
201
                $user->setId($userId);
202
            }
203
204
            $user->setFirstName($data['name']['first']);
205
            $user->setLastName($data['name']['last']);
206
            $user->setCreatedAt(new \DateTime($data['created']));
207
208
            if (!$data['is_staff']) {
209
                $user->addRole(UserInterface::ROLE_DEFAULT);
210
            }
211
212
            $objectManager->persist($user);
213
214
            $output->writeln("<bg=green;options=bold>$userEmail imported.</>");
215
        }
216
217
        $objectManager->flush();
218
219
        $output->writeln('<bg=green;options=bold>Done.</>');
220
    }
221
}
222