tethys/app/Models/File.php

88 lines
2.3 KiB
PHP
Raw Permalink Normal View History

2018-08-29 15:18:15 +00:00
<?php
namespace App\Models;
2018-09-10 13:09:10 +00:00
use App\Models\Dataset;
2018-08-29 15:18:15 +00:00
use App\Models\HashValue;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
2018-08-29 15:18:15 +00:00
class File extends Model
{
use HasFactory;
2018-08-29 15:18:15 +00:00
protected $table = 'document_files';
public $timestamps = true;
protected $fillable = ['path_name', 'file_size', 'mime_type', 'label', 'sort_order'];
public function dataset()
{
return $this->belongsTo(Dataset::class, 'document_id', 'id');
}
public function hashvalues()
{
return $this->hasMany(HashValue::class, 'file_id', 'id');
}
/**
2018-08-29 15:18:15 +00:00
* Create hash value model objects from original file.
*
* TODO throws Exception in case hash computation is not possible
* (e.g., if referenced file is missing in file system)
*
* @return void
*/
public function createHashValues()
{
$hashtypes = array('md5', 'sha512');
2018-08-29 15:18:15 +00:00
foreach ($hashtypes as $type) {
$hash = new HashValue();
$hash->type = $type;
$hashString = $this->getRealHash($type);
$hash->value = $hashString;
$this->hashvalues()->save($hash);
}
}
/**
2018-08-29 15:18:15 +00:00
* Get the hash value of the file
*
* @param string $type Type of the hash value, @see hash_file();
* @return string hash value
*/
private function getRealHash($type)
{
$hash = @hash_file($type, $this->getPath());
if (empty($hash)) {
throw new \Exception("Empty HASH for file '" . $this->getPath() . "'");
}
return $hash;
}
/**
* Get full path of destination file.
*/
private function getPath()
{
//return storage_path('app/public/' . $this->path_name);
return public_path('storage/' . $this->path_name);
2018-08-29 15:18:15 +00:00
}
2018-10-11 14:49:08 +00:00
public function exists()
{
return \Illuminate\Support\Facades\File::exists(public_path('storage/' . $this->path_name));
}
public function formatSize($precision = 1)
{
$size = $this->file_size;
$unit = ['Byte', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
for ($i = 0; $size >= 1024 && $i < count($unit) - 1; $i++) {
$size /= 1024;
}
return round($size, $precision) . ' ' . $unit[$i];
}
2018-08-29 15:18:15 +00:00
}