Model.php 2.05 KB
<?php

namespace App\Support;

use App\Traits\DateTimeTrait;
use Awobaz\Compoships\Compoships;
use EloquentFilter\Filterable;
use EloquentFilter\ModelFilter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as BaseModel;
use Illuminate\Support\Arr;

/**
 * @method static Builder filter(array $input, null|string|ModelFilter $filter = NULL)
 * @method static Builder orderByField(string $column, array $value)
 */
class Model extends BaseModel
{
    use DateTimeTrait, Filterable, Compoships;

    /**
     * @var int
     */
    protected $perPage = 20;

    /**
     * @var array<string,string>
     */
    public array $columnMap = [];

    /**
     * @param object|array<string|int, mixed> $array
     * @param string                          $prepend
     * @return array<string,mixed>
     */
    public static function dot(object|array|null $array, string $prepend = '', string $connect = '->'): array
    {

        $results = [];

        if (!is_null($array)) {
            foreach ($array as $key => $value) {
                if (!empty($value) && is_array($value) && Arr::isAssoc($value)) {
                    $results = @array_merge($results, self::dot($value, $prepend . $key . $connect, $connect));
                } else {
                    $results[$prepend . $key] = $value;
                }
            }
        }

        return $results;
    }

    /**
     * @return \App\Support\ModelColumn
     */
    public function getChangeColumn(): ModelColumn
    {
        return new ModelColumn($this->columnMap, array_keys($this->getChanges()));
    }

    /**
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param string                                $column
     * @param array                                 $value
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeOrderByField(Builder $builder, string $column, array $value): Builder
    {
        return $builder
            ->whereIn($column, $value)
            ->orderByRaw("FIELD($column," . implode(',', $value) . ")");
    }
}