pastethingy/app/Paste.php

130 lines
2.1 KiB
PHP
Raw Normal View History

2016-05-28 19:05:54 +02:00
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
2016-05-29 02:14:29 +02:00
use Carbon\Carbon;
use Storage;
2016-05-28 19:05:54 +02:00
class Paste extends Model
{
2016-05-28 22:43:44 +02:00
public $incrementing = false;
public $timestamps = false;
2016-05-29 17:32:30 +02:00
public static function create_id()
{
//TODO: Check if id is unique
$characters = 'abcdefghijklmnopqrstuvwxyz';
$id = '';
for($i = 0; $i < 6; $i++) //TODO: Make id length configurable (?)
{
$id .= $characters[rand(0, strlen($characters) -1)];
}
return $id;
}
2016-05-28 22:43:44 +02:00
public function deletion()
{
return $this->hasOne(Deletion::class);
}
2016-05-29 01:34:24 +02:00
public function soft_delete($reason, $deleted_by)
2016-05-28 22:43:44 +02:00
{
2016-05-29 02:14:29 +02:00
if($this->deleted)
2016-05-28 22:43:44 +02:00
{
return false;
}
$deletion = new Deletion;
$deletion->reason = $reason;
$deletion->deleted_by = $deleted_by;
$deletion->deleted_at = Carbon::now();
$this->deletion()->save($deletion);
return true;
}
2016-05-29 02:14:29 +02:00
public function try_hard_delete()
{
if(Storage::disk('ephemeral')->exists($this->id) && $this->has_expired)
{
Storage::disk('ephemeral')->delete($this->id);
}
2016-05-29 17:32:30 +02:00
}
2016-05-29 02:14:29 +02:00
public function getDeletedAttribute()
{
return $this->deletion !== null;
}
public function getExpiresAttribute()
{
return $this->expires_at !== null;
}
public function getHasExpiredAttribute()
{
return $this->expires && $this->expires_at < Carbon::now();
}
2016-05-29 04:21:18 +02:00
public function getIsFuturePasteAttribute()
{
return $this->created_at > Carbon::now();
}
2016-05-30 21:31:50 +02:00
public function getIdAttribute($value)
{
return trim($value);
}
2016-05-29 02:14:29 +02:00
public function getContentAttribute()
{
if($this->deleted)
{
return null;
}
if($this->expires)
{
if($this->has_expired)
{
$this->try_hard_delete();
return null;
}
else
{
return Storage::disk('ephemeral')->get($this->id);
}
}
else
{
return Storage::disk('persistent')->get($this->id);
}
}
public function setContentAttribute($content)
{
if($this->deleted || $this->has_expired)
{
//TODO: Throw an exception
return;
}
if($this->expires)
{
Storage::disk('ephemeral')->put($this->id, $content);
}
else
{
Storage::disk('persistent')->put($this->id, $content);
}
}
2016-05-28 19:05:54 +02:00
}