87 lines
2.6 KiB
PHP
87 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Resources\File;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Resources\Json\ResourceCollection;
|
|
|
|
class FileCollection extends ResourceCollection
|
|
{
|
|
/**
|
|
* Transform the resource collection into an array.
|
|
*
|
|
* @return array<int|string, mixed>
|
|
*/
|
|
public function toArray(Request $request): array
|
|
{
|
|
return [
|
|
'data' => FileResource::collection($this->collection),
|
|
'pagination' => [
|
|
'current_page' => $this->currentPage(),
|
|
'from' => $this->firstItem(),
|
|
'last_page' => $this->lastPage(),
|
|
'per_page' => $this->perPage(),
|
|
'to' => $this->lastItem(),
|
|
'total' => $this->total(),
|
|
'has_more_pages' => $this->hasMorePages(),
|
|
],
|
|
'summary' => [
|
|
'total_files' => $this->collection->count(),
|
|
'total_size' => $this->collection->sum('size_bytes'),
|
|
'total_size_formatted' => $this->formatBytes($this->collection->sum('size_bytes')),
|
|
'categories' => $this->getCategoryStats(),
|
|
],
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Calculate category statistics from the collection
|
|
*/
|
|
private function getCategoryStats(): array
|
|
{
|
|
$categories = [];
|
|
|
|
foreach ($this->collection as $file) {
|
|
$pathParts = explode('/', $file->storage_uri);
|
|
$category = $pathParts[count($pathParts) - 3] ?? 'general';
|
|
|
|
if (!isset($categories[$category])) {
|
|
$categories[$category] = [
|
|
'count' => 0,
|
|
'total_size' => 0,
|
|
'files' => []
|
|
];
|
|
}
|
|
|
|
$categories[$category]['count']++;
|
|
$categories[$category]['total_size'] += $file->size_bytes ?? 0;
|
|
$categories[$category]['files'][] = $file->file_name;
|
|
}
|
|
|
|
// Format sizes
|
|
foreach ($categories as $category => &$stats) {
|
|
$stats['total_size_formatted'] = $this->formatBytes($stats['total_size']);
|
|
// Remove file list to avoid too much data in collection
|
|
unset($stats['files']);
|
|
}
|
|
|
|
return $categories;
|
|
}
|
|
|
|
/**
|
|
* Format bytes to human readable format
|
|
*/
|
|
private function formatBytes(int $bytes, int $precision = 2): string
|
|
{
|
|
if ($bytes === 0) {
|
|
return '0 B';
|
|
}
|
|
|
|
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
$base = 1024;
|
|
$factor = floor((strlen($bytes) - 1) / 3);
|
|
|
|
return sprintf("%.{$precision}f", $bytes / pow($base, $factor)) . ' ' . $units[$factor];
|
|
}
|
|
}
|