135 lines
3 KiB
PHP
135 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\ContactFormType;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class Contact extends Model
|
|
{
|
|
/**
|
|
* The primary key for the model.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $primaryKey = 'date';
|
|
|
|
/**
|
|
* Indicates if the model should be timestamped.
|
|
*
|
|
* @var boolean
|
|
*/
|
|
public $timestamps = false;
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted()
|
|
{
|
|
static::creating(function ($contact) {
|
|
$contact->date = date('Y-m-d');
|
|
return $contact;
|
|
});
|
|
static::updating(function ($contact) {
|
|
// * increment general counter
|
|
$contact->all++;
|
|
return $contact;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Increments the ContactFormType stats of today
|
|
*
|
|
* @param ContactFormType $type
|
|
* @return void
|
|
*/
|
|
public static function incrementStat(ContactFormType $type)
|
|
{
|
|
$contact = static::where('date', '=', date('Y-m-d'))->firstOrNew();
|
|
// * Can't do $contact->counter[$type->value]++ => ErrorException
|
|
$d = $contact->values;
|
|
$d[$type->value]++;
|
|
$contact->values = $d;
|
|
$contact->save();
|
|
}
|
|
|
|
/**
|
|
* Get values attribute
|
|
*
|
|
* @param mixed $value
|
|
* @return array
|
|
*/
|
|
public function getValuesAttribute($value): array
|
|
{
|
|
return $this->unserialize($value ?? serialize($this->counterSkeleton()));
|
|
}
|
|
|
|
/**
|
|
* Set values attribute
|
|
*
|
|
* @param array $value
|
|
* @return string
|
|
*/
|
|
public function setValuesAttribute(array $value): string
|
|
{
|
|
$this->attributes['values'] = $this->serialize($value);
|
|
return $this->attributes['values'];
|
|
}
|
|
|
|
/**
|
|
* Serialize value
|
|
*
|
|
* @param array $value
|
|
* @return string
|
|
*/
|
|
private function serialize(array $value)
|
|
{
|
|
return serialize($this->merge($this->counterSkeleton(), $value));
|
|
}
|
|
|
|
/**
|
|
* Unserialize value
|
|
*
|
|
* @param string $value
|
|
* @return array
|
|
*/
|
|
private function unserialize(string $value)
|
|
{
|
|
return $this->merge($this->counterSkeleton(), unserialize($value));
|
|
}
|
|
|
|
/**
|
|
* Merge thow array
|
|
*
|
|
* TODO: Replace this with collection or array merge.
|
|
*
|
|
* @param array $a
|
|
* @param array $b
|
|
* @return array
|
|
*/
|
|
private function merge(array $a, array $b): array
|
|
{
|
|
foreach ($a as $i => $v) {
|
|
if (isset($b[$i])) {
|
|
$a[$i] = $b[$i];
|
|
}
|
|
}
|
|
return $a;
|
|
}
|
|
|
|
/**
|
|
* Get Counter skeleton
|
|
* @return array
|
|
*/
|
|
private function counterSkeleton(): array
|
|
{
|
|
return collect(ContactFormType::toArray())->mapWithKeys(function (ContactFormType $enum) {
|
|
if ($enum->equals(ContactFormType::none())) {
|
|
return [];
|
|
}
|
|
return [$enum->value => 0];
|
|
})->toArray();
|
|
}
|
|
}
|