* Read the Data * @param $option * @return array available options of the data source */
($option)
| 62 | * @return array available options of the data source |
| 63 | */ |
| 64 | public function readData($option): array |
| 65 | { |
| 66 | $regex = isset($option['regex']) ? htmlspecialchars_decode($option['regex'], ENT_NOQUOTES) : ''; |
| 67 | $url = isset($option['url']) ? htmlspecialchars_decode($option['url'], ENT_NOQUOTES) : ''; |
| 68 | $urlError = ExternalUrlValidator::validate($url); |
| 69 | if ($urlError !== null) { |
| 70 | return [ |
| 71 | 'header' => ['', 'Dimension2', 'Count'], |
| 72 | 'dimensions' => ['', 'Dimension2'], |
| 73 | 'data' => [], |
| 74 | 'error' => $urlError, |
| 75 | ]; |
| 76 | } |
| 77 | |
| 78 | // Fetch HTML content using cURL |
| 79 | [$curlResult, $httpCode] = $this->fetchUrlContent($url); |
| 80 | |
| 81 | $header = ['', 'Dimension2', 'Count']; |
| 82 | |
| 83 | // Early return on HTTP error |
| 84 | if ($httpCode < 200 || $httpCode >= 300) { |
| 85 | return [ |
| 86 | 'header' => $header, |
| 87 | 'dimensions' => ['', 'Dimension2'], |
| 88 | 'data' => [], |
| 89 | 'error' => 'HTTP response code: ' . $httpCode, |
| 90 | 'rawData' => $curlResult, |
| 91 | 'URL' => $url, |
| 92 | ]; |
| 93 | } |
| 94 | |
| 95 | // Apply regex and build data |
| 96 | preg_match_all($regex, $curlResult, $matches); |
| 97 | |
| 98 | $dimensions = $matches['dimension'] ?? []; |
| 99 | $values = $matches['value'] ?? []; |
| 100 | $limit = isset($option['limit']) && (int)$option['limit'] > 0 ? (int)$option['limit'] : count($dimensions); |
| 101 | |
| 102 | // Use array_map for efficient data construction |
| 103 | $data = []; |
| 104 | for ($i = 0; $i < min($limit, count($dimensions), count($values)); $i++) { |
| 105 | $data[] = [ |
| 106 | $option['name'] ?? '', |
| 107 | $dimensions[$i], |
| 108 | $values[$i] |
| 109 | ]; |
| 110 | } |
| 111 | |
| 112 | return [ |
| 113 | 'header' => $header, |
| 114 | 'dimensions' => array_slice($header, 0, count($header) - 1), |
| 115 | 'data' => $data, |
| 116 | 'error' => 0, |
| 117 | 'rawData' => $curlResult, |
| 118 | 'URL' => $url, |
| 119 | ]; |
| 120 | } |
| 121 |
no test coverage detected