<?php

declare(strict_types=1);

namespace Core\General\Formatter;

use Carbon\Carbon;
use Core\General\Helper\DateTimeHelper;

abstract class Formatter
{
    /**
     * @return ($field is Carbon ? string : null)
     */
    protected function formatNullableCarbonField(?Carbon $field, string $format = DateTimeHelper::ISO8601): ?string
    {
        if (!$field instanceof Carbon) {
            return null;
        }

        if (\in_array($format, DateTimeHelper::VALID_FORMATS)) {
            return $field->format($format);
        }

        return $field->toIso8601String();
    }

    /**
     * @return ($field is string ? string : string|null)
     */
    protected function formatStringField(?string $field, bool $castNullToEmptyString = false): ?string
    {
        if ($field === null && $castNullToEmptyString) {
            return (string) $field;
        }

        return $field;
    }
}
