<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class HttpToHttps implements CastsAttributes
{
    public function get($model, string $key, $value, array $attributes)
    {
        return static::replace($value);
    }

    public function set($model, string $key, $value, array $attributes)
    {
        return static::replace($value);
    }

    private static function replace($value): string
    {
        if (!$value) {
            return $value;
        }

        $value = str_replace('http://', 'https://', $value);
        $value = str_replace('-internal', '', $value);

        $arr = explode('/', $value);
        array_shift($arr);
        array_shift($arr);
        array_shift($arr);
        $baseUrl = env('ALI_OSS_URL', 'https://zhangsiyecdn.9026.com/');

        return $baseUrl . implode('/', $arr);
    }
}
