TokenQuery::init()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 9
cp 0
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/patron/license
6
 * @link       https://www.flipboxfactory.com/software/patron/
7
 */
8
9
namespace flipbox\patron\queries;
10
11
use craft\db\Query;
12
use craft\helpers\ArrayHelper;
13
use craft\helpers\DateTimeHelper;
14
use craft\helpers\Json;
15
use flipbox\craft\ember\queries\AuditAttributesTrait;
16
use flipbox\craft\ember\queries\PopulateObjectTrait;
17
use flipbox\patron\records\Token;
18
use League\OAuth2\Client\Token\AccessToken;
19
20
/**
21
 * @author Flipbox Factory <[email protected]>
22
 * @since 1.0.0
23
 */
24
class TokenQuery extends Query
25
{
26
    use TokenAttributesTrait,
27
        TokenProviderAttributeTrait,
28
        AuditAttributesTrait,
29
        PopulateObjectTrait;
30
31
    /**
32
     * @inheritdoc
33
     */
34
    public function init()
35
    {
36
        $this->orderBy = [
37
            Token::tableAlias() . '.enabled' => SORT_DESC,
38
            Token::tableAlias() . '.dateExpires' => SORT_DESC,
39
            Token::tableAlias() . '.dateUpdated' => SORT_DESC
40
        ];
41
        $this->from = [Token::tableName() . ' ' . Token::tableAlias()];
42
        $this->select = [Token::tableAlias() . '.*'];
43
44
        parent::init();
45
    }
46
47
48
    /*******************************************
49
     * RESULTS
50
     *******************************************/
51
52
    /**
53
     * @inheritdoc
54
     * @throws \Exception
55
     */
56
    public function one($db = null)
57
    {
58
        if (null === ($config = parent::one($db))) {
59
            return null;
60
        }
61
62
        return $this->createObject($config);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->createObject($config); (League\OAuth2\Client\Token\AccessToken) is incompatible with the return type declared by the interface yii\db\QueryInterface::one of type array|boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
63
    }
64
65
    /*******************************************
66
     * CREATE OBJECT
67
     *******************************************/
68
69
    /**
70
     * @param array $config
71
     * @return AccessToken
72
     * @throws \Exception
73
     */
74
    protected function createObject(array $config)
75
    {
76
        $config['revoked'] = !(bool)ArrayHelper::remove($config, 'enabled', true);
77
        $config['access_token'] = ArrayHelper::remove($config, 'accessToken');
78
        $config['refresh_token'] = ArrayHelper::remove($config, 'refreshToken');
79
        $config['resource_owner_id'] = ArrayHelper::remove($config, 'userId');
80
81
        // Handle DateTime expires
82
        if (false !== ($dateTime = DateTimeHelper::toDateTime(ArrayHelper::remove($config, 'dateExpires')))) {
83
            $config['expires'] = $this->calculateExpires($dateTime);
84
        }
85
86
        $values = ArrayHelper::remove($config, 'values', []);
87
        if (is_string($values)) {
88
            $values = Json::decodeIfJson($values);
89
        }
90
91
        $config = array_merge($config, (array)$values);
92
93
        return new AccessToken($config);
94
    }
95
96
    /**
97
     * @param \DateTime|null $dateTime
98
     * @return int|null
99
     */
100
    private function calculateExpires(\DateTime $dateTime = null)
101
    {
102
        return $dateTime ? ($dateTime->getTimestamp() - DateTimeHelper::currentUTCDateTime()->getTimestamp()) : null;
103
    }
104
105
106
    /*******************************************
107
     * PREPARE
108
     *******************************************/
109
110
    /**
111
     * @inheritdoc
112
     * @throws \ReflectionException
113
     */
114
    public function prepare($builder)
115
    {
116
        $this->applyTokenConditions();
117
        $this->applyProviderConditions();
118
        $this->applyAuditAttributeConditions();
119
120
        return parent::prepare($builder);
121
    }
122
}
123