Completed
Pull Request — master (#1)
by Klochok
06:34
created

Service::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
/**
3
 * Library for confirmation tokens.
4
 *
5
 * @link      https://github.com/hiqdev/php-confirmator
6
 * @package   php-confirmator
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2017, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\yii2\confirmator;
12
13
use hiqdev\php\confirmator\ServiceInterface;
14
use hiqdev\php\confirmator\ServiceTrait;
15
use hiqdev\php\confirmator\StorageInterface;
16
use Yii;
17
use yii\helpers\Inflector;
18
19
class Service extends \yii\base\Component implements ServiceInterface
20
{
21
    use ServiceTrait;
22
23
    protected $_storage;
24
25
    public function __construct(StorageInterface $storage, $config = [])
26
    {
27
        parent::__construct($config);
28
        $this->storage = $storage;
29
    }
30
31
    public function setStorage($value)
32
    {
33
        $this->_storage = $value;
34
    }
35
36
    public function getStorage()
37
    {
38
        if (is_array($this->_storage)) {
39
            $config = $this->_storage;
40
            if (isset($config['path']) && is_string($config['path'])) {
41
                $config['path'] = Yii::getAlias($config['path']);
42
            }
43
            $this->_storage = Yii::createObject($config);
44
        }
45
46
        return $this->_storage;
47
    }
48
49
    public function mailToken($user, $action, array $data = [])
50
    {
51
        if (!$user) {
52
            return false;
53
        }
54
55
        if (Yii::$app->has('authManager')) {
56
            $auth = Yii::$app->authManager;
57
            if ($auth->getItem($action) && !$auth->checkAccess($user->id, $action)) {
58
                return false;
59
            }
60
        }
61
62
        $token = $this->issueToken(array_merge([
63
            'action'    => $action,
64
            'email'     => $user->email,
65
            'username'  => $user->username,
66
            'notAfter'  => '+ 3 days',
67
        ], $data));
68
69
        $view = lcfirst(Inflector::id2camel($action . '-token'));
70
71
        return Yii::$app->mailer->compose()
72
            ->renderHtmlBody($view, compact('user', 'token'))
73
            ->setTo([$user->email => $user->name])
74
            ->send();
75
    }
76
}
77