Skip to content

Instantly share code, notes, and snippets.

@lpj145
Created September 13, 2017 15:15
Show Gist options
  • Save lpj145/58ef6167009517ee1174c67cc58e9086 to your computer and use it in GitHub Desktop.
Save lpj145/58ef6167009517ee1174c67cc58e9086 to your computer and use it in GitHub Desktop.
<?php
namespace FiremonPHP\Storage;
class FileStorage
{
private $files = [];
public function __construct(array $files)
{
$this->storeInternal($files);
}
/**
* @param $files
*/
private function storeInternal($files)
{
if ($this->isMultiplePostFiles($files)) {
$this->byMultiplePostFiles($files);
return;
}
$this->byMultipleDataString($files);
}
/**
* @param array $dataFiles
*/
private function byMultipleDataString(array $dataFiles)
{
foreach ($dataFiles as $fileKey => $file) {
$indexFile = $this->generateName();
$stream = $this->initStream($indexFile);
fwrite($stream, $file['data']);
$this->setFilesAttributes(
$indexFile,
$stream,
$fileKey,
$file['metadata'] ?? null
);
}
}
/**
* @param array $files
*/
private function byMultiplePostFiles(array $files)
{
$countFiles = count($files['name']);
for ($i = 0; $i < $countFiles; $i++) {
$indexFile = $this->generateName();
$this->setFilesAttributes(
$indexFile,
$this->initStream($files['tmp_name'][$i]),
$files['name'][$i],
['type' => $files['type'][$i] ?? 'application/octet-stream']
);
}
}
/**
* @param array $file
* @return bool
*/
private function isMultiplePostFiles(array $file)
{
return isset($file['name']) && count($file['name']) > 0;
}
/**
* @return string
*/
private function generateName()
{
return md5(uniqid(rand(), true));
}
private function initStream(string $fileName)
{
return fopen($fileName, 'a+');
}
/**
* @param $index
* @param $data
* @param $name
* @param null $metadata
*/
private function setFilesAttributes($index, $data, $name, $metadata = null)
{
$this->files[$index]['data'] = $data;
$metadata = array_merge($metadata, ['name' => $name]);
$this->files[$index]['metadata'] = $metadata;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment