<?php
|
namespace JVBase\integrations;
|
|
if (!defined('ABSPATH')) {
|
exit;
|
}
|
|
class Endpoint {
|
protected string $endpoint;
|
protected array $fields;
|
public function __construct(string $endpoint) {
|
$this->endpoint = $endpoint;
|
}
|
|
public function getEndpoint():string
|
{
|
return $this->endpoint;
|
}
|
|
public function addIdempotencyKey(?string $key = null):EndpointField
|
{
|
if (is_null($key)) {
|
$key = wp_generate_uuid4();
|
}
|
$field = new EndpointField('idempotency_key');
|
$this->fields['idempotency_key'] = $field;
|
return $field;
|
}
|
|
public function getFields():array
|
{
|
return $this->fields;
|
}
|
public function addField(string $slug, array $data = []):EndpointField
|
{
|
$slug = EndpointField::sanitizeSlug($slug);
|
$field = new EndpointField($slug);
|
if (!empty($data)) {
|
foreach ($data as $key => $value) {
|
if ($key === 'required' && $value !== false) {
|
$field->setRequired();
|
} elseif (property_exists($field, $key)) {
|
$method = 'set'.implode('',array_map('ucfirst', explode('_',$key)));
|
if (method_exists($field, $method)) {
|
$field->$method($value);
|
}
|
}
|
}
|
}
|
$this->fields[$slug] = $field;
|
return $field;
|
}
|
public function checkFields(array $fields):array|false
|
{
|
$fields = array_filter($fields, function ($f) use ($fields) {
|
if (!array_key_exists($f, $this->fields)) {
|
error_log('Endpoint '.$this->endpoint.'::checkFields removing field because it is not defined: '.print_r($fields[$f], true));
|
return false;
|
}
|
return true;
|
}, ARRAY_FILTER_USE_KEY);
|
|
$required = array_filter($this->fields, function ($f) {
|
return $f->isRequired();
|
});
|
|
$missing = [];
|
foreach ($required as $field => $config) {
|
if (!array_key_exists($field, $fields) || empty($fields[$field])) {
|
error_log('Endpoint '.$this->endpoint.'::checkFields required field not found: '.$field);
|
$missing[] = $field;
|
}
|
}
|
if (!empty($missing)) {
|
return false;
|
}
|
|
foreach ($fields as $field => $value) {
|
$test = $this->fields[$field]->validate($value);
|
if (!$test) {
|
error_log('Endpoint '.$this->endpoint.'::checkFields could not validate value for '.$field.': '.print_r($value, true));
|
unset($fields[$field]);
|
}
|
}
|
|
return $fields;
|
}
|
}
|