Issues (29)

src/services/Api.php (7 issues)

1
<?php
2
/**
3
 * @link      https://dukt.net/facebook/
4
 * @copyright Copyright (c) Dukt
5
 * @license   https://github.com/dukt/facebook/blob/master/LICENSE.md
6
 */
7
8
namespace dukt\facebook\services;
9
10
use Craft;
11
use GuzzleHttp\Client;
12
use GuzzleHttp\Exception\RequestException;
13
use yii\base\Component;
14
use dukt\facebook\Plugin as Facebook;
15
16
/**
17
 * Class Api service
18
 *
19
 * @author Dukt <[email protected]>
20
 * @since  2.0
21
 */
22
class Api extends Component
23
{
24
    // Properties
25
    // =========================================================================
26
27
    /**
28
     * @var string
29
     */
30
    private $baseApiUrl = 'https://graph.facebook.com/';
31
32
    // Public Methods
33
    // =========================================================================
34
35
    /**
36
     * Performs an authenticated GET request on Facebook’s API
37
     *
38
     * @param null $uri
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $uri is correct as it would always require null to be passed?
Loading history...
39
     * @param null $query
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $query is correct as it would always require null to be passed?
Loading history...
40
     * @param null $headers
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $headers is correct as it would always require null to be passed?
Loading history...
41
     *
42
     * @return mixed
43
     * @throws \GuzzleHttp\Exception\GuzzleException
44
     */
45
    public function get($uri = null, $query = null, $headers = null)
46
    {
47
        $options = [];
48
        try {
49
            $client = $this->getClient();
50
51
            $options['query'] = ($query ?: []);
0 ignored issues
show
$query is of type null, thus it always evaluated to false.
Loading history...
52
53
            if ($headers) {
0 ignored issues
show
$headers is of type null, thus it always evaluated to false.
Loading history...
54
                $options['headers'] = $headers;
55
            }
56
57
            $response = $client->request('GET', $uri, $options);
58
59
            return json_decode($response->getBody(), true);
60
        } catch (RequestException $requestException) {
61
            Craft::error('Error requesting Facebook’s API: '.$requestException->getResponse()->getBody(), __METHOD__);
62
            throw $requestException;
63
        }
64
    }
65
66
    /**
67
     * @param       $facebookInsightsObjectId
68
     * @param array $options
69
     *
70
     * @return mixed
71
     * @throws \GuzzleHttp\Exception\GuzzleException
72
     */
73
    public function getInsights($facebookInsightsObjectId, array $options = [])
74
    {
75
        try {
76
            $pageAccessTokenResponse = $this->get('/'.$facebookInsightsObjectId, ['fields' => 'access_token']);
77
78
            if(empty($pageAccessTokenResponse['access_token'])) {
79
                throw new \Exception('Couldn’t retrieve page access token for '.$facebookInsightsObjectId);
80
            }
81
82
            $client = $this->getClient($pageAccessTokenResponse['access_token']);
83
84
            $response = $client->request('GET', '/'.$facebookInsightsObjectId.'/insights', $options);
85
86
            return json_decode($response->getBody(), true);
87
        } catch (RequestException $requestException) {
88
            Craft::error('Error requesting insights: '.$requestException->getResponse()->getBody(), __METHOD__);
89
            throw $requestException;
90
        }
91
    }
92
93
    // Private Methods
94
    // =========================================================================
95
96
    /**
97
     * Returns the Facebook API URL.
98
     *
99
     * @return string
100
     */
101
    private function getApiUrl()
102
    {
103
        $apiVersion = Facebook::$plugin->getSettings()->apiVersion;
104
105
        return $this->baseApiUrl.$apiVersion.'/';
106
    }
107
108
    /**
109
     * Return the authenticated Facebook OAuth client.
110
     *
111
     * @param null $accessToken
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $accessToken is correct as it would always require null to be passed?
Loading history...
112
     *
113
     * @return Client
114
     */
115
    private function getClient($accessToken = null): Client
116
    {
117
        if(!$accessToken) {
0 ignored issues
show
$accessToken is of type null, thus it always evaluated to false.
Loading history...
118
            $token = Facebook::$plugin->getOauth()->getToken();
119
            $accessToken = $token->getToken();
120
        }
121
122
        $headers = [];
123
124
        if ($accessToken) {
125
            $headers['Authorization'] = 'Bearer '.$accessToken;
126
        }
127
128
        $options = [
129
            'base_uri' => $this->getApiUrl(),
130
            'headers' => $headers
131
        ];
132
133
        return new Client($options);
134
    }
135
}
136