SchemaCheckTrait.php in Drupal 8
File
core/lib/Drupal/Core/Config/Schema/SchemaCheckTrait.php
View source
<?php
namespace Drupal\Core\Config\Schema;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\TypedData\PrimitiveInterface;
use Drupal\Core\TypedData\TraversableTypedDataInterface;
use Drupal\Core\TypedData\Type\BooleanInterface;
use Drupal\Core\TypedData\Type\StringInterface;
use Drupal\Core\TypedData\Type\FloatInterface;
use Drupal\Core\TypedData\Type\IntegerInterface;
trait SchemaCheckTrait {
protected $schema;
protected $configName;
public function checkConfigSchema(TypedConfigManagerInterface $typed_config, $config_name, $config_data) {
if (!isset($config_data['langcode'])) {
$config_data['langcode'] = 'en';
}
$this->configName = $config_name;
if (!$typed_config
->hasConfigSchema($config_name)) {
return FALSE;
}
$this->schema = $typed_config
->createFromNameAndData($config_name, $config_data);
$errors = [];
foreach ($config_data as $key => $value) {
$errors = array_merge($errors, $this
->checkValue($key, $value));
}
if (empty($errors)) {
return TRUE;
}
return $errors;
}
protected function checkValue($key, $value) {
$error_key = $this->configName . ':' . $key;
$element = $this->schema
->get($key);
if ($element instanceof Undefined) {
return [
$error_key => 'missing schema',
];
}
if ($element && $element instanceof Ignore) {
return [];
}
if ($element && is_scalar($value) || $value === NULL) {
$success = FALSE;
$type = gettype($value);
if ($element instanceof PrimitiveInterface) {
$success = $type == 'integer' && $element instanceof IntegerInterface || ($type == 'double' || $type == 'integer') && $element instanceof FloatInterface || $type == 'boolean' && $element instanceof BooleanInterface || $type == 'string' && $element instanceof StringInterface || $value === NULL;
}
elseif ($element instanceof ArrayElement && $element
->isNullable() && $value === NULL) {
$success = TRUE;
}
$class = get_class($element);
if (!$success) {
return [
$error_key => "variable type is {$type} but applied schema class is {$class}",
];
}
}
else {
$errors = [];
if (!$element instanceof TraversableTypedDataInterface) {
$errors[$error_key] = 'non-scalar value but not defined as an array (such as mapping or sequence)';
}
if (!is_array($value)) {
$value = (array) $value;
}
foreach ($value as $nested_value_key => $nested_value) {
$errors = array_merge($errors, $this
->checkValue($key . '.' . $nested_value_key, $nested_value));
}
return $errors;
}
return [];
}
}