Completed
Push — master ( 19b2ae...0e0de4 )
by Nate
04:43
created

TokenQuery::init()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 14
cp 0
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
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\Patron;
18
use flipbox\patron\records\Token;
19
use League\OAuth2\Client\Token\AccessToken;
20
21
/**
22
 * @author Flipbox Factory <[email protected]>
23
 * @since 1.0.0
24
 */
25
class TokenQuery extends Query
26
{
27
    use TokenAttributesTrait,
28
        TokenEnvironmentAttributeTrait,
29
        TokenProviderAttributeTrait,
30
        PopulateObjectTrait,
31
        AuditAttributesTrait;
32
33
    /**
34
     * @inheritdoc
35
     */
36
    public function init()
37
    {
38
        $this->orderBy = [
39
            Token::tableName() . '.enabled' => SORT_DESC,
40
            Token::tableName() . '.dateExpires' => SORT_DESC,
41
            Token::tableName() . '.dateUpdated' => SORT_DESC
42
        ];
43
        $this->from = [Token::tableName() . ' ' . Token::tableAlias()];
44
        $this->select = [Token::tableAlias() . '.*'];
45
46
        parent::init();
47
48
        if ($this->environment === null) {
49
            $this->environment = Patron::getInstance()->getSettings()->getEnvironment();
50
        }
51
    }
52
53
    /*******************************************
54
     * RESULTS
55
     *******************************************/
56
57
    /**
58
     * @inheritdoc
59
     * @return AccessToken
60
     */
61
    public function one($db = null)
62
    {
63
        if (null === ($config = parent::one($db))) {
64
            return null;
65
        }
66
67
        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...
68
    }
69
70
    /**
71
     * @param array $config
72
     * @return AccessToken
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->applyEnvironmentConditions();
119
        $this->applyAuditAttributeConditions();
120
121
        return parent::prepare($builder);
122
    }
123
}
124