3 Commits

  1. 1
      .gitignore
  2. 97
      app/Http/Controllers/FileController.php
  3. 2
      app/Http/Middleware/BindFileModelMiddleware.php
  4. 2
      app/Http/Requests/FileStoreRequest.php
  5. 117
      app/Image/ImageProcessor.php
  6. 5
      composer.json
  7. 47
      composer.lock
  8. 6
      database/factories/BaseFactory.php
  9. 20
      database/factories/CollectionFactory.php
  10. 2
      database/factories/Documents/PolicyDocumentFactory.php
  11. 28
      database/factories/FileFactory.php
  12. 2
      database/factories/ILaravelFactory.php
  13. 2
      database/factories/UserFactory.php
  14. 6
      routes/api.php
  15. 111
      routes/web.php
  16. BIN
      storage/stub/image1.png
  17. 8
      tests/Base/FactoryMethodsTrait.php
  18. 53
      tests/Feature/FileDeleteTest.php
  19. 47
      tests/Feature/FileRestoreTest.php
  20. 29
      tests/Feature/FileShowTest.php
  21. 102
      tests/Feature/FileStoreTest.php
  22. 49
      tests/Feature/FileUpdateTest.php

1
.gitignore

@ -3,6 +3,7 @@
/public/hot
/public/storage
/storage/*.key
/storage/stub/*.webp
/vendor
.env
.env.backup

97
app/Http/Controllers/FileController.php

@ -1,97 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\FileStoreRequest;
use App\Http\Requests\FileUpdateRequest;
use App\Http\Resources\FileResource;
use App\Image\ImageProcessor;
use App\Jobs\FileConversionQueue;
use App\Models\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\Console\Input\Input;
use function PHPUnit\Framework\isNull;
class FileController extends Controller
{
public function show($collection, $uuid, $ext, Request $request, ImageProcessor $imageProcessor)
{
if ($request->castParams == 'resource') {
return new FileResource(app()->file);
}
if (!is_null(array_intersect(array_keys($request->all()), $this->availableParams))) {
$imageProcessor->process(app()->file->getPath(), app()->file->getModifiedPath(), $request->all());
return response()->file(app()->file->getModifiedPath());
}
return response()->file(app()->file->getPath());
}
// for local private we didn't talk about it
// public function private($collection, $path)
// {
// Storage::disk('local')->download($path);
// }
public function store(FileStoreRequest $request, ImageProcessor $imageProcessor)
{
$request->file = $imageProcessor->convertImage($request->file->path(), '/tmp/' . app()->uuid . '.' . app()->collection->ext);
if (!is_null(app()->collection->process)) {
$request->file = $imageProcessor->process($request->file->path(), '/tmp/' . app()->uuid . '.' . app()->collection->ext, app()->collection->process);
}
$fileResource = null;
DB::transaction(function () use ($request, &$fileResource) {
$uuid = app()->uuid;
$fileResource = File::create([
'uuid' => $uuid,
'original_name' => $request->name,
'public' => $request->public,
'ext' => $request->file->extension(),
'mimetype' => $request->file->getMimeType(),
'width' => getimagesize($request->file)[0],
'height' => getimagesize($request->file)[1],
'file_size' => $request->file->getSize(),
'sort' => $request->file->getSize(),
'alts' => $request->alts,
'description' => $request->description,
'user_id' => auth()->id(),
'ip' => $request->ip(),
'collection_id' => app()->collection->id,
'published_at' => $request->published_at,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
]);
if (!app()->collection->tmp_support && app()->collection->count == 1) {
File::where('user_id', auth()->id())->delete();
}
$storedFile = Storage::disk(app()->collection->disk)->putFileAs($fileResource->server_path, $request->file, $fileResource->uuid . '.' . app()->collection->ext);
if (app()->collection->public) {
Storage::disk(app()->collection->disk)->setVisibility($storedFile, 'public');
}
});
return new FileResource($fileResource);
}
public function update(FileUpdateRequest $request)
{
app()->file->update($request->all());
return new FileResource(app()->file);
}
public function destroy()
{
if (app()->file->trashed()) {
return app()->file->restore();
}
return app()->file->delete();
}
}

2
app/Http/Middleware/BindFileModelMiddleware.php

@ -20,8 +20,10 @@ class BindFileModelMiddleware
*/
public function handle(Request $request, Closure $next)
{
if (($request->route()->action['as'] == 'api.files.store') && is_null($request->file('file'))) {
$file = File::find($request->file);
if (!is_null($file)) {
$Collection = Collection::where('name', $request->route('collection_name'))->firstOrFail();
if (Storage::disk($Collection->disk)->exists($file->server_path . $file->uuid . '.' . $Collection->ext)) {

2
app/Http/Requests/FileStoreRequest.php

@ -26,6 +26,7 @@ class FileStoreRequest extends FormRequest
public function authorize()
{
if (!app()->collection->tmp_support && !$this->model_id) {
return false;
}
@ -52,6 +53,7 @@ class FileStoreRequest extends FormRequest
*/
public function rules()
{
return [
"file" => [
"mimes:" . app()->collection->getExts(),

117
app/Image/ImageProcessor.php

@ -17,6 +17,123 @@ class ImageProcessor
protected $defaultW = 2000;
protected $defaultH = 2000;
public function processToBuffer(string $filename, array $options = [], $saveOptions = ['Q' => 100])
{
if (array_key_exists('w', $options) && array_key_exists('h', $options) && array_key_exists('r', $options)) {
unset($options['r']);
}
if (array_key_exists('r', $options)) {
$options['r'] = explode(':', $options['r']);
if (count($options['r']) != 2) {
unset($options['r']);
}
$validator = Validator::make($options, [
'r' => ['nullable', 'array'],
'r.*' => ['nullable', 'numeric'],
]);
if ($validator->fails()) {
foreach ($validator->messages()->getMessages() as $field_name => $messages) {
unset($options[explode('.', $field_name)[0]]);
}
}
}
if (array_key_exists('r', $options)) {
if (array_key_exists('w', $options) && !array_key_exists('h', $options)) {
$options['w'] = $options['w'] * $options['r'][0];
$options['h'] = $options['w'] * $options['r'][1];
}
if (!array_key_exists('w', $options) && array_key_exists('h', $options)) {
$options['w'] = $options['h'] * $options['r'][0];
$options['h'] = $options['h'] * $options['r'][1];
}
if (!array_key_exists('w', $options) && !array_key_exists('h', $options)) {
$options['w'] = getimagesize($filename)[0] * $options['r'][0];
$options['h'] = getimagesize($filename)[0] * $options['r'][1];
}
unset($options['r']);
}
$validator = Validator::make($options, [
'w' => ['numeric', 'between:1,2000'],
'h' => ['numeric', 'between:1,2000'],
'canv' => ['boolean'],
'brightness' => ['numeric', 'between:0,100'],
'saturation' => ['numeric', 'between:0,100'],
'hue' => ['numeric', 'between:0,100'],
'rotation' => ['numeric'],
'flip' => ['string', ValidationRule::in(['h', 'v', 'hv'])]
]);
if ($validator->fails()) {
foreach ($validator->messages()->getMessages() as $field_name => $messages) {
unset($options[$field_name]);
}
}
if (!array_key_exists('w', $options) && !array_key_exists('h', $options)) {
$image = Image::newFromFile($filename);
}
if (array_key_exists('w', $options) && !array_key_exists('h', $options)) {
$image = Image::thumbnail($filename, $options['w'], ['height' => $this->defaultH]);
}
if (!array_key_exists('w', $options) && array_key_exists('h', $options)) {
$image = Image::thumbnail($filename, $this->defaultW, ['height' => $options['h']]);
}
if (array_key_exists('w', $options) && array_key_exists('h', $options)) {
if (array_key_exists('canv', $options) && ($options['canv'] == true)) {
$image = Image::thumbnail($filename, $options['w'], ['height' => $options['h']]);
$widthH = ($options['h'] - $image->height) / 2;
$widthW = ($options['w'] - $image->width) / 2;
$image = $image->embed(
$widthW,
$widthH,
$options['w'],
$options['h'],
['extend' => 'background', 'background' => 1024]
);
} else {
$image = Image::thumbnail($filename, $options['w'], ['height' => $options['h'], 'crop' => 'centre']);
}
}
if (array_key_exists('brightness', $options) || array_key_exists('saturation', $options) || array_key_exists('hue', $options)) {
$image = $this->brightness($image, array_key_exists('brightness', $options) ? $options['brightness'] : 1.0, array_key_exists('saturation', $options) ? $options['saturation'] : 1.0, array_key_exists('hue', $options) ? $options['hue'] : 0.0);
}
if (array_key_exists('rotation', $options)) {
$image = $image->rotate($options['rotation']);
}
if (array_key_exists('flip', $options)) {
if ($options['flip'] == "h") {
$image = $image->fliphor();
}
if ($options['flip'] == "v") {
$image = $image->flipver();
}
if ($options['flip'] == "hv") {
$image = $image->fliphor();
$image = $image->flipver();
}
}
if (array_key_exists('q', $options)) {
$saveOptions['Q'] = $options['q'];
}
return $image->writeToBuffer("." . app()->file->ext, $saveOptions);
}
public function process(string $filename, string $target, array $options = [], $saveOptions = ['Q' => 100])
{

5
composer.json

@ -7,12 +7,13 @@
"require": {
"php": "^8.0.2",
"guzzlehttp/guzzle": "^7.2",
"jcupitt/vips": "2.0.0",
"jenssegers/agent": "^2.6",
"jenssegers/mongodb": "^3.9",
"kosinix/grafika": "^2.0",
"laravel/framework": "^9.19",
"laravel/sanctum": "^2.14.1",
"laravel/tinker": "^2.7",
"jcupitt/vips" : "2.0.0"
"laravel/tinker": "^2.7"
},
"require-dev": {
"brianium/paratest": "^6.5",

47
composer.lock

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "aa091ad8935a98954cd65fdb252e3ab7",
"content-hash": "5ccb92d0caa97ee80e3508d0b7941f1c",
"packages": [
{
"name": "brick/math",
@ -1230,6 +1230,51 @@
],
"time": "2022-06-29T19:04:13+00:00"
},
{
"name": "kosinix/grafika",
"version": "2.0.8",
"source": {
"type": "git",
"url": "https://github.com/kosinix/grafika.git",
"reference": "211f61fc334b8b36616b23e8af7c5727971d96ee"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/kosinix/grafika/zipball/211f61fc334b8b36616b23e8af7c5727971d96ee",
"reference": "211f61fc334b8b36616b23e8af7c5727971d96ee",
"shasum": ""
},
"require": {
"php": ">=5.3"
},
"type": "library",
"autoload": {
"psr-4": {
"Grafika\\": "src/Grafika"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT",
"GPL-2.0+"
],
"authors": [
{
"name": "Nico Amarilla",
"homepage": "https://www.kosinix.com"
}
],
"description": "An image manipulation library for PHP.",
"homepage": "http://kosinix.github.io/grafika",
"keywords": [
"grafika"
],
"support": {
"issues": "https://github.com/kosinix/grafika/issues",
"source": "https://github.com/kosinix/grafika/tree/develop"
},
"time": "2017-06-20T03:13:49+00:00"
},
{
"name": "laravel/framework",
"version": "v9.21.6",

6
database/factories/BaseFactory.php

@ -62,10 +62,10 @@ trait BaseFactory
return rand($min + 1, $min + 100);
}
public function withDependency()
public function withDependency($dependencyAttributes = [])
{
return $this->state(function (array $attributes) {
return $this->dependencyProvider();
return $this->state(function (array $attributes) use ($dependencyAttributes) {
return $this->dependencyProvider($dependencyAttributes);
});
}

20
database/factories/CollectionFactory.php

@ -20,19 +20,19 @@ class CollectionFactory extends Factory
{
return [
"name" => fake()->name(),
"public" => rand(0,1),
"public" => rand(0, 1),
"disk" => "local",
"count" => rand(3, 18),
"tmp_support" => rand(0, 1) ,
"remove_tmp_time" => "2022-07-27 09:17:59",
"max_file_size" => rand(300, 2000),
"min_file_size" => rand(300, 2000),
"max_width" => rand(300, 2000),
"min_width" => rand(300, 2000),
"max_height" => rand(300, 2000),
"min_height" => rand(300, 2000),
"alt_required" => rand(0, 1) ,
"description_required" => rand(0, 1) ,
'alt_required' => false,
'description_required' => false,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0,
"exts" => [
"jpg",
"jpeg",
@ -61,7 +61,7 @@ class CollectionFactory extends Factory
];
}
public function dependencyProvider()
public function dependencyProvider($dependencyAttributes = [])
{
return [];
}

2
database/factories/Documents/PolicyDocumentFactory.php

@ -24,7 +24,7 @@ class PolicyDocumentFactory extends Factory
];
}
public function dependencyProvider()
public function dependencyProvider($dependencyAttributes= [])
{
return [];
}

28
database/factories/FileFactory.php

@ -2,9 +2,11 @@
namespace Database\Factories;
use App\Image\ImageProcessor;
use App\Models\Collection;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
/**
@ -13,6 +15,9 @@ use Illuminate\Support\Str;
class FileFactory extends Factory
{
use BaseFactory;
private $uuid = null;
/**
* Define the model's default state.
*
@ -20,8 +25,9 @@ class FileFactory extends Factory
*/
public function definition()
{
$this->uuid = app()->uuid;
return [
"uuid" => app()->uuid,
"uuid" => $this->uuid,
"original_name" => fake()->name(),
"ext" => ['jpg', 'jpeg', 'png', 'webp'][rand(0, 3)],
"mimetype" => 'image',
@ -35,7 +41,7 @@ class FileFactory extends Factory
'jhsf asduyfsadf sadf safsuf isfjsdfsudifsduiyf sdiuf sd'
],
"description" => 'ajsfoisahjfoaspf asduf safsafjsh lh',
"user_id" => rand(43724, 382348),
"user_id" => 1,
"ip" => "127.0. 0.1",
// "collection_id" => $collection->id,
"published_at" => "2022-07-27 09:17:59",
@ -43,10 +49,24 @@ class FileFactory extends Factory
}
public function dependencyProvider()
public function dependencyProvider($dependencyAttributes = [])
{
if (array_key_exists('withImage', $dependencyAttributes)) {
if ($dependencyAttributes['withImage'] == true) {
unset($dependencyAttributes['withImage']);
$collection = Collection::factory()->createQuietly($dependencyAttributes);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path('/' . date('y') . '/' . date('m') . '/' . $this->uuid . '.' . $collection->ext));
}
} else {
$collection = Collection::factory()->createQuietly($dependencyAttributes);
}
return [
'collection_id' => Collection::factory()->createQuietly()
'collection_id' => $collection
];
}
}

2
database/factories/ILaravelFactory.php

@ -57,7 +57,7 @@ class ILaravelFactory extends Factory
];
}
public function dependencyProvider()
public function dependencyProvider($dependencyAttributes= [])
{
return [
'user_id' => UserDocument::factory()->create()->id

2
database/factories/UserFactory.php

@ -34,7 +34,7 @@ class UserFactory extends Factory
return [];
}
public function dependencyProvider()
public function dependencyProvider($dependencyAttributes= [])
{
return [];
}

6
routes/api.php

@ -24,7 +24,7 @@ use Illuminate\Support\Facades\Storage;
Route::get('newTmp/{uuid}', function ($uuid) {
$file = File::find($uuid);
return Storage::disk('local')->temporaryUrl($file->server_path . $file->uuid . '.webp', now()->addMinutes(5),['collection_name'=>'Paris Renner II']);
return Storage::disk('local')->temporaryUrl($file->server_path . $file->uuid . '.webp', now()->addMinutes(5), ['collection_name' => 'Paris Renner II']);
})->name('newTmp');
@ -34,6 +34,6 @@ Route::group(['as' => 'api.'], function () {
Route::get('{collection_name}/{uuid}.{extention}', [FileController::class, 'show'])->name('files.show');
// Route::get('{collection_name}/{path}', [FileController::class, 'private'])->name('files.private');
Route::post('{collection_name}/{model_id?}', [FileController::class, 'store'])->name('files.store');
Route::put('{collection_name}/{uuid}.{extention}',[FileController::class,'update'])->name('files.update');
Route::delete('{collection_name}/{uuid}.{extention}',[FileController::class,'destroy'])->withTrashed()->name('files.destroy');
Route::put('{collection_name}/{uuid}.{extention}', [FileController::class, 'update'])->name('files.update');
Route::delete('{collection_name}/{uuid}.{extention}', [FileController::class, 'destroy'])->withTrashed()->name('files.destroy');
});

111
routes/web.php

@ -1,15 +1,6 @@
<?php
use App\Http\Controllers\FileController;
use App\Image\ImageProcessor;
use App\Image\Processor;
use App\Models\Collection;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Jcupitt\Vips\Config;
use Jcupitt\Vips\Extend;
use Jcupitt\Vips\Image;
use Jcupitt\Vips\Utils;
/*
|--------------------------------------------------------------------------
@ -21,105 +12,3 @@ use Jcupitt\Vips\Utils;
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/fuck',function(Request $request,ImageProcessor $imageProcessor)
{
$image = Image::thumbnail(storage_path('stub') . '/image.png', getimagesize(storage_path('stub') . '/image.png')[1]);
$image->writeToFile(public_path(). '/fuck.jpg',['Q'=> 100]);
// $imageProcessor->process(public_path('image.png'),public_path('image-modified.webp'));
// return response()->file(storage_path('stub') . '/image.png');
return response()->file(public_path(). '/fuck.jpg');
});
Route::get('/', function (Request $request) {
Collection::find(1)->getExts();
if (!isset($request->w) && !isset($request->h)) {
$image = Image::thumbnail('../public/image.png', getimagesize('../public/image.png')[0]);
}
if ($request->r) {
$rArray = explode(':', $request->r);
if (isset($request->w) && !isset($request->h)) {
$request->h = $request->w * $rArray[1];
$request->w = $request->w * $rArray[0];
}
if (!isset($request->w) && isset($request->h)) {
$request->h = $request->h * $rArray[1];
$request->w = $request->h * $rArray[0];
}
if (!isset($request->w) && !isset($request->h)) {
$request->h = getimagesize('../public/image.png')[0] * $rArray[1];
$request->w = getimagesize('../public/image.png')[0] * $rArray[0];
}
}
if (isset($request->w) && !isset($request->h)) {
$image = Image::thumbnail('../public/image.png', $request->w, ['height' => getimagesize('../public/image.png')[1]]);
}
if (!isset($request->w) && isset($request->h)) {
$image = Image::thumbnail('../public/image.png', getimagesize('../public/image.png')[0], ['height' => $request->h]);
}
if (isset($request->w) && isset($request->h) && !($request->canv == true)) {
$image = Image::thumbnail('../public/image.png', $request->w, ['height' => $request->h, 'crop' => 'centre']);
}
if (isset($request->w) && isset($request->h) && $request->canv == true) {
$image = Image::thumbnail('../public/image.png', $request->w, ['height' => $request->h]);
$widthH = ($request->h - $image->height) / 2;
$widthW = ($request->w - $image->width) / 2;
$image = $image->embed(
$widthW,
$widthH,
$request->w,
$request->h,
['extend' => 'background','background'=>1024]
);
}
if (isset($request->brightness) || isset($request->saturation) || isset($request->hue)) {
$image = Processor::brightness($image, isset($request->brightness) ? $request->brightness : 1.0, isset($request->saturation) ? $request->saturation : 1.0, isset($request->hue) ? $request->hue : 0.0);
}
if ($request->rotation) {
$image = $image->rotate($request->rotation);
}
if ($request->flip == "h") {
$image = $image->fliphor();
}
if ($request->flip == "v") {
$image = $image->flipver();
}
if ($request->flip == "hv") {
$image = $image->fliphor();
$image = $image->flipver();
}
$image->writeToFile(storage_path('image-modified.webp'), [
'Q' => isset($request->q) ? $request->q : 100
]);
return response()->file(public_path("image-modified.webp" . $request->ext));
});
Route::get('/upload',function(){
return view('welcome');
});
Route::post('/fuck',function(Request $request)
{
$request->all();
$storedImage = $request->file->storeAs('/addifsfsfsffuck', app()->uuid . '.' . 'webp', 'local');
});

BIN
storage/stub/image1.png

Binary file not shown.

Before

Width: 600  |  Height: 1200  |  Size: 620 KiB

8
tests/Base/FactoryMethodsTrait.php

@ -19,9 +19,9 @@ trait FactoryMethodsTrait
return Arr::except($model->toArray(), $model->getAppends());
}
public function one($class, $attributes = [])
public function one($class, $attributes = [], $dependencyAttributes = [])
{
return $class::factory()->withDependency()->createQuietly($attributes);
return $class::factory()->withDependency($dependencyAttributes)->createQuietly($attributes);
}
public function randomOne($class)
@ -29,9 +29,9 @@ trait FactoryMethodsTrait
return $class::inRandomOrder()->first();
}
public function trashed($class)
public function trashed($class, $dependencyAttributes = [])
{
$model = $this->one($class);
$model = $this->one($class,dependencyAttributes:$dependencyAttributes);
$model->delete();
$this->assertSoftDeleted($model);

53
tests/Feature/FileDeleteTest.php

@ -8,39 +8,40 @@ use App\Models\File;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Storage;
use Tests\Bootstrap;
use Tests\TestCase;
class FileDeleteTest extends TestCase
class FileDeleteTest extends Bootstrap
{
public function test_user_with_permission_can_not_delete_file()
{
$this->assertFalse("it's not mohammad's fault, I'm waiting for dynamic policy");
}
// public function test_user_with_permission_can_not_delete_file()
// {
// $this->assertFalse("it's not mohammad's fault, I'm waiting for dynamic policy");
// }
public function test_user_with_permission_can_delete_file()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0
]);
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'user_id' => auth()->id(),
'collection_id' => $collection->id
]);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path($file->server_path . $uuid . '.' . $collection->ext));
$file = $this->one(File::class, dependencyAttributes: ['withImage' => true]);
$collection = Collection::find($file->collection_id);
$response = $this->loginAs()->deleteJson(route('api.files.destroy', ['collection_name' => $collection->name, 'uuid' => $file->uuid, 'extention' => $collection->ext]));
$response->assertok();
}
public function test_file_restore_success()
{
$this->modelWithPolicy('collections', ['permission:collections.restore'])
->loginAsUser(['collections.restore'])
->deleteJson(route("api.collections.destroy", $collection = $this->trashed(Collection::class, dependencyAttributes: ['withImage' => true])))
->assertOk();
$this->loginAsAdmin()
->getJson(route("api.collections.show", $collection))
->assertOk();
}
public function test_file_delete_notFound()
{
$this->loginAsAdmin()
->deleteJson(route("api.files.destroy", ['collection_name' => 'not found', 'uuid' => 'wrong uuid', 'extention' => 'wrong ext']))
->assertNotFound();
}
}

47
tests/Feature/FileRestoreTest.php

@ -1,47 +0,0 @@
<?php
namespace Tests\Feature;
use App\Image\ImageProcessor;
use App\Models\Collection;
use App\Models\File;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class FileRestoreTest extends TestCase
{
public function test_user_with_permission_can_not_restore_file()
{
$this->assertFalse("it's not mohammad's fault, I'm waiting for dynamic policy");
}
public function test_user_with_permission_can_restore_file()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0
]);
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'user_id' => auth()->id(),
'collection_id' => $collection->id
]);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path($file->server_path . $uuid . '.' . $collection->ext));
$file->delete();
$response = $this->loginAs()->deleteJson(route('api.files.destroy', ['collection_name' => $collection->name, 'uuid' => $file->uuid, 'extention' => $collection->ext]));
$response->assertok();
}
}

29
tests/Feature/FileShowTest.php

@ -17,35 +17,12 @@ class FileShowTest extends TestCase
use FileShowTrait, FileImageTrait;
public function test_user_can_resize_image_with_width_and_height_fields_ok()
{
$models = $this->createCollectionAndFileModelWithImage();
$file = $this->one(File::class, dependencyAttributes: ['withImage' => true]);
$collection = Collection::find($file->collection_id);
$w = rand(10, 2000);
$h = rand(10, 2000);
$canv = rand(0, 1);
$response = $this->loginAs()->getJson(route('api.files.show', ['collection_name' => $models['collection']->name, 'uuid' => $models['file']->uuid, 'extention' => $models['collection']->ext, 'w' => $w, 'h' => $h, 'canv' => $canv]));
$response = $this->loginAs()->getJson(route('api.files.show', ['collection_name' => $collection->name, 'uuid' => $file->uuid, 'extention' => $collection->ext, 'w' => $w, 'h' => $h, 'canv' => $canv]));
$response->assertOk()->assertHeader('content-type', $response->headers->get('content-type'));
$this->assertEquals($w, getimagesize($response->getFile()->getPathname())[0]);
$this->assertEquals($h, getimagesize($response->getFile()->getPathname())[1]);
$this->deleteFakeImageForModel($models['file']);
}
// /**
// * @testWith ["test", 4,'1:fgvjjf']
// * ["longer-string", 13,'1:fgvjjf']
// */
// public function test_user_send_not_currect_value_to_file($w, $h, $r)
// {
// $models = $this->createCollectionAndFileModelWithImage();
// $canv = rand(0, 1);
// $response = $this->loginAs()->getJson(route('api.files.show', ['collection_name' => $models['collection']->name, 'uuid' => $models['file']->uuid, 'extention' => $models['collection']->ext, 'w' => $w, 'h' => $h, 'canv' => $canv]));
// $response->assertOk()->assertHeader('content-type', $response->headers->get('content-type'));
// $this->assertNotEquals($w, getimagesize($response->getFile()->getPathname())[0]);
// $this->assertNotEquals($h, getimagesize($response->getFile()->getPathname())[1]);
// $this->deleteFakeImageForModel($models['file']);
// }
}

102
tests/Feature/FileStoreTest.php

@ -83,11 +83,8 @@ class FileStoreTest extends Bootstrap
public function test_user_can_not_access_not_ownered_files()
{
$collection = Collection::factory()->createQuietly();
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'user_id' => auth()->id() + 1234,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'collection_id' => $collection->id
]);
@ -113,13 +110,6 @@ class FileStoreTest extends Bootstrap
public function test_store_static_validation_unprocessable()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => true,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0
]);
@ -141,20 +131,11 @@ class FileStoreTest extends Bootstrap
*/
public function test_store_dynamic_validation_stored_file_unprocessable($collectionFields)
{
$collection = Collection::factory()->createQuietly($collectionFields);
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'user_id' => auth()->id(),
'collection_id' => $collection->id
]);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path($file->server_path . $uuid . '.' . $collection->ext));
$collectionFields['withImage'] = true;
$file = $this->one(File::class, dependencyAttributes: $collectionFields);
$collection = Collection::find($file->collection_id);
$data = [
"file" => $file->uuid,
"public" => 1
];
$response = $this->loginAs()->postJson(route('api.files.store', ['collection_name' => $collection->name]), $data);
@ -163,27 +144,13 @@ class FileStoreTest extends Bootstrap
public function test_user_can_store_sent_file_count_multiple_without_image_processor_ok()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0
]);
$uuid = app()->uuid;
$this->one(File::class, [
'uuid' => $uuid,
'user_id' => auth()->id(),
'collection_id' => $collection->id,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
]);
$collectionFields['withImage'] = true;
$file = $this->one(File::class, dependencyAttributes: $collectionFields);
$collection = Collection::find($file->collection_id);
$data = [
"file" => UploadedFile::fake()->image('test.png'),
"public" => 1
];
$response = $this->loginAs()->postJson(route('api.files.store', ['collection_name' => $collection->name]), $data);
$response->assertCreated();
@ -191,25 +158,9 @@ class FileStoreTest extends Bootstrap
public function test_user_can_store_sent_file_uuid_count_multiple_without_image_processor_ok()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0
]);
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'user_id' => auth()->id(),
'collection_id' => $collection->id
]);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path($file->server_path . $uuid . '.' . $collection->ext));
$collectionFields['withImage'] = true;
$file = $this->one(File::class, dependencyAttributes: $collectionFields);
$collection = Collection::find($file->collection_id);
$data = [
"file" => $file->uuid,
@ -223,14 +174,6 @@ class FileStoreTest extends Bootstrap
public function test_user_can_store_sent_file_count_one_without_image_processor_ok()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => false,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0,
'count' => 1
]);
@ -246,26 +189,11 @@ class FileStoreTest extends Bootstrap
public function test_user_can_store_sent_file_uuid_count_one_without_image_processor_ok()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => false,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0,
'count' => 1
]);
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'user_id' => auth()->id(),
'collection_id' => $collection->id
]);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path($file->server_path . $uuid . '.' . $collection->ext));
$collectionFields['withImage'] = true;
$collectionFields['count'] = 1;
$file = $this->one(File::class, dependencyAttributes: $collectionFields);
$collection = Collection::find($file->collection_id);
$data = [
"file" => $file->uuid,

49
tests/Feature/FileUpdateTest.php

@ -14,10 +14,11 @@ use Tests\TestCase;
class FileUpdateTest extends TestCase
{
use FileTraits;
public function test_user_can_not_access_update_without_permission()
{
$this->assertFalse("it's not mohammad's fault, I'm waiting for dynamic policy");
}
// public function test_user_can_not_access_update_without_permission()
// {
// $this->assertFalse("it's not mohammad's fault, I'm waiting for dynamic policy");
// }
public function test_user_update_not_exits_files_not_found()
{
@ -30,46 +31,10 @@ class FileUpdateTest extends TestCase
$response->assertNotFound();
}
// /**
// * @dataProvider updateValidationTestProvider
// */
// public function test_user_send_unproccable_fileds($collectionFields, $dataFields)
// {
// $collection = Collection::factory()->create($collectionFields);
// $uuid = app()->uuid;
// $file = File::factory()->createQuietly([
// 'uuid' => $uuid,
// 'server_path' => '/' . date('y') . '/' . date('m') . '/',
// 'user_id' => auth()->id(),
// 'collection_id' => $collection->id
// ]);
// $response = $this->loginAs()->postJson(route('api.files.update', ['collection_name' => $collection->name, 'uuid' => $file->uuid, 'ext' => $collection->ext]), $dataFields);
// $response->assertUnprocessable();
// }
public function test_user_can_update_file()
{
$collection = Collection::factory()->createQuietly([
'alt_required' => false,
'description_required' => false,
'tmp_support' => true,
'max_width' => 2000,
'max_height' => 2000,
'min_width' => 1,
'min_height' => 1,
'min_file_size' => 0
]);
$uuid = app()->uuid;
$file = File::factory()->createQuietly([
'uuid' => $uuid,
'server_path' => '/' . date('y') . '/' . date('m') . '/',
'user_id' => auth()->id(),
'collection_id' => $collection->id
]);
$imageProcessor = new ImageProcessor;
$imageProcessor->createFakeImage(storage_path('stub') . '/image.png', Storage::disk($collection->disk)->path($file->server_path . $uuid . '.' . $collection->ext));
$file = $this->one(File::class, dependencyAttributes: ['withImage' => true]);
$collection = Collection::find($file->collection_id);
$data = [
"original_name" => 'original name is very bad',

Loading…
Cancel
Save