ModelColumn.php 1.53 KB
<?php

namespace App\Support;

use Illuminate\Support\Arr;

class ModelColumn
{
    public array $map;

    public array $keys;

    public function __construct(array $map, array $keys)
    {
        $this->map  = $map;
        $this->keys = $keys;
    }

    /**
     * @param float|array|int|string $keys
     * @return $this
     */
    public function add(float|array|int|string $keys): ModelColumn
    {
        $this->keys = Arr::flatten([$this->keys, Arr::wrap($keys)]);
        return $this;
    }

    /**
     * @param float|array|int|string $keys
     * @return \App\Support\ModelColumn
     */
    public function except(float|array|int|string $keys): ModelColumn
    {
        $this->keys = Arr::except($this->keys, $keys);
        return $this;
    }

    /**
     * @return bool
     */
    public function isEmpty(): bool
    {
        return count($this->toArray()) === 0;
    }

    /**
     * @param string $prefix
     * @return string
     */
    public function format(string $prefix = ''): string
    {
        return $this->isEmpty() ? '' : $prefix . $this->toString();
    }

    /**
     * @return array
     */
    public function toArray(): array
    {
        return Arr::only($this->map, $this->keys);
    }

    /**
     * @param string $separator
     * @return string
     */
    public function toString(string $separator = ','): string
    {
        return implode($separator, $this->toArray());
    }

    /**
     * @return string
     */
    public function __toString(): string
    {
        return $this->toString();
    }
}