ConfigurableResourceType.php in JSON:API Extras 8.3
File
src/ResourceType/ConfigurableResourceType.php
View source
<?php
namespace Drupal\jsonapi_extras\ResourceType;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\jsonapi\ResourceType\ResourceType;
use Drupal\jsonapi_extras\Entity\JsonapiResourceConfig;
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerManager;
use Drupal\Core\Config\ConfigFactoryInterface;
class ConfigurableResourceType extends ResourceType {
use DependencySerializationTrait;
protected $jsonapiResourceConfig;
protected $enhancerManager;
protected $configFactory;
protected $cache = [];
public function getJsonapiResourceConfig() {
return $this->jsonapiResourceConfig;
}
public function setJsonapiResourceConfig(JsonapiResourceConfig $resource_config) {
$this->jsonapiResourceConfig = $resource_config;
if ($name = $resource_config
->get('resourceType')) {
$this->typeName = $name;
}
}
public function includeCount() {
return $this->configFactory
->get('jsonapi_extras.settings')
->get('include_count');
}
public function getPath() {
$resource_config = $this
->getJsonapiResourceConfig();
if (!$resource_config) {
return parent::getPath();
}
$config_path = $resource_config
->get('path');
if (!$config_path) {
return parent::getPath();
}
return '/' . ltrim($config_path, '/');
}
public function getResourceFieldConfiguration($field_name, $from = 'fieldName') {
$cid = "{$field_name}:{$from}";
if (isset($this->cache[$cid]) || array_key_exists($cid, $this->cache)) {
return $this->cache[$cid];
}
$resource_fields = $this
->getJsonapiResourceConfig()
->get('resourceFields');
$found = array_filter($resource_fields, function ($resource_field) use ($field_name, $from) {
return !empty($resource_field[$from]) && $field_name == $resource_field[$from];
});
$result = empty($found) ? NULL : reset($found);
$this->cache[$cid] = $result;
return $result;
}
public function setConfigFactory(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public function setEnhancerManager(ResourceFieldEnhancerManager $enhancer_manager) {
$this->enhancerManager = $enhancer_manager;
}
public function getFieldEnhancer($field_name, $from = 'fieldName') {
if (!($resource_field = $this
->getResourceFieldConfiguration($field_name, $from))) {
return NULL;
}
if (empty($resource_field['enhancer']['id'])) {
return NULL;
}
try {
$enhancer_info = $resource_field['enhancer'];
$settings = [];
if (!empty($enhancer_info['settings']) && is_array($enhancer_info['settings'])) {
$settings = $enhancer_info['settings'];
}
$enhancer = $this->enhancerManager
->createInstance($enhancer_info['id'], $settings);
return $enhancer;
} catch (PluginException $exception) {
return NULL;
}
}
}