<?php

namespace wdigital\cms\inspinia\validators;

use yii\validators\Validator;

class Base64ImageValidator extends Validator
{
    /**
     * @inheritdoc
     */
    public function validateAttribute($model, $attribute): void
    {
        if (preg_match('/^data:image\/(\w+);base64,/', $model->$attribute, $type)) {
            $value = substr($model->$attribute, strpos($model->$attribute, ',') + 1);
            $type = strtolower($type[1]);

            if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
                $this->addError($model, $attribute, 'invalid image type');
            }

            $value = base64_decode($value);

            if ($value === false) {
                $this->addError($model, $attribute, 'Decoding image failed');
            }
        }
    }
}