FractionTarget.php in Fraction 8
File
src/Feeds/Target/FractionTarget.php
View source
<?php
namespace Drupal\fraction\Feeds\Target;
use Drupal\Core\Form\FormStateInterface;
use Drupal\feeds\Plugin\Type\Target\ConfigurableTargetInterface;
use Drupal\feeds\Plugin\Type\Target\FieldTargetBase;
use Drupal\fraction\Fraction;
class FractionTarget extends FieldTargetBase implements ConfigurableTargetInterface {
protected function importTypes() {
return [
'fraction' => $this
->t('Fraction'),
'decimal' => $this
->t('Decimal'),
];
}
public function defaultConfiguration() {
return [
'type' => 'fraction',
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['type'] = [
'#type' => 'select',
'#title' => $this
->t('Filter format'),
'#options' => $this
->importTypes(),
'#default_value' => $this->configuration['type'],
];
return $form;
}
public function getSummary() {
$types = $this
->importTypes();
return $this
->t('Import type: %type', [
'%type' => $types[$this->configuration['type']],
]);
}
protected function prepareValue($delta, array &$values) {
$item = trim($values['value']);
unset($values['value']);
switch ($this->configuration['type']) {
case 'fraction':
$parts = explode('/', $item);
if (!empty($parts[0]) && is_numeric($parts[0]) && !empty($parts[1]) && is_numeric($parts[1]) && $parts[1] >= 0) {
$values['numerator'] = $parts[0];
$values['denominator'] = $parts[1];
}
else {
$values['numerator'] = '';
$values['denominator'] = '';
}
break;
case 'decimal':
if (!is_numeric($item) || $item === '') {
$values['numerator'] = '';
$values['denominator'] = '';
}
else {
$fraction = Fraction::createFromDecimal($item);
$values['numerator'] = $fraction
->getNumerator();
$values['denominator'] = $fraction
->getDenominator();
}
break;
}
}
}