Completed
Push — master ( 5ee4c9...308b6a )
by Antonio
05:05
created

UserCreateService   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 7
dl 0
loc 56
ccs 0
cts 34
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B run() 0 37 5
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Service;
13
14
use Da\User\Contracts\ServiceInterface;
15
use Da\User\Event\UserEvent;
16
use Da\User\Helper\SecurityHelper;
17
use Da\User\Model\User;
18
use Exception;
19
use yii\base\InvalidCallException;
20
use yii\log\Logger;
21
22
class UserCreateService implements ServiceInterface
23
{
24
    protected $model;
25
    protected $securityHelper;
26
    protected $mailService;
27
    protected $logger;
28
29
    public function __construct(User $model, MailService $mailService, SecurityHelper $securityHelper, Logger $logger)
30
    {
31
        $this->model = $model;
32
        $this->mailService = $mailService;
33
        $this->securityHelper = $securityHelper;
34
        $this->logger = $logger;
35
    }
36
37
    /**
38
     * @return bool
39
     */
40
    public function run()
41
    {
42
        $model = $this->model;
43
44
        if ($model->getIsNewRecord() === false) {
45
            throw new InvalidCallException('Cannot create a new user from an existing one.');
46
        }
47
48
        $transaction = $model->getDb()->beginTransaction();
49
50
        try {
51
            $model->confirmed_at = time();
52
            $model->password = !empty($model->password)
53
                ? $model->password
54
                : $this->securityHelper->generatePassword(8);
55
56
            $model->trigger(UserEvent::EVENT_BEFORE_CREATE);
57
58
            if (!$model->save()) {
59
                $transaction->rollBack();
60
61
                return false;
62
            }
63
64
            $model->trigger(UserEvent::EVENT_AFTER_CREATE);
65
66
            $this->mailService->run();
67
            $transaction->commit();
68
69
            return true;
70
        } catch (Exception $e) {
71
            $transaction->rollBack();
72
            $this->logger->log($e->getMessage(), Logger::LEVEL_ERROR);
73
74
            return false;
75
        }
76
    }
77
}
78