| 1 |
<?php |
| 2 |
/*! |
| 3 |
* Hybridauth |
| 4 |
* https://hybridauth.github.io | https://github.com/hybridauth/hybridauth |
| 5 |
* (c) 2017 Hybridauth authors | https://hybridauth.github.io/license.html |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Hybridauth\Data; |
| 9 |
|
| 10 |
/** |
| 11 |
* Parser |
| 12 |
* |
| 13 |
* This class is used to parse plain text into objects. It's used by hybriauth adapters to converts |
| 14 |
* providers api responses to a more 'manageable' format. |
| 15 |
*/ |
| 16 |
final class Parser |
| 17 |
{ |
| 18 |
/** |
| 19 |
* Decodes a string into an object. |
| 20 |
* |
| 21 |
* This method will first attempt to parse data as a JSON string (since most providers use this format) |
| 22 |
* then XML and parse_str. |
| 23 |
* |
| 24 |
* @param string $raw |
| 25 |
* |
| 26 |
* @return mixed |
| 27 |
*/ |
| 28 |
public function parse($raw = null) |
| 29 |
{ |
| 30 |
$data = $this->parseJson($raw); |
| 31 |
|
| 32 |
if (!$data) { |
| 33 |
$data = $this->parseXml($raw); |
| 34 |
|
| 35 |
if (!$data) { |
| 36 |
$data = $this->parseQueryString($raw); |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
return $data; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Decodes a JSON string |
| 45 |
* |
| 46 |
* @param $result |
| 47 |
* |
| 48 |
* @return mixed |
| 49 |
*/ |
| 50 |
public function parseJson($result) |
| 51 |
{ |
| 52 |
return json_decode($result); |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Decodes a XML string |
| 57 |
* |
| 58 |
* @param $result |
| 59 |
* |
| 60 |
* @return mixed |
| 61 |
*/ |
| 62 |
public function parseXml($result) |
| 63 |
{ |
| 64 |
libxml_use_internal_errors(true); |
| 65 |
|
| 66 |
$result = preg_replace('/([<\/])([a-z0-9-]+):/i', '$1', $result); |
| 67 |
$xml = simplexml_load_string($result); |
| 68 |
|
| 69 |
libxml_use_internal_errors(false); |
| 70 |
|
| 71 |
if (!$xml) { |
| 72 |
return []; |
| 73 |
} |
| 74 |
|
| 75 |
$arr = json_decode(json_encode((array)$xml), true); |
| 76 |
$arr = array($xml->getName() => $arr); |
| 77 |
|
| 78 |
return $arr; |
| 79 |
} |
| 80 |
|
| 81 |
/** |
| 82 |
* Parses a string into variables |
| 83 |
* |
| 84 |
* @param $result |
| 85 |
* |
| 86 |
* @return \StdClass |
| 87 |
*/ |
| 88 |
public function parseQueryString($result) |
| 89 |
{ |
| 90 |
parse_str($result, $output); |
| 91 |
|
| 92 |
if (!is_array($output)) { |
| 93 |
return $result; |
| 94 |
} |
| 95 |
|
| 96 |
$result = new \StdClass(); |
| 97 |
|
| 98 |
foreach ($output as $k => $v) { |
| 99 |
$result->$k = $v; |
| 100 |
} |
| 101 |
|
| 102 |
return $result; |
| 103 |
} |
| 104 |
|
| 105 |
/** |
| 106 |
* needs to be improved |
| 107 |
* |
| 108 |
* @param $birthday |
| 109 |
* |
| 110 |
* @return array |
| 111 |
*/ |
| 112 |
public function parseBirthday($birthday) |
| 113 |
{ |
| 114 |
$birthday = date_parse((string) $birthday); |
| 115 |
|
| 116 |
return [$birthday['year'], $birthday['month'], $birthday['day']]; |
| 117 |
} |
| 118 |
} |
| 119 |
|