Last active
September 9, 2022 09:30
-
-
Save yaleksandr89/e8ca240ff3f2613d02544d48124bd0c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @return void | |
*/ | |
private function setInformationRemoteJsonFile(): void | |
{ | |
$curl = curl_init(); | |
curl_setopt_array($curl, [ | |
CURLOPT_URL => $this->jsonUrl, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_HEADER => true, | |
CURLOPT_NOBODY => true, | |
CURLOPT_HTTPHEADER => ['Authorization: Basic ...'], // if need | |
]); | |
curl_exec($curl); | |
$info = curl_getinfo($curl); | |
curl_close($curl); | |
$this->jsonUrl = $info['url']; | |
$this->httpCode = $info['http_code']; | |
$this->jsonSize = $this->calculateSize($info['download_content_length']); | |
} | |
/** | |
* @param float $size | |
* @return float|int | |
*/ | |
private function calculateSize(float $size) | |
{ | |
if (-1.0 === $size) { | |
throw new RuntimeException("Incorrect file size"); | |
} | |
$calcSize = 0; | |
switch ($size) { | |
case $size < 1024: | |
$calcSize = $size; // b | |
$this->unitMeasurement = 'b'; | |
break; | |
case $size < 1048576: | |
$calcSize = round($size / 1024, 6); // Kb | |
$this->unitMeasurement = 'kb'; | |
break; | |
case $size < 1073741824: | |
$calcSize = round($size / 1048576, 6); // Mb | |
$this->unitMeasurement = 'mb'; | |
break; | |
case $size < 1099511627776: | |
$calcSize = round($size / 1073741824, 6); // Gb | |
$this->unitMeasurement = 'gb'; | |
break; | |
} | |
return $calcSize; | |
} | |
/** | |
* @return void | |
*/ | |
private function saveJsonToFile(): void | |
{ | |
if (!$this->pathToSavedFile) { | |
throw new RuntimeException("Directory: $this->pathToSavedFile thi is deleted"); | |
} | |
$file = fopen($this->pathToSavedFile, 'wb'); | |
if (!$file) { | |
throw new RuntimeException("Failed to save file"); | |
} | |
$curl = curl_init(); | |
curl_setopt_array($curl, [ | |
CURLOPT_URL => $this->jsonUrl, | |
CURLOPT_FILE => $file, | |
CURLOPT_FOLLOWLOCATION => true, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_HEADER => false, | |
CURLOPT_HTTPHEADER => ['Authorization: Basic emFiYml4X21haW46VWI0NUFkUlk='], | |
]); | |
$data = curl_exec($curl); | |
curl_close($curl); | |
$file = file_put_contents($this->pathToSavedFile, $data); | |
if (!$file) { | |
throw new RuntimeException('Failed to save file'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment