Completed
Push — master ( c2e1e4...22c8ee )
by
unknown
04:32
created

CurlLogger::normalizeFileParam()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 1
nop 1
crap 12
1
<?php
2
/**
3
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
4
 *
5
 * You are hereby granted a non-exclusive, worldwide, royalty-free license to
6
 * use, copy, modify, and distribute this software in source code or binary
7
 * form for use in connection with the web services and APIs provided by
8
 * Facebook.
9
 *
10
 * As with any software that integrates with the Facebook platform, your use
11
 * of this software is subject to the Facebook Developer Principles and
12
 * Policies [http://developers.facebook.com/policy/]. This copyright notice
13
 * shall be included in all copies or substantial portions of the software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21
 * DEALINGS IN THE SOFTWARE.
22
 *
23
 */
24
25
namespace FacebookAds\Logger;
26
27
use FacebookAds\Http\FileParameter;
28
use FacebookAds\Http\Parameters;
29
use FacebookAds\Http\RequestInterface;
30
use FacebookAds\Http\ResponseInterface;
31
use FacebookAds\Logger\CurlLogger\JsonAwareParameters;
32
33
class CurlLogger implements LoggerInterface {
34
35
  /**
36
   * @var string
37
   */
38
  const PARAM_DEFAULT_FLAG = 'd';
39
40
  /**
41
   * @var string
42
   */
43
  const PARAM_URLENCODE_FLAG = '-data-urlencode';
44
45
  /**
46
   * @var string
47
   */
48
  const PARAM_POST_FLAG = 'F';
49
50
  /**
51
   * @var string
52
   */
53
  const METHOD_DEFAULT_FLAG = '';
54
55
  /**
56
   * @var string
57
   */
58
  const METHOD_GET_FLAG = 'G';
59
60
  /**
61
   * @var string
62
   */
63
  const METHOD_PUT_FLAG = 'X PUT';
64
65
  /**
66
   * @var string
67
   */
68
  const METHOD_DELETE_FLAG = 'X DELETE';
69
70
  /**
71
   * @var resource
72
   */
73
  protected $handle;
74
75
  /**
76
   * @var bool
77
   */
78
  protected $jsonPrettyPrint = false;
79
80
  /**
81
   * @param resource $handle
82
   */
83 7
  public function __construct($handle = null) {
84 7
    $this->handle = is_resource($handle) ? $handle : STDOUT;
85 7
  }
86
87
  /**
88
   * @return bool
89
   */
90 5
  public function isJsonPrettyPrint() {
91 5
    return $this->jsonPrettyPrint;
92
  }
93
94
  /**
95
   * @param bool $json_pretty_print
96
   * @return $this
97
   */
98 1
  public function setJsonPrettyPrint($json_pretty_print) {
99 1
    $this->jsonPrettyPrint = $json_pretty_print;
100 1
    return $this;
101
  }
102
103
  /**
104
   * @param string $method
105
   * @return string
106
   */
107 5
  public static function getMethodFlag($method) {
108
    switch ($method) {
109 5
      case RequestInterface::METHOD_GET:
110 1
        return static::METHOD_GET_FLAG;
111 4
      case RequestInterface::METHOD_PUT:
112 1
        return static::METHOD_PUT_FLAG;
113 3
      case RequestInterface::METHOD_DELETE:
114 1
        return static::METHOD_DELETE_FLAG;
115
    }
116
117 2
    return static::METHOD_DEFAULT_FLAG;
118
  }
119
120
  /**
121
   * @param string $method
122
   * @param string $value
123
   * @return string
124
   */
125 5
  public static function getParamFlag($method, $value) {
126
    return $method === RequestInterface::METHOD_POST
127 5
      ? static::PARAM_POST_FLAG
128 5
      : (strstr($value, "\n")
129 4
        ? static::PARAM_URLENCODE_FLAG
130 5
        : static::PARAM_DEFAULT_FLAG);
131
  }
132
133
  /**
134
   * @param string $string
135
   * @param int $indent
136
   * @return string
137
   */
138 1
  protected function indent($string, $indent) {
139 1
    return str_replace("\n", " \n".str_repeat(' ', $indent), $string);
140
  }
141
142
  /**
143
   * @param Parameters $params
144
   * @param string $method
145
   * @param bool $is_file
146
   * @return string
147
   */
148 5
  protected function processParams(Parameters $params, $method, $is_file) {
149 5
    $chunks = array();
150 5
    if ($this->isJsonPrettyPrint()) {
151 1
      $params = new JsonAwareParameters($params);
152 1
    }
153 5
    foreach ($params->export() as $name => $value) {
154 5
      if ($is_file && $params->offsetGet($name) instanceof FileParameter) {
155
        $value = "@" . $this->normalizeFileParam($params->offsetGet($name));
156
      } else {
157 5
        $value = addcslashes(
158 5
          strpos($value, "\n") !== false
159 5
            ? $this->indent($value, 2)
160 5
            : $value,
161 5
          '\'');
162
      }
163 5
      $chunks[$name] = sprintf(
164 5
        '-%s \'%s=%s\'',
165 5
        $this->getParamFlag($method, $value),
166 5
        $name,
167 5
        $value);
168 5
    }
169
170 5
    return $chunks;
171
  }
172
173
  /**
174
   * @param FileParameter $file_param
175
   * @return string
176
   */
177
  protected function normalizeFileParam(FileParameter $file_param) {
178
    return sprintf('%s%s%s%s%s',
179
      $file_param->getPath(),
180
      $file_param->getMimeType() != null ? ";type=" : "",
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $file_param->getMimeType() of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
181
      $file_param->getMimeType(),
182
      $file_param->getName() != null ? ";name=" : "",
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $file_param->getName() of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
183
      $file_param->getName());
184
  }
185
186
  /**
187
   * @param RequestInterface $request
188
   * @return string
189
   */
190 5
  protected function processUrl(RequestInterface $request) {
191 5
    return $request->getProtocol().$request->getDomain()
192 5
      .'/v'.$request->getGraphVersion().$request->getPath();
193
  }
194
195
  /**
196
   * @param string $buffer
197
   */
198 5
  protected function flush($buffer) {
199 5
    fwrite($this->handle, $buffer.PHP_EOL.PHP_EOL);
200 5
  }
201
202
  /**
203
   * @param mixed $level
204
   * @param string $message
205
   * @param array $context
206
   */
207 1
  public function log($level, $message, array $context = array()) {
208
    // We only care about requests
209 1
  }
210
211
  /**
212
   * @param array $array
213
   * @param mixed $key
214
   * @return mixed
215
   */
216 5
  protected function removeArrayKey(array &$array, $key) {
217 5
    if (array_key_exists($key, $array)) {
218 4
      $value = $array[$key];
219 4
      unset($array[$key]);
220 4
      return $value;
221
    } else {
222 1
      return null;
223
    }
224
  }
225
226
  /**
227
   * @param array $params
228
   * @return array
229
   */
230 5
  protected function sortParams(array $params) {
231 5
    $access_token = $this->removeArrayKey($params, 'access_token');
232 5
    $appsecret_proof = $this->removeArrayKey($params, 'appsecret_proof');
233 5
    $access_token !== null && $params['access_token'] = $access_token;
234 5
    $appsecret_proof !== null && $params['appsecret_proof'] = $appsecret_proof;
235
236 5
    return $params;
237
  }
238
239
  /**
240
   * @param string $level
241
   * @param RequestInterface $request
242
   * @param array $context
243
   */
244 5
  public function logRequest(
245
    $level, RequestInterface $request, array $context = array()) {
246
247 5
    $new_line = ' \\'.PHP_EOL.'  ';
248 5
    $method = $request->getMethod();
249 5
    $method_flag = static::getMethodFlag($method);
250 5
    $params = $this->sortParams(array_merge(
251 5
      $this->processParams($request->getQueryParams(), $method, false),
252 5
      $this->processParams($request->getBodyParams(), $method, false),
253 5
      $this->processParams($request->getFileParams(), $method, true)));
254
255 5
    $buffer = 'curl'.($method_flag ? ' -'.$method_flag : '');
256 5
    foreach ($params as $param) {
257 5
      $buffer .= $new_line.$param;
258 5
    }
259 5
    $buffer .= $new_line.$this->processUrl($request);
260
261 5
    $this->flush($buffer);
262 5
  }
263
264
  /**
265
   * @param string $level
266
   * @param ResponseInterface $response
267
   * @param array $context
268
   */
269 1
  public function logResponse(
270
    $level, ResponseInterface $response, array $context = array()) {
271
    // We only care about requests
272 1
  }
273
}
274