Skip to content
This repository has been archived by the owner on Sep 30, 2024. It is now read-only.

Commit

Permalink
adds mutiple_value_processor plugin for datapipe
Browse files Browse the repository at this point in the history
  • Loading branch information
vincent-gao committed Jul 18, 2024
1 parent 396efb2 commit a8aba94
Showing 1 changed file with 74 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

declare(strict_types=1);

namespace Drupal\tide_search\Plugin\DatasetTransform;

use Drupal\data_pipelines\DatasetData;
use Drupal\data_pipelines\Transform\TransformPluginBase;

/**
* Splits a string into multiple values and optionally processes them.
*
* @DatasetTransform(
* id="mutiple_value_processor",
* fields=TRUE,
* records=FALSE
* )
*/
class MutipleValueProcessor extends TransformPluginBase {

/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return parent::defaultConfiguration() + [
'separator' => '',
'callback' => NULL,
'parameters' => [],
];
}

/**
* {@inheritdoc}
*/
protected function doTransformField(string $field_name, DatasetData $record): DatasetData {
$record = parent::doTransformRecord($record);
if ($record->offsetExists($field_name) && !empty($record[$field_name])) {
$separator = $this->configuration['separator'];
$callback = $this->configuration['callback'];
$parameters = $this->configuration['parameters'];
$parts = explode($separator, $record[$field_name]);
$cleaned_parts = array_values(array_filter(array_map('trim', $parts), function ($part) {
return $part !== '';
}));

// Process the parts if a callback is provided.
if (is_callable($callback)) {
$cleaned_parts = array_map(function ($value) use ($callback, $parameters) {
$typed_parameters = array_map([$this, 'convertParameter'], $parameters);
return call_user_func_array($callback, array_merge([$value], $typed_parameters));
}, $cleaned_parts);
}
$record[$field_name] = $cleaned_parts;
}
return $record;
}

/**
* Converts a parameter to its appropriate type.
*/
private function convertParameter($parameter) {
if (is_numeric($parameter)) {
return $parameter + 0;
}
if ($parameter === 'true' || $parameter === 'false') {
return $parameter === 'true';
}
if (defined($parameter)) {
return constant($parameter);
}
return $parameter;
}

}

0 comments on commit a8aba94

Please sign in to comment.