Client::setPackage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 4
rs 10
c 1
b 0
f 1
ccs 3
cts 3
cp 1
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
/*
3
 * Copyright 2015 Alexey Maslov <[email protected]>
4
 *
5
 * Licensed under the Apache License, Version 2.0 (the "License");
6
 * you may not use this file except in compliance with the License.
7
 * You may obtain a copy of the License at
8
 *
9
 * http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
18
namespace alxmsl\Google\AndroidPublisher\Purchases;
19
20
use alxmsl\Google\AndroidPublisher\Exception\ErrorException;
21
use alxmsl\Google\AndroidPublisher\Exception\InvalidCredentialsException;
22
use alxmsl\Google\AndroidPublisher\Exception\NotFoundException;
23
use alxmsl\Google\AndroidPublisher\Purchases\Products\Resource as ProductResource;
24
use alxmsl\Google\AndroidPublisher\Purchases\Subscriptions\Resource as SubscriptionResource;
25
use alxmsl\Google\OAuth2\WebServerApplication;
26
use alxmsl\Network\Exception\HttpClientErrorCodeException;
27
use alxmsl\Network\Exception\HttpServerErrorCodeException;
28
use UnexpectedValueException;
29
use RuntimeException;
30
31
/**
32
 * Class for support GooglePlay Purchases API
33
 * @author alxmsl
34
 */
35
class Client extends WebServerApplication implements ClientInterface {
36
    /**
37
     * API client code
38
     */
39
    const TYPE_PRODUCTS      = 0,
40
          TYPE_SUBSCRIPTIONS = 1;
41
42
    /**
43
     * Google Purchases API uri parts
44
     */
45
    const URI_PRODUCTS      = 'products',
46
          URI_SUBSCRIPTIONS = 'subscriptions';
47
48
    /**
49
     * GooglePlay Purchases Products API endpoint
50
     */
51
    const ENDPOINT_PURCHASES = 'https://www.googleapis.com/androidpublisher/v2';
52
53
    /**
54
     * @var string package name
55
     */
56
    private $package = '';
57
58
    /**
59
     * @var string purchases type code
60
     */
61
    private $typeCode = self::TYPE_PRODUCTS;
62
63
    /**
64
     * @param string $package package name
65
     * @return $this
66
     */
67 1
    public function setPackage($package) {
68 1
        $this->package = (string) $package;
69 1
        return $this;
70
    }
71
72
    /**
73
     * @return string package name
74
     */
75 2
    public function getPackage() {
76 2
        return $this->package;
77
    }
78
79
    /**
80
     * @param int $typeCode client type code, Products or subscription
81
     */
82 2
    public function __construct($typeCode = self::TYPE_PRODUCTS) {
83 2
        $this->typeCode = (int) $typeCode;
0 ignored issues
show
Documentation Bug introduced by
The property $typeCode was declared of type string, but (int) $typeCode is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
84 2
    }
85
86
    /**
87
     * @inheritdoc
88
     */
89 1
    public function get($productId, $token) {
90 1
        $accessToken = $this->getAccessToken();
91 1
        if (!empty($accessToken)) {
92 1
            $Request = $this->getRequest(self::ENDPOINT_PURCHASES)
93 1
                ->addUrlField('applications', $this->getPackage())
94 1
                ->addUrlField('purchases', '')
95 1
                ->addUrlField($this->getPurchasesUri(), $productId)
96 1
                ->addUrlField('tokens', $token)
97 1
                ->addGetField('access_token', $accessToken);
98
            try {
99 1
                switch ($this->typeCode) {
100 1
                    case self::TYPE_PRODUCTS:
101
                        return ProductResource::initializeByString($Request->send());
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \alxmsl\Google\An...ring($Request->send()); (alxmsl\Google\AndroidPub...hases\Products\Resource) is incompatible with the return type declared by the interface alxmsl\Google\AndroidPub...es\ClientInterface::get of type resource.

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...
102 1
                    case self::TYPE_SUBSCRIPTIONS:
103
                        return SubscriptionResource::initializeByString($Request->send());
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \alxmsl\Google\An...ring($Request->send()); (alxmsl\Google\AndroidPub...\Subscriptions\Resource) is incompatible with the return type declared by the interface alxmsl\Google\AndroidPub...es\ClientInterface::get of type resource.

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...
104 1
                    default:
105 1
                        throw new RuntimeException(sprintf('type code %s not supported now', $this->typeCode));
106 1
                }
107 1
            } catch (HttpClientErrorCodeException $Ex) {
108
                switch ($Ex->getCode()) {
109
                    case 401:
110
                        throw InvalidCredentialsException::initializeByString($Ex->getMessage());
111
                    case 404:
112
                        throw NotFoundException::initializeByString($Ex->getMessage());
113
                    default:
114
                        throw ErrorException::initializeByString($Ex->getMessage());
115
                }
116 1
            } catch (HttpServerErrorCodeException $Ex) {
117
                throw ErrorException::initializeByString($Ex->getMessage());
118
            }
119
        } else {
120 1
            throw new UnexpectedValueException('access token is empty');
121
        }
122
    }
123
124
    /**
125
     * @return string purchases API uri string for client type
126
     */
127 1
    private function getPurchasesUri() {
128 1
        return $this->typeCode == self::TYPE_PRODUCTS
129 1
            ? self::URI_PRODUCTS
130 1
            : self::URI_SUBSCRIPTIONS;
131
    }
132
}
133