Last active
December 1, 2016 19:20
-
-
Save f3ath/971143dfa99009934c033262db0724c7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
public function upload(Request $request): array | |
{ | |
$tmp_file = tmpfile(); | |
stream_copy_to_stream($request->getContent(true), $tmp_file); | |
fflush($tmp_file); | |
$tmp_file_name = stream_get_meta_data($tmp_file)['uri']; | |
$this->logger->debug("File uploaded to $tmp_file_name"); | |
$tmp_file_type = mime_content_type($tmp_file_name); | |
if (!in_array($tmp_file_type, $this->allowed_mime_types)) { | |
throw new ApiException("Invalid mime type: $tmp_file_type", ApiException::VALIDATION); | |
} | |
$hash = sha1_file($tmp_file_name); | |
$path = $this->getPath($hash); | |
$dir = "{$this->upload_dir}/{$path}"; | |
$this->logger->debug("Creating dir: $dir"); | |
mkdir($dir, 0700, true); | |
rename($tmp_file_name, "{$dir}/{$hash}"); | |
return [ | |
'url' => "{$this->base_url}/{$path}/{$hash}", | |
]; | |
} | |
private function getPath(string $hash): string | |
{ | |
$depth = 2; | |
$length = 2; | |
$path = []; | |
for ($i = 0; $i < $depth * $length; $i += $length) { | |
$path[] = substr($hash, $i, $length); | |
} | |
return implode('/', $path); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment