Completed
Push — master ( b6c757...4b91d2 )
by Nelson J
03:52
created

SoundcloudFacade   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 194
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.19%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 2
dl 0
loc 194
ccs 81
cts 86
cp 0.9419
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getAuthUrl() 0 17 1
A userCredentials() 0 19 1
A codeForToken() 0 19 1
A refreshAccessToken() 0 20 2
B setAuthData() 0 12 5
A download() 0 13 2
A upload() 0 20 3
A getCurlFile() 0 8 2
1
<?php
2
3
namespace Njasm\Soundcloud;
4
5
use Njasm\Soundcloud\Soundcloud;
6
7
/**
8
 * SoundCloud API wrapper in PHP
9
 *
10
 * @author      Nelson J Morais <[email protected]>
11
 * @copyright   2014 Nelson J Morais <[email protected]>
12
 * @license     http://www.opensource.org/licenses/mit-license.php MIT
13
 * @link        http://github.com/njasm/soundcloud
14
 * @package     Njasm\Soundcloud
15
 */
16
17
class SoundcloudFacade extends Soundcloud
18
{   
19
    /**
20
     * Get the authorization url for your users.
21
     * 
22
     * @param array $params key => value pair, of params to be sent to the /connect endpoint.
23
     * @return string The URL
24
     */
25 1
    public function getAuthUrl(array $params = array())
26
    {
27
        $defaultParams = array(
28 1
            'client_id'     => $this->auth->getClientID(),
29 1
            'scope'         => 'non-expiring',
30 1
            'display'       => 'popup',
31 1
            'response_type' => 'code',
32 1
            'redirect_uri'  => $this->auth->getAuthUrlCallback(),
33
            'state'         => ''
34 1
        );
35
        
36 1
        $params = array_merge($defaultParams, $params);
37 1
        $resource = $this->make('ResourceInterface', array('get', '/connect', $params));
38 1
        $url = $this->make('UrlBuilderInterface', array($resource, 'www'));
39
        
40 1
        return $url->getUrl();
41
    }
42
    
43
    /**
44
     * Request for a valid access token via User Credential Flow
45
     * 
46
     * @param string $username user username
47
     * @param string $password user password
48
     * @return \Njasm\Soundcloud\Request\ResponseInterface
49
     */
50 1
    public function userCredentials($username, $password)
51
    {
52
        $defaultParams = array(
53 1
            'grant_type'    => 'password',
54 1
            'scope'         => 'non-expiring',
55 1
            'username'      => $username,
56
            'password'      => $password
57 1
        );
58
        
59 1
        $params = $this->mergeAuthParams($defaultParams, true);
60 1
        $response = $this->post('/oauth2/token', $params)->asJson()
0 ignored issues
show
Deprecated Code introduced by
The method Njasm\Soundcloud\Soundcloud::asJson() has been deprecated with message: Soundcloud does not support XML responses anymore and calling this method will be redundant.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
61 1
            ->request(array(
62 1
                CURLOPT_FOLLOWLOCATION => true,
63 1
                CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded')
64 1
            ))->bodyObject();
65 1
        $this->setAuthData($response);
66
67 1
        return $this->response;
68
    }
69
    
70
    /**
71
     * Second step in user authorization. 
72
     * Exchange code for token
73
     * 
74
     * @param string $code the code received to exchange for token
75
     * @param array $params 
76
     * @return \Njasm\Soundcloud\Request\ResponseInterface
77
     */
78 1
    public function codeForToken($code, array $params = array())
79
    {
80
        $defaultParams = array(
81 1
            'redirect_uri'  => $this->auth->getAuthUrlCallback(),
82 1
            'grant_type'    => 'authorization_code',
83
            'code'          => $code
84 1
        );
85
        
86 1
        $mergedParams = array_merge($defaultParams, $params);
87 1
        $finalParams = $this->mergeAuthParams($mergedParams, true);
88 1
        $response = $this->post('/oauth2/token', $finalParams)->asJson()
0 ignored issues
show
Deprecated Code introduced by
The method Njasm\Soundcloud\Soundcloud::asJson() has been deprecated with message: Soundcloud does not support XML responses anymore and calling this method will be redundant.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
89 1
            ->request(array(
90 1
                CURLOPT_FOLLOWLOCATION => true,
91 1
                CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded')
92 1
            ))->bodyObject();
93 1
        $this->setAuthData($response);
94
        
95 1
        return $this->response;
96
    }
97
    
98
    /**
99
     * Refresh Auth access token.
100
     * 
101
     * @param string|null $refreshToken the refresh token to send to soundcloud. if null, the default Auth object
102
     *                                  refresh token will be used.
103
     * @param array $params 
104
     * @return \Njasm\Soundcloud\Request\ResponseInterface
105
     */    
106 1
    public function refreshAccessToken($refreshToken = null, array $params = array())
107
    {
108
        $defaultParams = array(
109 1
            'redirect_uri'  => $this->auth->getAuthUrlCallback(),
110 1
            'client_id'     => $this->auth->getClientID(),
111 1
            'client_secret' => $this->auth->getClientSecret(),
112 1
            'grant_type'    => 'refresh_token',
113 1
            'refresh_token' => ($refreshToken) ?: $this->auth->getRefreshToken()
114 1
        );
115
        
116 1
        $finalParams = array_merge($defaultParams, $params);
117 1
        $response = $this->post('/oauth2/token', $finalParams)->asJson()
0 ignored issues
show
Deprecated Code introduced by
The method Njasm\Soundcloud\Soundcloud::asJson() has been deprecated with message: Soundcloud does not support XML responses anymore and calling this method will be redundant.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
118 1
            ->request(array(
119 1
                CURLOPT_FOLLOWLOCATION => true,
120 1
                CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded')
121 1
            ))->bodyObject();
122 1
        $this->setAuthData($response);
123
        
124 1
        return $this->response;
125
    }
126
    
127
    /**
128
     * Sets OAuth data received from Soundcloud into Auth object.
129
     * 
130
     * @param \stdClass $response
131
     * @return void
132
     */
133 3
    protected function setAuthData($response)
134
    {
135 3
        $accessToken    = isset($response->access_token) ? $response->access_token : null;
136 3
        $scope          = isset($response->scope) ? $response->scope : null;
137 3
        $expires        = isset($response->expires_in) ? $response->expires_in : null;
138 3
        $refreshToken   = isset($response->refresh_token) ? $response->refresh_token : null;
139
140 3
        $this->auth->setToken($accessToken);
141 3
        $this->auth->setScope($scope);
142 3
        $this->auth->setExpires($expires);
143 3
        $this->auth->setRefreshToken($refreshToken);
144 3
    }
145
    
146
    /**
147
     * Download a track from soundcloud.
148
     * 
149
     * @param integer track ID.
150
     * @param boolean $download if we should follow location and download the media file to an in-memory variable 
151
     *                          accessible on the Response::bodyRaw() method, or return the Response object with the
152
     *                          location header with the direct URL.
153
     * @return \Njasm\Soundcloud\Request\ResponseInterface
154
     */
155 1
    public function download($trackID, $download = false)
156
    {
157 1
        $path = '/tracks/' . intval($trackID) . '/download';
158 1
        $this->get($path);
159
160 1
        if ($download === true) {
161 1
            $this->request(array(CURLOPT_FOLLOWLOCATION => true));
162 1
        } else {
163 1
            $this->request(array(CURLOPT_FOLLOWLOCATION => false));
164
        }
165
        
166 1
        return $this->response;        
167
    }
168
    
169
    /**
170
     * Upload a track to soundcloud.
171
     * 
172
     * @param string $trackPath the path to the media file to be uploaded to soundcloud.
173
     * @param array $params the params/info for the track that will be uploaded like, licence, name, etc.
174
     * @return \Njasm\Soundcloud\Request\ResponseInterface
175
     */
176 1
    public function upload($trackPath, array $params = array())
177
    {
178
        // loop to keep BC. params array can be
179
        // array('track[title]' => 'track name', ...) or
180
        // array('title' => 'track name', 'downloadable' => true, ...)
181 1
        foreach($params as $key => $value) {
182
            if (stripos($key, 'track[') !== false) {
183
                continue;
184
            }
185
            $params['track[' . $key . ']'] = $value;
186
            unset($params[$key]);
187 1
        }
188
189 1
        $file = $this->getCurlFile($trackPath);
190 1
        $params = array_merge($params, array('track[asset_data]' => $file));
191 1
        $finalParams = $this->mergeAuthParams($params);
192
        
193 1
        return $this->post('/tracks')->setParams($finalParams)
194 1
            ->request(array(CURLOPT_HTTPHEADER => array('Content-Type: multipart/form-data')));
195
    }
196
    
197
    /**
198
     * @param string $trackPath the full path for the media file to upload.
199
     * @return string|\CURLFile object if CurlFile class available or string prepended with @ for deprecated file upload.
200
     */
201 1
    private function getCurlFile($trackPath)
202
    {
203 1
        if (class_exists('CurlFile') === true) {
204 1
            return new \CURLFile($trackPath);
205
        }
206
        
207
        return "@" . $trackPath;
208
    }
209
    
210
}
211