Completed
Push — master ( 1758f1...601966 )
by Felix
08:03
created

SearchConsole::getWebmastersService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace SchulzeFelix\SearchConsole;
4
5
use Google_Service_Webmasters_ApiDimensionFilter;
6
use Google_Service_Webmasters_ApiDimensionFilterGroup;
7
use Google_Service_Webmasters_SearchAnalyticsQueryRequest;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Traits\Macroable;
10
11
class SearchConsole
12
{
13
    /** @var SearchConsoleClient */
14
    protected $client;
15
16
    /**
17
     * @param SearchConsoleClient $client
18
     */
19
    public function __construct(SearchConsoleClient $client)
20
    {
21
        $this->client = $client;
22
    }
23
24
    /**
25
     * @param string $quotaUser
26
     *
27
     * @return $this
28
     */
29
    public function setQuotaUser(string $quotaUser)
30
    {
31
        $this->client->setQuotaUser($quotaUser);
32
33
        return $this;
34
    }
35
36
    /**
37
     * @param string $accessToken
38
     *
39
     * @return $this
40
     */
41
    public function setAccessToken(string $accessToken)
42
    {
43
        $this->client->setAccessToken($accessToken);
44
45
        return $this;
46
    }
47
48
    public function getSite(string $siteUrl)
49
    {
50
        $sites = $this->client->getWebmastersService()->sites;
51
52
        $siteInfo = $sites->get($siteUrl);
53
54
        $response = [
55
            'siteUrl' => $siteInfo->getSiteUrl(),
56
            'permissionLevel' => $siteInfo->getPermissionLevel(),
57
        ];
58
59
        return $response;
60
    }
61
62
    public function listSites()
63
    {
64
        $sites = $this->client->getWebmastersService()->sites;
65
        $siteList = $sites->listSites();
66
67
        $sitesCollection = new Collection();
68
        foreach ($siteList->getSiteEntry() as $site) {
69
            $sitesCollection->push([
70
                'siteUrl' => $site->siteUrl,
71
                'permissionLevel' => $site->permissionLevel
72
            ]);
73
        }
74
        $sitesCollection = $sitesCollection->sortBy('siteUrl');
75
76
        return $sitesCollection;
77
    }
78
79
    /**
80
     * Call the query method on the authenticated client.
81
     *
82
     * @param Period $period
83
     * @param array $dimensions
84
     * @param array $filters
85
     * @param int $rows
86
     * @param string $searchType
87
     * @return Collection
88
     */
89
    public function searchAnalyticsQuery(string $siteUrl, Period $period, array $dimensions = [], array $filters = [], int $rows = 1000, string $searchType = 'web')
90
    {
91
        $request = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
92
        $request->setStartDate($period->startDate->toDateString());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DateTime as the method toDateString() does only exist in the following sub-classes of DateTime: Carbon\Carbon. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
93
        $request->setEndDate($period->endDate->toDateString());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class DateTime as the method toDateString() does only exist in the following sub-classes of DateTime: Carbon\Carbon. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
94
        $request->setSearchType($searchType);
95
        $request->setDimensions($dimensions);
96
        $request = $this->applyFilters($request, $filters);
97
98
        return $this->client->performQuery($siteUrl, $rows, $request);
99
    }
100
101
    /*
102
     * Get the underlying Google_Service_Webmasters object. You can use this
103
     * to basically call anything on the Google Search Console API.
104
     */
105
    public function getWebmastersService(): \Google_Service_Webmasters
106
    {
107
        return $this->client->getWebmastersService();
108
    }
109
110
    private function applyFilters(Google_Service_Webmasters_SearchAnalyticsQueryRequest $request, $filters)
111
    {
112
        $filterArray = [];
113
        foreach ($filters as $filterItem) {
114
            if (strlen($filterItem['expression']) === 0) {
115
                continue;
116
            }
117
            $filter = new Google_Service_Webmasters_ApiDimensionFilter();
118
            $filter->setDimension($filterItem['dimension']);
119
            $filter->setOperator($filterItem['operator']);
120
            $filter->setExpression($filterItem['expression']);
121
            $filterArray[] = $filter;
122
        }
123
124
        if (count($filterArray)) {
125
            $filtergroup = new Google_Service_Webmasters_ApiDimensionFilterGroup();
126
            $filtergroup->setFilters($filterArray);
127
            $request->setDimensionFilterGroups([$filtergroup]);
128
        }
129
130
        return $request;
131
    }
132
133
}