Jake Vanderwerf
5 days ago 0dfe1d8afafc59c4a5559c498342668d5a58d6ef
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
namespace JVBase\integrations;
 
use Closure;
use JVBase\meta\Meta;
use JVBase\meta\Validator;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class EndpointField {
    protected string $slug;
    protected string $type = 'text';
    protected bool $required = false;
    protected Closure $validation;
    public function __construct(string $slug)
    {
        $this->slug = self::sanitizeSlug($slug);
    }
 
    public function setRequired():void
    {
        $this->required = true;
    }
    public function isRequired():bool
    {
        return $this->required;
    }
 
    public function setValidation(callable $validation):void
    {
        $this->validation = Closure::fromCallable($validation);
    }
    public function handleValidation(mixed $data):bool|null
    {
        if (is_callable($this->validation)) {
            return ($this->validation)($data);
        }
        return null;
    }
 
    public static function sanitizeSlug(string $slug):string
    {
        return str_replace('-','_', sanitize_title($slug));
    }
    public function validate(mixed $value):bool
    {
        $result = $this->handleValidation($value);
        if (is_null($result) && !empty($this->type)) {
            error_log('Handling validation with the Meta Validator.php class');
            Validator::validate($value, ['type' => $this->type]);
        }
        error_log('No validation set for '.$this->slug.' endpoint field');
        return true;
    }
}