/** * Retrieve information about the authentication * * Will get the realm and other tokens by performing * another request without authentication to get authentication * challenge. * * @param \Cake\Network\Http\Request $request The request object. * @param array $credentials Authentication credentials. * @return Array modified credentials. */ protected function _getServerInfo(Request $request, $credentials) { $response = $this->_client->get($request->url(), [], ['auth' => []]); if (!$response->header('WWW-Authenticate')) { return false; } preg_match_all('@(\\w+)=(?:(?:")([^"]+)"|([^\\s,$]+))@', $response->header('WWW-Authenticate'), $matches, PREG_SET_ORDER); foreach ($matches as $match) { $credentials[$match[1]] = $match[2]; } if (!empty($credentials['qop']) && empty($credentials['nc'])) { $credentials['nc'] = 1; } return $credentials; }
public function rent($id) { // no view to render $this->autoRender = false; $id--; $http = new Client(); $response = $http->get('http://mgautschi.dev.at.sfsu.edu/building_mgmt/properties/api'); $rental = json_decode($response->body); // echo $rental[$id - 1]->address; // die; $property = $this->Properties->newEntity(); // Added this line $property->user_id = $this->Auth->user('id'); $property->unitType = $rental[$id]->unitType; $property->address = $rental[$id]->address; $property->city = $rental[$id]->city; $property->state = $rental[$id]->state; $property->zip = $rental[$id]->zip; $property->building = $rental[$id]->building; $property->unitNumber = $rental[$id]->unit; $property->beds = $rental[$id]->beds; $property->baths = $rental[$id]->baths; $property->rent = $rental[$id]->rent; $property->square_feet = $rental[$id]->squareFt; if ($this->Properties->save($property)) { $this->Flash->success(__('You are now renting at ' . $property->address)); return $this->redirect(['action' => 'search']); } //return $this->redirect(['action' => 'search']); //$this->Flash->error(__('Unable to rent this property.')); return $this->redirect(['action' => 'search']); }
public function results() { $client = new Client(); $results = json_decode($client->get('http://api.giphy.com/v1/gifs/search?', ['q' => $this->request->data('search'), 'api_key' => $this->api_key])->body()); $this->set('results', $results->data); $this->set('search_string', $this->request->data('search')); }
public function cep($cep) { $cep = str_replace('-', '', $cep); $this->viewBuilder()->layout('ajax'); $http = new Client(); $response = $http->get('http://cep.agenciavoxel.com.br/' . $cep . '.json'); $this->set('retorno', json_decode($response->body(), true)); }
/** * Shorten the given $url, handle response errors and return a BitlyResponseData object. * * @param string $url * @return BitlyResponseData|null */ public function shorten($url) { $longUrl = urlencode($url); $apiRequest = Text::insert(':shortenEndpoint?login=:login&apiKey=:apiKey&longUrl=:longUrl', ['shortenEndpoint' => self::ENDPOINT . self::SHORTEN, 'login' => $this->_login, 'apiKey' => $this->_apiKey, 'longUrl' => $longUrl]); /** @var null|BitlyResponse $response */ $response = $this->http->get($apiRequest)->body('json_decode'); $this->_handleBitlyResponse($response, $longUrl); return $response->data; }
public function main() { $tick_names_and_values = array(); $this->authentication(); $http = new Client(); $this->loadModel('Stocks'); $this->loadModel('Devices'); $token_file = new File("/home/demo/token/token.txt"); $token = $token_file->read(); $token_file->close(); $MyAuthObject = new OAuthObject(array("token_type" => "Bearer", "access_token" => $token)); $OptionsToast = new WNSNotificationOptions(); $OptionsToast->SetAuthorization($MyAuthObject); $OptionsToast->SetX_WNS_REQUESTFORSTATUS(X_WNS_RequestForStatus::Request); $NotifierToast = new WindowsNotificationClass($OptionsToast); $OptionsTile = new WNSNotificationOptions(); $OptionsTile->SetAuthorization($MyAuthObject); $OptionsTile->SetX_WNS_REQUESTFORSTATUS(X_WNS_RequestForStatus::Request); //NOTE: Set the Tile type $OptionsTile->SetX_WNS_TYPE(X_WNS_Type::Tile); $NotifierTile = new WindowsNotificationClass($OptionsTile); $allStocks = $this->Stocks->find('all')->toArray(); //$allStocks = $this->Stocks->find('all')->group(['Stocks.device_id'])->toArray(); //$allStocks = $this->Stocks->Devices->find()->group(['Devices.id'])->toArray(); Debugger::dump('allStocks: '); Debugger::dump($allStocks); $allStocksByDeviceId = array(); for ($i = 0; $i < sizeof($allStocks); $i++) { $actualDeviceId = $allStocks[$i]['device_id']; $added = false; for ($a = 0; $a < sizeof($allStocksByDeviceId); $a++) { if ($allStocksByDeviceId[$a]['device_id'] == $actualDeviceId) { $allStocksByDeviceId[$a]['stocks'][] = $allStocks[$i]; $added = true; } } if (!$added) { $allStocksByDeviceId[] = ['device_id' => $actualDeviceId, 'stocks' => [$allStocks[$i]]]; } } Debugger::dump('allStocksByDeviceId: '); Debugger::dump($allStocksByDeviceId); $someStocks = $this->Stocks->find()->distinct(['tick_name'])->toArray(); for ($i = 0; $i < sizeof($someStocks); $i++) { $response = $http->get('http://download.finance.yahoo.com/d/quotes?f=sl1d1t1v&s=' . $someStocks[$i]['tick_name']); $tick_name = explode(",", $response->body())[0]; $tick_names_and_values[] = [str_replace("\"", "", $tick_name), explode(",", $response->body())[1]]; } Debugger::dump('tick_names_and_values: '); Debugger::dump($tick_names_and_values); $this->sendAllStocksNotificationsInTileNotifications($NotifierTile, $tick_names_and_values, $allStocksByDeviceId); $this->checkMinMaxValuesAndSendToastNotifications($NotifierToast, $tick_names_and_values); //$stuff = implode(",", $stuff); //$now = Time::now(); //$this->createFile('/home/demo/files_created_each_minute/'.$now->i18nFormat('yyyy-MM-dd HH:mm:ss').'.txt', $stuff); }
/** * @param $id * @param $data * @param $isRejection * @return \Cake\Network\Http\Response */ public static function processRequirementApproval($id, $data, $isRejection) { $queryParams = ['cod_u' => $data->user_code, 'cod_sol' => $data->request_user, 'opt' => $isRejection ? 'no' : 'si', 'id' => $id]; if ($isRejection) { $queryParams['moti'] = $data->reject_reason; } $http = new Client(); // Simple get with query string $response = $http->get('http://192.168.30.57/mesaayuda/rq_autorizGte_u.php', $queryParams); return $response; }
public function getPlayerSummary($steamId = null) { $this->autoRender = false; if ($steamId === null) { $steamId = $this->myId; } $http = new Client(); $response = $http->get('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/', ['key' => $this->key, 'steamids' => $steamId, 'format' => 'json']); $out = json_decode($response->body); debug($out); }
public function sendCodeToNode($id) { $http = new Client(); $node = $this->Nodes->get($id, ['fields' => 'node_code']); $node_code = $node['node_code']; $master_address = \Cake\Core\Configure::read('Master.master_address'); $master_port = \Cake\Core\Configure::read('Master.master_port'); $address = $master_address . ':' . $master_port . '/node/link?target=' . $node_code . '&sender=1'; $response = $http->get((string) $address); $this->Flash->success('Code sent'); return $this->redirect(['action' => 'index']); }
/** * Geocodes an address. * * @param string $address The address or location to geocode * @param array $parameters Additional params to pass to the Google Geocoding API * @throws GeocoderException if the API return a status code other than 200 * @return object */ public function geocode($address, $parameters = []) { $parameters['address'] = $address; $parameters['sensor'] = 'false'; $url = 'http://maps.googleapis.com/maps/api/geocode/json'; $http = new Client(); $response = $http->get($url, $parameters); if ($response->code != 200) { throw new GeocoderException('Google Maps Geocoding API returned status code ' . $response->code); } $response = json_decode($response->body()); return $response->results; }
/** * Retuns the full address */ public function getByZipcode($zipcode) { $http = new Client(); $response = $http->get('http://www.consultaenderecos.com.br/busca-cep/' . $zipcode); $html = str_get_html($response->body()); $lines = $html->find("table td"); $data = []; $data['street'] = isset($lines[1]) ? $lines[1]->innertext : ''; $data['neighborhood'] = isset($lines[2]) ? $lines[2]->innertext : ''; $data['city'] = isset($lines[3]) ? $lines[3]->innertext : ''; $data['state'] = isset($lines[4]) ? $lines[4]->innertext : ''; return $data; }
public function desactivateScenario($id) { $scenariosTable = TableRegistry::get('Scenarios'); $scenario = $scenariosTable->get($id); $http = new Client(); $master_address = \Cake\Core\Configure::read('Master.master_address'); $master_port = \Cake\Core\Configure::read('Master.master_port'); $address = $master_address . ':' . $master_port . '/master/desactivateScript?script_file=' . $scenario->script_file; $response = $http->get((string) $address); $scenario->status = false; $scenariosTable->save($scenario); $this->Flash->success('Scenario desactivated'); return $this->redirect(['action' => 'view' . '/' . $id]); }
public function decodeAddress($lat, $lng) { $url = "{$this->config['apiUrl']}?latlng={$lat},{$lng}&language={$this->config['language']}®ion={$this->config['region']}"; $httpClient = new Client(); $response = $httpClient->get($url); if (!$response->isOk()) { return false; } $resp = json_decode($response->body(), true); // debug($resp); if (!isset($resp['results']['0'])) { return false; } $address = []; foreach ($resp['results'][0]['address_components'] as $component) { if (!isset($this->apiFieldMap[$component['types'][0]])) { continue; } $address[$this->config['fields'][$this->apiFieldMap[$component['types'][0]]]] = $component['long_name']; } return $address; }
public function flood($payload, $job) { $command = 'ps -p ' . $payload['pid']; exec($command, $op); if (!isset($op[1])) { return 'Flood has been stopped'; } $pi = $this->_bcpi(rand(1, $payload['work'])); //Fetch an api 50% of the time if (rand(0, 1) == 0) { $client = new Client(); $client->get('http://jsonplaceholder.typicode.com/posts'); $pi .= ' - api'; sleep(rand(0, 120)); } $number_forks = rand($payload['first'] ? 1 : 0, $payload['max_fork']); $payload['first'] = false; $sequence = rand(0, 9) > 0 ? null : 'ark_' . $job->id . '_' . time(); for ($i = 0; $i < $number_forks; $i++) { $this->_queueJob('FloodTest', 'DelayedJobs\\Worker\\ArkWorker', 'flood', $payload, rand(0, 9) + $job->priority, $sequence); } return $pi; }
/** * Before save callback. * * @param \Cake\Event\Event $event The beforeSave event that was fired * @param \Cake\ORM\Entity $entity The entity that is going to be saved * @return bool */ public function beforeSave(Event $event, Entity $entity) { $addressColumn = $this->_config['addressColumn']; $latitudeColumn = $this->_config['latitudeColumn']; $longitudeColumn = $this->_config['longitudeColumn']; $parameters = (array) $this->_config['parameters']; $requireSuccess = $this->_config['requireSuccess']; if (is_array($addressColumn)) { $address = []; foreach ($addressColumn as $column) { if (!empty($entity->{$column})) { $address[] = $entity->{$column}; } } $address = implode(', ', $address); } else { $address = $entity->{$addressColumn}; } $parameters['address'] = $address; $parameters['sensor'] = 'false'; $url = 'http://maps.googleapis.com/maps/api/geocode/json'; $http = new Client(); $response = $http->get($url, $parameters); $response = json_decode($response->body()); if ($response->status == 'OK') { $entity->{$latitudeColumn} = floatval($response->results[0]->geometry->location->lat); $entity->{$longitudeColumn} = floatval($response->results[0]->geometry->location->lng); return true; } else { if ($requireSuccess) { $entity->errors($addressColumn, 'Could not geocode address'); return false; } else { return true; } } }
/** * Fetch data from Openweathermap website * * @param array $params Array of parameters for building the url * @param string $mode Output format expected (json, xml, html) * @param string $type Type of request (forecast, current) * @return array|mixed */ protected function _fetchData($params, $mode = null, $type = 'forecast') { try { // if $mode is null, we get the default config mode if (is_null($mode)) { $mode = $this->config('mode'); } // create HTTP Client $client = new Client(); $params['mode'] = $mode; // grab the info $data = $client->get($this->config('url.' . $type), $params); if (!$data->isOk()) { // if the grabing is a failure, we return an error return ['success' => false, 'error' => __d('openweathermap', 'Fetching error from Openweathermap')]; } else { // if grabing is a success, we parse the result switch ($mode) { case 'json': $response = ['success' => true, 'data' => $data->json]; break; case 'xml': $response = ['success' => true, 'data' => $data->xml]; break; case 'html': $response = ['success' => true, 'data' => $data->body()]; break; } // we save weather informations into database $this->_saveData($data->json); } } catch (\Exception $ex) { $response = ['success' => false, 'error' => $ex->getMessage()]; } return $response; }
/** * Requisita dados dos Correios * * @param string $url Caminho relativo da página nos Correios * @param string $method Método de requisição (POST/GET) * @param array $query Dados para enviar na página * @return string Página solicitada * @access protected */ protected function _requisitaUrl($url, $method, $query) { $httpClient = new Client(); if ($method === 'get') { $response = $httpClient->get($url . "?" . http_build_query($query)); } else { $response = $httpClient->post($url, $query); } if (!$response->isOk()) { return CorreiosTrait::$ERRO_CORREIOS_FALHA_COMUNICACAO; } return trim($response->body()); }
/** * Svn method * * @param int $id user id * * @return void */ public function svn($id) { $user = $this->Users->get($id); $svnsUsers = TableRegistry::get('svn_users'); $pseudos = $svnsUsers->findByUserId($id)->toArray(); $code = $this->request->query('code'); if ($code) { $http = new Client(); $result = $http->post('https://github.com/login/oauth/access_token', ['client_id' => GITHUBID, 'client_secret' => GITHUBKEY, 'code' => $code]); $tmp = explode('&', $result->body)[0]; $token = explode('=', $tmp)[1]; if ($token != "bad_verification_code") { $result = $http->get('https://api.github.com/user', ['access_token' => $token]); $res = json_decode($result->body, true); if (!$svnsUsers->findByPseudo($res['login'])->toArray()) { $svnUser = $svnsUsers->newEntity(); $svnUser->editPseudo($res['login']); $svnUser->editSvnId(1); $svnUser->edituserId($id); if ($svnsUsers->save($svnUser)) { $this->Flash->success(__('The account have been added')); return $this->redirect(['controller' => 'Users', 'action' => 'svn', $id]); } else { $this->Flash->error(__('Error in adding the account, please try again.')); } } else { $this->Flash->error(__('This account have already been added')); } } } $this->set(compact('user', 'pseudos')); $this->set('_serialize', ['user']); }
/** * @param Client $http * @param string $endPoint * @param array $query * @return array */ private function __requestApiGet(Client $http, $endPoint, $query = []) { $url = self::BASE_URL . $endPoint; $accessToken = $this->Session->read('Config.access_token'); $this->header['headers']['Authorization'] = $this->header['headers']['Authorization'] . $accessToken; $response = $http->get($url, $query, $this->header); return $response->json; }
/** * Check MFA Method */ public function mfa() { $session = $this->request->session(); $user = $session->read('user'); $channel = $session->read('channel'); if (empty($channel) || empty($user)) { $this->Flash->error('Invalid parameters.'); return $this->redirect($this->Auth->redirectUrl()); } $mfaEmail = $user['mfa_email']; $http = new Client(); $response = $http->get("https://www.acceptto.com/api/v9/check?email={$mfaEmail}&channel={$channel}"); $data = $response->json; $status = $data['status']; $message = "Multi factor authorization request was {$status}"; if ($status == 'approved') { $this->Flash->success(__($message)); $this->Auth->setUser($user); $this->redirect($this->Auth->redirectUrl()); } else { $this->Flash->error(__($message)); $this->redirect(['action' => 'login']); } }
/** * Returns the details of the employee based their emp ID * @param type $empID * @return string */ public function getEmpDataByID($empID) { $http = new Client(); $response = $http->get(WEBSTAION_API, ['UserID' => $empID, 'CompanyID' => OSMOSYS]); $response = $response->json; if ($response['RecordCount'] == 1) { $empData = $response['MultipleResults'][0]; return $empData; } return ''; }
public function getDataSouth($city, $slug, $arrWeekDay = array()) { $area = Configure::read('Area.south.code'); $resultsTable = TableRegistry::get('Results'); $query = $resultsTable->find('all', ['fields' => ['date_result'], 'conditions' => ['area' => $area, 'city' => $city], 'order' => ['date_result' => 'DESC']]); $dataFirst = $query->first(); $newestDate = $dataFirst ? $dataFirst->date_result->modify('+1 days')->i18nFormat('YYYY-MM-dd') : '2008-01-01'; $endDate = date('H', strtotime('+7 hour')) > 18 ? 0 : 1; //Init variable $http = new Client(); $begin = new \DateTime($newestDate); $end = new \DateTime(); $end->modify("-{$endDate} day"); $interval = new \DateInterval('P1D'); $daterange = new \DatePeriod($begin, $interval, $end); foreach ($daterange as $date) { $dateFormat = $date->format("d-m-Y"); $wday = $date->format("w"); $dateResult = $date->format("Ymd"); if (!in_array($wday, $arrWeekDay)) { continue; } $this->log($dateResult, 'info'); $url = "http://www.xoso.net/getkqxs/{$slug}/{$dateFormat}.js"; $response = $http->get($url); preg_match_all("|'(.*)'|", $response->body(), $match); $dom = new \DOMDocument(); $dom->loadHTML($match[1][2]); foreach ($dom->getElementsByTagName('td') as $node) { $class = $node->getAttribute('class'); $value = preg_replace('/\\s+/', '', $node->nodeValue); if (preg_match('/^giai(\\d|db)+$/', $class) && $value !== '') { $arrContent = explode('-', $value); foreach ($arrContent as $content) { $result = $resultsTable->newEntity(); $result->date_result = $dateResult; $result->level = Configure::read("Result_Level.{$class}"); $result->content = $content; $result->area = $area; $result->city = $city; $result->created_date = $end->format("YmdHis"); $result->modified_date = $end->format("YmdHis"); $resultsTable->save($result); } } } } }
/** * Prepares install from remote URL. * * @return bool True on success */ protected function _getFromUrl() { try { $http = new Client(['redirect' => 3]); // follow up to 3 redirections $response = $http->get($this->params['source'], [], ['headers' => ['X-Requested-With' => 'XMLHttpRequest']]); } catch (\Exception $ex) { $response = false; $this->err(__d('installer', 'Could not download the package. Details: {0}', $ex->getMessage())); return false; } if ($response && $response->isOk()) { $this->params['source'] = TMP . substr(md5($this->params['source']), 24) . '.zip'; $file = new File($this->params['source']); $responseBody = $response->body(); if (is_readable($file->pwd())) { $file->delete(); } if (!empty($responseBody) && $file->create() && $file->write($responseBody, 'w+', true)) { $file->close(); return $this->_getFromFile(); $this->err(__d('installer', 'Unable to extract the package.')); return false; } $this->err(__d('installer', 'Unable to download the file, check write permission on "{0}" directory.', [TMP])); return false; } $this->err(__d('installer', 'Could not download the package, no .ZIP file was found at the given URL.')); return false; }
private function doGet($url) { $socket = new Client(array('ssl_verify_host' => false)); $result = $socket->get($url); $this->fullResponse = $result; return $result; }
/** * Fetch commits for any given git repository from the Github API. * * @param string $repository Github repository shortname (owner/repo). * @param string $branch Branch to get commits for * @param int $limit Number of results to return. * @return array Array * @throws Cake\Core\Exception\Exception */ public function getRepositoryCommits($repository, $branch = 'master', $limit = null) { $cacheKey = 'commits_' . str_replace('/', '_', $repository); $commits = Cache::read($cacheKey, 'short'); if ($commits) { return $commits; } if ($limit) { if (!is_int($limit)) { throw new Exception("Parameter limit must be an integer"); } $limit = "page=1&per_page={$limit}"; } $params = "?sha={$branch}&{$limit}"; try { $http = new Client(); $response = $http->get("https://api.github.com/repos/{$repository}/commits{$params}"); if (!$response->isOk()) { return null; } $result = json_decode($response->body(), true); Cache::write($cacheKey, $result, 'short'); return $result; } catch (\Exception $e) { return null; } }
protected function _getFromUrl($url, $resetCache = false) { if ($resetCache) { Cache::delete('geo_import_' . md5($url)); } if ($cache = Cache::read('geo_import_' . md5($url))) { return $cache; } $HttpSocket = new Client(); $res = $HttpSocket->get($url); //file_put_contents(TMP . \Cake\Utility\Inflector::slug($url) . '.json', $res->body); Cache::write('geo_import_' . md5($url), $res->body); return $res->body; }
/** * TransifexLib::_get() * * @param string $url * @return array * @throws \RuntimeException Exception. */ protected function _get($url) { $Socket = new Client(); $config = ['auth' => ['username' => $this->settings['user'], 'password' => $this->settings['password']]]; $url = Text::insert($url, $this->settings, ['before' => '{', 'after' => '}']); $response = $Socket->get($url, [], $config); if (!$response->isOk()) { throw new RuntimeException('Unable to retrieve data from API'); } return json_decode($response->body(), true); }
/** * Test that Client stores cookies * * @return void */ public function testCookieStorage() { $adapter = $this->getMockBuilder('Cake\\Network\\Http\\Adapter\\Stream')->setMethods(['send'])->getMock(); $cookieJar = $this->getMockBuilder('Cake\\Network\\Http\\CookieCollection')->getMock(); $headers = ['HTTP/1.0 200 Ok', 'Set-Cookie: first=1', 'Set-Cookie: expiring=now; Expires=Wed, 09-Jun-1999 10:18:14 GMT']; $response = new Response($headers, ''); $cookieJar->expects($this->at(0))->method('get')->with('http://cakephp.org/projects')->will($this->returnValue([])); $cookieJar->expects($this->at(1))->method('store')->with($response); $adapter->expects($this->at(0))->method('send')->will($this->returnValue([$response])); $http = new Client(['host' => 'cakephp.org', 'adapter' => $adapter, 'cookieJar' => $cookieJar]); $http->get('/projects'); }
/** * Get Request * * Execute get request * * @param string $url - url of the to send the request. * @param Array $data - Array to data to send if not null. * @param string $type - Type of data specified in request. * @param Array $option - Array of options to add into request as get variables. * @param Array $header - Array of header to add into request as http headers. * @param boolean $entityAdmin - flag to use either _api or _admin in request. * * * @return array $response - The response array. */ public function get($url, $data = NULL, $type = NULL, $option = NULL, $header = NULL, $entityAdmin = false) { $entity = self::ENTRY_API; if ($entityAdmin) { $entity = self::ENTRY_ADMIN; } $uri = $this->protocol . '://' . $this->user . ':' . $this->pass . '@' . $this->host . ':' . $this->port . '/' . self::ENTRY_DB . '/' . $this->db . '/' . $entity . '/' . $url; if ($option != NULL) { $uri .= '?'; foreach ($option as $key => $value) { # code... $uri .= $key . '=' . $value . '&'; } } $http = new Client(); $response = $http->get($uri, json_encode($data), ['headers' => $header]); return $response; }
/** * Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array. * * ### Usage: * * Building XML from a string: * * `$xml = Xml::build('<example>text</example>');` * * Building XML from string (output DOMDocument): * * `$xml = Xml::build('<example>text</example>', array('return' => 'domdocument'));` * * Building XML from a file path: * * `$xml = Xml::build('/path/to/an/xml/file.xml');` * * Building from a remote URL: * * `$xml = Xml::build('http://example.com/example.xml');` * * Building from an array: * * {{{ * $value = array( * 'tags' => array( * 'tag' => array( * array( * 'id' => '1', * 'name' => 'defect' * ), * array( * 'id' => '2', * 'name' => 'enhancement' * ) * ) * ) * ); * $xml = Xml::build($value); * }}} * * When building XML from an array ensure that there is only one top level element. * * ### Options * * - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument. * - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This * is disabled by default for security reasons. * - If using array as input, you can pass `options` from Xml::fromArray. * * @param string|array $input XML string, a path to a file, a URL or an array * @param string|array $options The options to use * @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument * @throws \Cake\Utility\Error\XmlException */ public static function build($input, array $options = []) { $defaults = array('return' => 'simplexml', 'loadEntities' => false); $options += $defaults; if (is_array($input) || is_object($input)) { return static::fromArray((array) $input, $options); } elseif (strpos($input, '<') !== false) { return static::_loadXml($input, $options); } elseif (file_exists($input)) { return static::_loadXml(file_get_contents($input), $options); } elseif (strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) { try { $socket = new Client(['redirect' => 10]); $response = $socket->get($input); if (!$response->isOk()) { throw new Error\XmlException('XML cannot be read.'); } return static::_loadXml($response->body, $options); } catch (SocketException $e) { throw new Error\XmlException('XML cannot be read.'); } } elseif (!is_string($input)) { throw new Error\XmlException('Invalid input.'); } throw new Error\XmlException('XML cannot be read.'); }