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
|
1 |
|
public function __construct(User $model, MailService $mailService, SecurityHelper $securityHelper, Logger $logger) |
30
|
|
|
{ |
31
|
1 |
|
$this->model = $model; |
32
|
1 |
|
$this->mailService = $mailService; |
33
|
1 |
|
$this->securityHelper = $securityHelper; |
34
|
1 |
|
$this->logger = $logger; |
35
|
1 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return bool |
39
|
|
|
*/ |
40
|
1 |
|
public function run() |
41
|
|
|
{ |
42
|
1 |
|
$model = $this->model; |
43
|
|
|
|
44
|
1 |
|
if ($model->getIsNewRecord() === false) { |
45
|
|
|
throw new InvalidCallException('Cannot create a new user from an existing one.'); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
$transaction = $model->getDb()->beginTransaction(); |
49
|
|
|
|
50
|
|
|
try { |
51
|
1 |
|
$model->confirmed_at = time(); |
52
|
1 |
|
$model->password = !empty($model->password) |
53
|
1 |
|
? $model->password |
54
|
1 |
|
: $this->securityHelper->generatePassword(8); |
55
|
|
|
|
56
|
1 |
|
$model->trigger(UserEvent::EVENT_BEFORE_CREATE); |
57
|
|
|
|
58
|
1 |
|
if (!$model->save()) { |
59
|
1 |
|
$transaction->rollBack(); |
60
|
|
|
|
61
|
1 |
|
return false; |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
$model->trigger(UserEvent::EVENT_AFTER_CREATE); |
65
|
|
|
|
66
|
1 |
|
$this->mailService->run(); |
67
|
1 |
|
$transaction->commit(); |
68
|
|
|
|
69
|
1 |
|
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
|
|
|
|