Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
recca0120 committed Apr 26, 2023
1 parent 4ad2961 commit bd907c6
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 102 deletions.
23 changes: 8 additions & 15 deletions src/ChunkFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use ErrorException;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Recca0120\Upload\Exceptions\ChunkedResponseException;
use Recca0120\Upload\Exceptions\ResourceOpenException;

class ChunkFile
Expand Down Expand Up @@ -46,8 +45,14 @@ class ChunkFile
*/
protected $tmpfilename = null;

public function __construct(string $name, string $chunkPath, string $storagePath, string $token = null, string $mimeType = null, Filesystem $files = null)
{
public function __construct(
string $name,
string $chunkPath,
string $storagePath,
string $token = null,
string $mimeType = null,
Filesystem $files = null
) {
$this->files = $files ?: new Filesystem();
$this->name = $name;
$this->chunkPath = $chunkPath;
Expand All @@ -65,21 +70,10 @@ public function getMimeType(): ?string
}
}

/**
* @param array|string $message
* @param array $headers
* @return void
*/
public function throwException($message = '', array $headers = []): void
{
throw new ChunkedResponseException($message, $headers);
}

/**
* appendStream.
*
* @param mixed $source
* @param int $offset
* @return $this
*
* @throws ResourceOpenException
Expand All @@ -96,7 +90,6 @@ public function appendStream($source, int $offset = 0)
* appendFile.
*
* @param mixed $source
* @param int $index
* @return $this
*
* @throws ResourceOpenException
Expand Down
1 change: 0 additions & 1 deletion src/Contracts/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ public function domain(): string;
public function path(): string;

/**
* @param string $path
* @return self
*/
public function makeDirectory(string $path);
Expand Down
9 changes: 6 additions & 3 deletions src/Dropzone.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\JsonResponse;
use Recca0120\Upload\Exceptions\ChunkedResponseException;
use Recca0120\Upload\Exceptions\ResourceOpenException;

class Dropzone extends FineUploader
Expand All @@ -29,9 +30,11 @@ public function receive(string $name)

$completed = $totalparts - 1 === $partindex;

return $completed === true
? $chunkFile->createUploadedFile($totalparts)
: $chunkFile->throwException(['success' => true, 'uuid' => $uuid]);
if ($completed !== true) {
throw new ChunkedResponseException(['success' => true, 'uuid' => $uuid], []);
}

return $chunkFile->createUploadedFile($totalparts);
}

public function completedResponse(JsonResponse $response): JsonResponse
Expand Down
19 changes: 14 additions & 5 deletions src/FileAPI.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Recca0120\Upload;

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Recca0120\Upload\Exceptions\ChunkedResponseException;
use Recca0120\Upload\Exceptions\ResourceOpenException;

class FileAPI extends Api
Expand All @@ -27,11 +28,17 @@ public function receive(string $name)
$chunkFile = $this->createChunkFile($originalName, $mimeType, $uuid);
$chunkFile->appendStream('php://input', $start);

return $completed === true
? $chunkFile->createUploadedFile()
: $chunkFile->throwException([
'files' => ['name' => $originalName, 'size' => $end, 'type' => $chunkFile->getMimeType()],
if ($completed !== true) {
throw new ChunkedResponseException([
'files' => [
'name' => $originalName,
'size' => $end,
'type' => $chunkFile->getMimeType(),
],
], ['X-Last-Known-Byte' => $end]);
}

return $chunkFile->createUploadedFile();
}

protected function getOriginalName(string $contentDisposition): string
Expand Down Expand Up @@ -61,7 +68,9 @@ protected function parseContentRange(): array
{
$contentRange = $this->request->header('content-range');
if (empty($contentRange) === false) {
return sscanf($contentRange, 'bytes %d-%d/%d');
[$start, $end, $total] = sscanf($contentRange, 'bytes %d-%d/%d');

return [$start, $end, $total];
}

$total = $end = (int) $this->request->header('content-length');
Expand Down
2 changes: 0 additions & 2 deletions src/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ public function createUploadedFile(string $path, string $originalName, string $m
* convertToResource.
*
* @param mixed $resource
* @param string $mode
* @param string $type
* @return resource
*
* @throws ResourceOpenException
Expand Down
12 changes: 9 additions & 3 deletions src/FineUploader.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@

namespace Recca0120\Upload;

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\JsonResponse;
use Recca0120\Upload\Exceptions\ChunkedResponseException;
use Recca0120\Upload\Exceptions\ResourceOpenException;

class FineUploader extends Api
{
/**
* @throws FileNotFoundException
* @throws ResourceOpenException
*/
public function receive(string $name)
{
$file = $this->request->file($name);
Expand All @@ -23,11 +30,10 @@ public function receive(string $name)

if ($completed === false) {
$chunkFile->appendFile($file->getRealPath(), $partindex);
throw new ChunkedResponseException(['success' => true, 'uuid' => $uuid], []);
}

return $completed === true
? $chunkFile->createUploadedFile($totalparts)
: $chunkFile->throwException(['success' => true, 'uuid' => $uuid]);
return $chunkFile->createUploadedFile($totalparts);
}

public function completedResponse(JsonResponse $response): JsonResponse
Expand Down
9 changes: 7 additions & 2 deletions src/Plupload.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Http\JsonResponse;
use Recca0120\Upload\Exceptions\ChunkedResponseException;
use Recca0120\Upload\Exceptions\ResourceOpenException;

class Plupload extends Api
Expand All @@ -19,8 +20,8 @@ public function receive(string $name)
if (empty($chunks) === true) {
return $uploadedFile;
}
$chunk = $this->request->get('chunk');

$chunk = $this->request->get('chunk');
$originalName = $this->request->get('name');
$start = $chunk * $this->request->header('content-length');
$uuid = $this->request->get('token');
Expand All @@ -29,7 +30,11 @@ public function receive(string $name)
$chunkFile = $this->createChunkFile($originalName, $uuid);
$chunkFile->appendStream($uploadedFile->getPathname(), $start);

return $completed === true ? $chunkFile->createUploadedFile() : $chunkFile->throwException();
if ($completed !== true) {
throw new ChunkedResponseException('', []);
}

return $chunkFile->createUploadedFile();
}

public function completedResponse(JsonResponse $response): JsonResponse
Expand Down
26 changes: 15 additions & 11 deletions src/Receiver.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ public function receive(string $inputName = 'file', callable $callback = null):
{
try {
$callback = $callback ?: [$this, 'callback'];
$response = $callback($uploadedFile = $this->api->receive($inputName), $this->api->path(), $this->api->domain(), $this->api);
$response = $callback(
$uploadedFile = $this->api->receive($inputName),
$this->api->path(),
$this->api->domain(),
$this->api
);

return $this->api->deleteUploadedFile($uploadedFile)->completedResponse($response);
} catch (ChunkedResponseException $e) {
Expand All @@ -35,12 +40,14 @@ public function receive(string $inputName = 'file', callable $callback = null):

public static function factory(array $config = [], string $class = FileAPI::class): Receiver
{
$class = Arr::get([
$lookup = [
'dropzone' => Dropzone::class,
'fileapi' => FileAPI::class,
'fineuploader' => FineUploader::class,
'plupload' => Plupload::class,
], strtolower($class), $class);
];

$class = Arr::get($lookup, strtolower($class), $class);

return new static(new $class($config));
}
Expand All @@ -50,18 +57,15 @@ protected function callback(UploadedFile $uploadedFile, $path, $domain): JsonRes
$clientPathInfo = $this->pathInfo($uploadedFile->getClientOriginalName());
$basePathInfo = $this->pathInfo($uploadedFile->getBasename());
$filename = md5($basePathInfo['basename']).'.'.$clientPathInfo['extension'];
$mimeType = $uploadedFile->getMimeType();
$size = $uploadedFile->getSize();
$uploadedFile->move($path, $filename);
$response = [

return new JsonResponse([
'name' => $clientPathInfo['filename'].'.'.$clientPathInfo['extension'],
'tmp_name' => $path.$filename,
'type' => $mimeType,
'size' => $size,
'type' => $uploadedFile->getMimeType(),
'size' => $uploadedFile->getSize(),
'url' => $domain.$path.$filename,
];

return new JsonResponse($response);
]);
}

private function pathInfo($path): array
Expand Down
29 changes: 4 additions & 25 deletions tests/ChunkFileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ public function testAppendStream(): void
$offset = 0;
$files->allows('tmpfilename')->once()->with($name, $token)->andReturn($tmpfilename = 'foo.php');
$files->allows('appendStream')->once()->with($chunkPath.$tmpfilename.'.part', $source, $offset);
$chunkFile->appendStream($source, $offset);

$chunkFile->appendStream($source, $offset)->throwException();
throw new ChunkedResponseException('', []);
}

public function testAppendFile(): void
Expand All @@ -57,8 +58,9 @@ public function testAppendFile(): void
$index = 0;
$files->allows('tmpfilename')->once()->with($name, $token)->andReturn($tmpfilename = 'foo.php');
$files->allows('appendStream')->once()->with($chunkPath.$tmpfilename.'.part.'.$index, $source, 0);
$chunkFile->appendFile($source, $index);

$chunkFile->appendFile($source, $index)->throwException();
throw new ChunkedResponseException('', []);
}

/**
Expand All @@ -85,27 +87,4 @@ public function testCreateUploadedFile(): void

$this->assertSame($uploadedFile, $chunkFile->createUploadedFile());
}

public function testThrowException(): void
{
$files = m::mock(Filesystem::class);

$chunkFile = new ChunkFile(
__FILE__,
'storage/chunk/',
'storage/',
uniqid('', true),
'text/plain',
$files
);

try {
$chunkFile->throwException(['foo' => 'bar'], ['foo' => 'bar']);
} catch (ChunkedResponseException $e) {
$response = $e->getResponse();
$this->assertSame(201, $response->getStatusCode());
$this->assertSame(json_encode(['foo' => 'bar']), $e->getMessage());
$this->assertSame('bar', $response->headers->get('foo'));
}
}
}
12 changes: 8 additions & 4 deletions tests/DropzoneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ public function testReceiveChunkedFile(): void
$request->allows('get')->once()->with('dzuuid')->andReturn($uuid = 'foo.uuid');
$uploadedFile->allows('getRealPath')->once()->andReturn($realPath = 'foo.realpath');

$chunkFileFactory->allows('create')->once()->with($originalName, $chunksPath, $storagePath, $uuid, null)->andReturn($chunkFile = m::mock(ChunkFile::class));
$chunkFileFactory->allows('create')->once()->with($originalName, $chunksPath, $storagePath, $uuid,
null)->andReturn($chunkFile = m::mock(ChunkFile::class));
$chunkFile->allows('appendFile')->once()->with($realPath, (int) $partindex)->andReturnSelf();
$chunkFile->allows('createUploadedFile')->once()->with($totalparts)->andReturn($uploadedFile);

Expand Down Expand Up @@ -97,12 +98,15 @@ public function testReceiveChunkedFileWithParts()
$request->allows('get')->once()->with('dzuuid')->andReturn($uuid = 'foo.uuid');
$uploadedFile->allows('getRealPath')->once()->andReturn($realPath = 'foo.realpath');

$chunkFileFactory->allows('create')->once()->with($originalName, $chunksPath, $storagePath, $uuid, null)->andReturn($chunkFile = m::mock(ChunkFile::class));
$chunkFileFactory->allows('create')->once()->with($originalName, $chunksPath, $storagePath, $uuid,
null)->andReturn($chunkFile = m::mock(ChunkFile::class));

$chunkFile->allows('appendFile')->once()->with($realPath, (int) $partindex)->andReturnSelf();

$chunkFile->allows('throwException')->once()->with(['success' => true, 'uuid' => $uuid])->andThrow($exception = new Exception());
// $chunkFile->allows('throwException')->once()->with([
// 'success' => true, 'uuid' => $uuid,
// ])->andThrow($exception = new Exception());

$this->assertSame($exception, $api->receive($inputName));
$api->receive($inputName);
}
}
Loading

0 comments on commit bd907c6

Please sign in to comment.