Completed
Push — master ( 8f8221...a2309d )
by Haridarshan
02:33
created

HelperFactory::createExceptionMessage()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 8
rs 9.2
cc 4
eloc 6
nc 8
nop 1
1
<?php
2
/**
3
 * The MIT License (MIT)
4
 * 
5
 * Copyright (c) 2016 Haridarshan Gorana
6
 * 
7
 * Permission is hereby granted, free of charge, to any person obtaining a copy
8
 * of this software and associated documentation files (the "Software"), to deal
9
 * in the Software without restriction, including without limitation the rights
10
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
 * copies of the Software, and to permit persons to whom the Software is
12
 * furnished to do so, subject to the following conditions:
13
 * 
14
 * The above copyright notice and this permission notice shall be included in all
15
 * copies or substantial portions of the Software.
16
 * 
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 *
25
 */
26
namespace Haridarshan\Instagram;
27
28
use GuzzleHttp\Client;
29
use GuzzleHttp\Exception\ClientException;
30
use GuzzleHttp\Psr7\Response;
31
use GuzzleHttp\Psr7\Stream;
32
use Psr\Http\Message\ResponseInterface;
33
use Haridarshan\Instagram\Exceptions\InstagramException;
34
use Haridarshan\Instagram\Exceptions\InstagramOAuthException;
35
use Haridarshan\Instagram\Exceptions\InstagramServerException;
36
37
/**
38
 * HelperFactory class
39
 * 
40
 * @library			instagram-php
41
 * @license 		https://opensource.org/licenses/MIT MIT
42
 * @link			http://github.com/haridarshan/instagram-php Class Documentation
43
 * @link			http://instagram.com/developer/ API Documentation
44
 * @author			Haridarshan Gorana 	<[email protected]>
45
 * @since			May 09, 2016
46
 * @copyright		Haridarshan Gorana
47
 * @version			2.2.2
48
 */
49
class HelperFactory
50
{
51
    /** @var HelperFactory The reference to *HelperFactory* instance of this class */
52
    private static $instance;
53
	
54
    /** @var Response|ResponseInterface $response */
55
    protected static $response;
56
    
57
    /** @var Stream $stream */
58
    protected static $stream;
59
    
60
    /** @var object $content */
61
    protected static $content;
62
    
63
    /** 
64
     * Returns the *HelperFactory* instance of this class.
65
     *
66
     * @return HelperFactory The *HelperFactory* instance.
67
     */
68
    public static function getInstance()
69
    {
70
        if (null === self::$instance) {
71
            self::$instance = new static();
72
        }
73
        
74
        return self::$instance;
75
    }
76
	
77
    /** 
78
     * Protected constructor to prevent creating a new instance of the
79
     * *HelperFactory* via the `new` operator from outside of this class.
80
     */
81
    protected function __construct()
82
    {
83
        // a factory constructor should never be invoked
84
    }
85
    
86
    /** 
87
     * Factory Client method to create \GuzzleHttp\Client object
88
	 * 
89
     * @param string $uri
90
	 * 
91
     * @return Client
92
     */
93
    public function client($uri)
94
    {
95
        return new Client([
96
            'base_uri' => $uri
97
        ]);
98
    }
99
	
100
    /**
101
	 * Sends request to Instagram Api Endpoints
102
	 * 
103
     * @param Client $client
104
     * @param string $endpoint
105
     * @param array|string $options
106
     * @param string $method
107
	 * 
108
     * @return Response
109
	 * 
110
     * @throws InstagramOAuthException|InstagramException
111
     */
112
    public function request(Client $client, $endpoint, $options, $method = 'GET')
113
    {
114
        try {
115
            return $client->request($method, $endpoint, [
116
                'form_params' => $options
117
            ]);
118
        } catch (ClientException $exception) {
119
            static::throwException(static::extractOriginalExceptionMessage($exception), $exception);
120
        }
121
    }
122
    
123
    /**
124
     * Create body for Guzzle client request
125
	 * 
126
     * @param array|null|string $options
127
     * @param string $method GET|POST
128
	 * 
129
     * @return string|mixed
130
     */
131
    protected static function createBody($options, $method)
132
    {
133
        return ('GET' !== $method) ? is_array($options) ? http_build_query($options) : ltrim($options, '&') : null;
134
    }
135
    
136
    /*
137
     * Method to extract all exceptions for Guzzle ClientException
138
	 * 
139
     * @param ClientException $exception
140
	 * 
141
     * @return stdClass
142
	 * 
143
	 * @throws InstagramServerException
144
     */
145
    protected static function extractOriginalExceptionMessage(ClientException $exception)
146
    {
147
        self::$response = $exception->getResponse();
148
        self::$stream = self::$response->getBody();
149
        self::$content = self::$stream->getContents();
150
        if (!self::$content) {
151
            throw new InstagramServerException(
152
                $exception->getMessage(),
153
                $exception->getCode(),
154
                $exception
155
            );
156
        }
157
        return json_decode(self::$content);
158
    }
159
    
160
    /** 
161
	 * Throw required Exception 
162
	 * 
163
     * @param \stdClass $object
164
	 * @param ClientException $exMessage
165
	 * 
166
	 * @return void
167
	 *
168
     * @throws InstagramOAuthException|InstagramException
169
     */
170
    protected static function throwException(\stdClass $object, ClientException $exMessage)
171
    {
172
        $exception = static::createExceptionMessage($object);
173
        if (stripos($exception['error_type'], "oauth") !== false) {
174
            throw new InstagramOAuthException(
175
                json_encode(array("Type" => $exception['error_type'], "Message" => $exception['error_message'])),
176
                $exception['error_code'],
177
                $exMessage
178
            );
179
        }
180
        throw new InstagramException(
181
            json_encode(array("Type" => $exception['error_type'], "Message" => $exception['error_message'])),
182
            $exception['error_code'],
183
            $exMessage
184
        );
185
    }
186
	
187
    /**
188
	 * Creates Exception Message
189
	 * 
190
	 * @param \stdClass $object
191
	 * 
192
	 * @return array
193
	 */
194
    protected static function createExceptionMessage(\stdClass $object)
195
    {
196
        $message = array();		
197
        $message['error_type'] = isset($object->meta) ? $object->meta->error_type : $object->error_type;
198
        $message['error_message'] = isset($object->meta) ? $object->meta->error_message : $object->error_message;
199
        $message['error_code'] = isset($object->meta) ? $object->meta->code : $object->code;
200
        return $message;
201
    }
202
	
203
    /** 
204
     * Private clone method to prevent cloning of the instance of the
205
     * *HelperFactory* instance.
206
     *
207
     * @return void
208
     */
209
    private function __clone()
210
    {
211
        // a factory clone should never be invoked
212
    }
213
	
214
	/**
215
     * Private unserialize method to prevent unserializing of the *HelperFactory	*
216
     * instance.
217
     *
218
     * @return void
219
     */
220
    private function __wakeup()
221
    {
222
    }
223
}
224