clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,143 @@
<?php
namespace Drupal\fraction\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
/**
* Provides a fraction form element.
*
* Usage example:
* @code
* $form['fraction'] = [
* '#type' => 'fraction',
* '#title' => $this->t('Fraction'),
* '#default_value' => ['numerator' => 10, 'denominator' => 100],
* '#size' => 60,
* '#required' => TRUE,
* ];
* @endcode
*
* @FormElement("fraction")
*/
class Fraction extends FormElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#size' => 10,
'#element_validate' => [
[$class, 'validateFraction'],
],
'#process' => [
[$class, 'processElement'],
[$class, 'processAjaxForm'],
[$class, 'processGroup'],
],
'#pre_render' => [
[$class, 'preRenderGroup'],
],
'#theme_wrappers' => ['container'],
];
}
/**
* Builds the fraction form element.
*
* @param array $element
* The initial fraction form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array $complete_form
* The complete form structure.
*
* @return array
* The built fraction form element.
*/
public static function processElement(array $element, FormStateInterface $form_state, array &$complete_form) {
$default_value = $element['#default_value'];
if (isset($default_value) && !self::validateDefaultValue($default_value)) {
throw new \InvalidArgumentException('The #default_value for a fraction element must be an array with "numerator" and "denominator" keys.');
}
$element['#tree'] = TRUE;
$element['#attributes']['class'][] = 'form-type-fraction';
$element['numerator'] = [
'#type' => 'number',
'#title' => t('Numerator'),
'#title_display' => $element['#title_display'],
'#default_value' => $default_value ? $default_value['numerator'] : NULL,
'#required' => $element['#required'],
'#size' => $element['#size'],
'#error_no_message' => TRUE,
];
$element['denominator'] = [
'#type' => 'number',
'#title' => t('Denominator'),
'#title_display' => $element['#title_display'],
'#default_value' => $default_value ? $default_value['denominator'] : NULL,
'#description' => !empty($element['#description']) ?? '',
'#required' => $element['#required'],
'#size' => $element['#size'],
'#error_no_message' => TRUE,
];
// Remove the keys that were transferred to child elements.
unset($element['#size']);
unset($element['#description']);
return $element;
}
/**
* Form element validation handler for #type 'fraction'.
*
* Note that #required is validated by _form_validate() already.
*/
public static function validateFraction(&$element, FormStateInterface $form_state, &$complete_form) {
$numerator = $element['numerator']['#value'];
$denominator = $element['denominator']['#value'];
// If the denominator is empty, but the numerator isn't, print an error.
if (empty($denominator) && !empty($numerator)) {
$form_state->setError($element, t('The denominator of a fraction cannot be zero or empty (if a numerator is provided).'));
}
// Numerators must be between -9223372036854775808 and 9223372036854775807.
// Explicitly perform a string comparison to ensure precision.
if (!empty($numerator) && ((string) $numerator < '-9223372036854775808' || (string) $numerator > '9223372036854775807')) {
$form_state->setError($element, t('The numerator of a fraction must be between -9223372036854775808 and 9223372036854775807.'));
}
// Denominators must be between 1 and 2147483647.
// Explicitly perform a string comparison to ensure precision.
if (!empty($denominator) && ((string) $denominator <= '0' || (string) $denominator > '2147483647')) {
$form_state->setError($element, t('The denominator of a fraction must be greater than 0 and less than 2147483647.'));
}
}
/**
* Validates the default value.
*
* @param mixed $default_value
* The default value.
*
* @return bool
* TRUE if the default value is valid, FALSE otherwise.
*/
public static function validateDefaultValue($default_value) {
if (!is_array($default_value)) {
return FALSE;
}
if (!array_key_exists('numerator', $default_value) || !array_key_exists('denominator', $default_value)) {
return FALSE;
}
return TRUE;
}
}
@@ -0,0 +1,188 @@
<?php
namespace Drupal\fraction\Element;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\Render\Element\Number;
use Drupal\fraction\Fraction;
/**
* Provides a fraction decimal form element.
*
* Usage example:
* @code
* $form['fraction'] = [
* '#type' => 'fraction_decimal',
* '#title' => $this->t('Fraction'),
* '#default_value' => 10.385,
* '#size' => 60,
* '#required' => TRUE,
* ];
* @endcode
*
* @FormElement("fraction_decimal")
*/
class FractionDecimal extends FormElement {
/**
* {@inheritdoc}
*/
public function getInfo() {
$class = get_class($this);
return [
'#input' => TRUE,
'#step' => 'any',
'#size' => 15,
'#maxlength' => 128,
'#default_value' => NULL,
'#element_validate' => [
[$class, 'validateDecimal'],
],
'#process' => [
[$class, 'processAjaxForm'],
[$class, 'processGroup'],
],
'#pre_render' => [
[$class, 'preRenderNumber'],
[$class, 'preRenderGroup'],
],
'#theme' => 'input__textfield',
'#theme_wrappers' => ['form_element'],
];
}
/**
* Validates the fraction_decimal element.
*
* @param array $element
* The form element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param array $complete_form
* The complete form structure.
*/
public static function validateDecimal(array $element, FormStateInterface $form_state, array &$complete_form) {
$value = trim($element['#value']);
// Only continue with validation if the value is not empty.
if ($element['#value'] === '') {
return;
}
// Do basic number validations.
Number::validateNumber($element, $form_state, $complete_form);
// Only continue with validation if value is a valid number.
if (count($form_state->getErrors()) !== 0) {
return;
}
// Convert the value to a fraction.
$fraction = Fraction::createFromDecimal($value);
// Get the numerator and denominator.
$numerator = $fraction->getNumerator();
$denominator = $fraction->getDenominator();
// Set the numerator and denominator values for the form.
$values = [
'decimal' => $value,
'numerator' => $numerator,
'denominator' => $denominator,
];
$form_state->setValueForElement($element, $values);
// The maximum number of digits after the decimal place is 9.
// Explicitly perform a string comparison to ensure precision.
if ((string) $denominator > '1000000000') {
$form_state->setError($element, t('The maximum number of digits after the decimal place is 9.'));
}
// Ensure that the decimal value is within an acceptable value range.
// Convert the fraction back to a decimal, because that is what will be
// stored. Explicitly perform a string comparison to ensure precision.
$decimal = (string) $fraction->toDecimal(0, TRUE);
$min_decimal_fraction = new Fraction('-9223372036854775808', $denominator);
$min_decimal = (string) $min_decimal_fraction->toDecimal(0, TRUE);
$max_decimal_fraction = new Fraction('9223372036854775807', $denominator);
$max_decimal = (string) $max_decimal_fraction->toDecimal(0, TRUE);
$scale = strlen($denominator) - 1;
$in_bounds = static::checkInBounds($decimal, $min_decimal, $max_decimal, $scale);
if (!$in_bounds) {
$form_state->setError($element, t('The number you entered is outside the range of acceptable values. This limitation is related to the decimal precision, so reducing the precision may solve the problem.'));
}
}
/**
* Prepares a #type 'fraction_decimal' render element for input.html.twig.
*
* @param array $element
* An associative array containing the properties of the element.
* Properties used: #title, #value, #description, #size, #maxlength,
* #placeholder, #required, #attributes.
*
* @return array
* The $element with prepared variables ready for input.html.twig.
*/
public static function preRenderNumber(array $element) {
$element['#attributes']['type'] = 'text';
Element::setAttributes($element,
['id', 'name', 'value', 'size', 'maxlength', 'placeholder']
);
static::setAttributes($element, ['form-text']);
return $element;
}
/**
* Helper method to check if a given value is in between two other values.
*
* Uses BCMath and strings for arbitrary-precision operations where possible.
*
* @param string $value
* The value to check.
* @param string $min
* The minimum bound.
* @param string $max
* The maximum bound.
* @param int $scale
* Optional scale integer to pass into bcsub() if BCMath is used.
*
* @return bool
* Returns TRUE if $number is between $min and $max, FALSE otherwise.
*/
public static function checkInBounds($value, $min, $max, $scale = 0) {
// If BCMath isn't available, let PHP handle it via normal float comparison.
if (!function_exists('bcsub')) {
return ($value > $max || $value < $min) ? FALSE : TRUE;
}
// Subtract the minimum bound and maximum bounds from the value.
$diff_min = bcsub($value, $min, $scale);
$diff_max = bcsub($value, $max, $scale);
// If either have a difference of zero, then the value is in bounds.
if ($diff_min == 0 || $diff_max == 0) {
return TRUE;
}
// If the first character of $diff_min is a negative sign (-), then the
// value is less than the minimum, and therefore out of bounds.
if (substr($diff_min, 0, 1) == '-') {
return FALSE;
}
// If the first character of $diff_max is a number, then the value is
// greater than the maximum, and therefore out of bounds.
if (is_numeric(substr($diff_max, 0, 1))) {
return FALSE;
}
// Assume the value is in bounds if none of the above said otherwise.
return TRUE;
}
}
@@ -0,0 +1,103 @@
<?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;
/**
* Defines a fraction field mapper.
*
* @FeedsTarget(
* id = "fraction",
* field_types = {
* "fraction",
* }
* )
*/
class FractionTarget extends FieldTargetBase implements ConfigurableTargetInterface {
/**
* Helper function to define the ways to import the fraction data.
*
* @return array
* Array with all the possible types.
*/
protected function importTypes() {
return [
'fraction' => $this->t('Fraction'),
'decimal' => $this->t('Decimal'),
];
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return ['type' => 'fraction'];
}
/**
* {@inheritdoc}
*/
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;
}
/**
* {@inheritdoc}
*/
public function getSummary() {
$types = $this->importTypes();
return $this->t('Import type: %type', ['%type' => $types[$this->configuration['type']]]);
}
/**
* {@inheritdoc}
*/
protected function prepareValue($delta, array &$values) {
$item = is_string($values['value']) ? trim($values['value']) : $values['value'];
unset($values['value']);
switch ($this->configuration['type']) {
case 'fraction':
// Pull out the numerator and denominator.
$parts = is_string($item) ? 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 item is non-numeric or an empty string, create an empty fraction.
// Otherwise, pass the value to createFromDecimal().
if (!is_numeric($item) || $item === '') {
$values['numerator'] = '';
$values['denominator'] = '';
}
else {
$fraction = Fraction::createFromDecimal($item);
$values['numerator'] = $fraction->getNumerator();
$values['denominator'] = $fraction->getDenominator();
}
break;
}
}
}
+428
View File
@@ -0,0 +1,428 @@
<?php
namespace Drupal\fraction;
/**
* A simple class for representing and acting upon a fraction.
*/
class Fraction implements FractionInterface {
/**
* Numerator of the fraction.
*
* @var string
*/
protected $numerator;
/**
* Denominator of the fraction.
*
* @var string
*/
protected $denominator;
/**
* Constructs a Fraction object.
*
* @param string|int $numerator
* The fraction's numerator. Defaults to 0.
* @param string|int $denominator
* The fraction's denominator. Defaults to 1.
*/
public function __construct($numerator = 0, $denominator = 1) {
$this->setNumerator($numerator);
$this->setDenominator($denominator);
}
/**
* {@inheritdoc}
*/
public static function createFromDecimal($value) {
// Calculate the precision by counting the number of decimal places.
$precision = strlen(substr(strrchr($value, '.'), 1));
// Create the denominator by raising 10 to the power of the precision.
if (function_exists('bcpow')) {
$denominator = bcpow(10, $precision);
}
else {
$denominator = pow(10, $precision);
}
// Calculate the numerator by multiplying the value by the denominator.
if (function_exists('bcmul')) {
$numerator = bcmul($value, $denominator, 0);
}
else {
$numerator = $value * $denominator;
}
return new Fraction($numerator, $denominator);
}
/**
* {@inheritdoc}
*/
public function setNumerator($value) {
// Cast the value as a string and save it.
$this->numerator = (string) $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function setDenominator($value) {
// Protect against division by zero.
if (empty($value)) {
$this->setNumerator(0);
$value = 1;
}
// Normalize negative fractions.
// If the denominator is negative, invert the signs for both numbers.
if ($value < 0) {
$numerator = $this->getNumerator();
$numerator = $numerator * -1;
$this->setNumerator($numerator);
$value = $value * -1;
}
// Cast the value as a string and save it.
$this->denominator = (string) $value;
return $this;
}
/**
* {@inheritdoc}
*/
public function getNumerator() {
return $this->numerator;
}
/**
* {@inheritdoc}
*/
public function getDenominator() {
return $this->denominator;
}
/**
* {@inheritdoc}
*/
public function toString(string $separator = '/') {
// Get the numerator and denominator.
$numerator = $this->getNumerator();
$denominator = $this->getDenominator();
// Concatenate with the separator and return.
return $numerator . $separator . $denominator;
}
/**
* {@inheritdoc}
*/
public function toDecimal(int $precision = 0, bool $auto_precision = FALSE) {
// Get the numerator and denominator.
$numerator = $this->getNumerator();
$denominator = $this->getDenominator();
// If auto precision is on figure out the maximum precision.
if ($auto_precision) {
// If the denominator is base-10, max precision is the number of zeroes
// in the denominator.
if ($denominator % 10 == 0) {
$max_precision = strlen($denominator) - 1;
}
// Or, if the denominator is 1, max precision is zero.
elseif ($denominator == 1) {
$max_precision = 0;
}
// Or, if the denominator is a multiple of 2 or 5, the fraction is known
// to be terminating, and we can figure out the precision.
elseif ($this->isTerminating()) {
$max_precision = $this->terminatingPrecision($this->reduce()->getDenominator());
}
// Otherwise, max precision is the denominator length.
else {
$max_precision = strlen($denominator);
}
// Use the greater of the two precisions.
$precision = ($max_precision > $precision) ? $max_precision : $precision;
}
// Divide the numerator by the denominator (using BCMath if available).
if (function_exists('bcdiv')) {
// Divide the numerator and denominator, with extra precision.
$value = bcdiv($numerator, $denominator, $precision + 1);
// Return a decimal string rounded to the final precision.
return $this->bcRound($value, $precision);
}
// If BCMath is not available, use normal PHP float division and rounding.
else {
return (string) round($numerator / $denominator, $precision);
}
}
/**
* {@inheritdoc}
*/
public function gcd() {
// Get the numerator and denominator.
$numerator = $this->getNumerator();
$denominator = $this->getDenominator();
// Make sure both numbers are positive.
$a = str_replace('-', '', $numerator);
$b = str_replace('-', '', $denominator);
// Euclid's algorithm gives us the greatest common divisor.
// Use BCMath's modulus function if available.
if (function_exists('bcmod')) {
while ($b != 0) {
$t = $b;
$b = bcmod($a, $b);
$a = $t;
}
}
else {
while ($b != 0) {
$t = $b;
$b = $a % $b;
$a = $t;
}
}
return (string) $a;
}
/**
* {@inheritdoc}
*/
public function reduce() {
// Get the numerator and denominator.
$numerator = $this->getNumerator();
$denominator = $this->getDenominator();
// Calculate the greatest common divisor.
$gcd = $this->gcd();
// Divide the numerator and denominator by the gcd.
// Use BCMath division if available.
if (function_exists('bcdiv')) {
$numerator = bcdiv($numerator, $gcd, 0);
$denominator = bcdiv($denominator, $gcd, 0);
}
else {
$numerator = $numerator / $gcd;
$denominator = $denominator / $gcd;
}
// Create a new Fraction object.
return new Fraction($numerator, $denominator);
}
/**
* {@inheritdoc}
*/
public function reciprocate() {
// Get the numerator and denominator, but flipped.
$numerator = $this->getDenominator();
$denominator = $this->getNumerator();
// Create a new Fraction object.
return new Fraction($numerator, $denominator);
}
/**
* {@inheritdoc}
*/
public function add(Fraction $fraction) {
// Get the numerator and denominator of each fraction.
$numerator1 = $this->getNumerator();
$denominator1 = $this->getDenominator();
$numerator2 = $fraction->getNumerator();
$denominator2 = $fraction->getDenominator();
// Calculate the sum of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul') && function_exists('bcadd')) {
$denominator = bcmul($denominator1, $denominator2, 0);
$numerator = bcadd(bcmul($numerator1, $denominator2, 0), bcmul($numerator2, $denominator1, 0), 0);
}
else {
$denominator = $denominator1 * $denominator2;
$numerator = $numerator1 * $denominator2 + $numerator2 * $denominator1;
}
// Create a new Fraction object and reduce it.
$fraction = new Fraction($numerator, $denominator);
$fraction = $fraction->reduce();
return $fraction;
}
/**
* {@inheritdoc}
*/
public function subtract(Fraction $fraction) {
// Get the numerator and denominator of each fraction.
$numerator1 = $this->getNumerator();
$denominator1 = $this->getDenominator();
$numerator2 = $fraction->getNumerator();
$denominator2 = $fraction->getDenominator();
// Calculate the difference of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul') && function_exists('bcsub')) {
$denominator = bcmul($denominator1, $denominator2, 0);
$numerator = bcsub(bcmul($numerator1, $denominator2, 0), bcmul($numerator2, $denominator1, 0), 0);
}
else {
$denominator = $denominator1 * $denominator2;
$numerator = $numerator1 * $denominator2 - $numerator2 * $denominator1;
}
// Create a new Fraction object and reduce it.
$fraction = new Fraction($numerator, $denominator);
$fraction = $fraction->reduce();
return $fraction;
}
/**
* {@inheritdoc}
*/
public function multiply(Fraction $fraction) {
// Get the numerator and denominator of each fraction.
$numerator1 = $this->getNumerator();
$denominator1 = $this->getDenominator();
$numerator2 = $fraction->getNumerator();
$denominator2 = $fraction->getDenominator();
// Calculate the product of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul')) {
$numerator = bcmul($numerator1, $numerator2, 0);
$denominator = bcmul($denominator1, $denominator2, 0);
}
else {
$numerator = $numerator1 * $numerator2;
$denominator = $denominator1 * $denominator2;
}
// Create a new Fraction object and reduce it.
$fraction = new Fraction($numerator, $denominator);
$fraction = $fraction->reduce();
return $fraction;
}
/**
* {@inheritdoc}
*/
public function divide(Fraction $fraction) {
// Reciprocate the fraction.
$reciprocal = $fraction->reciprocate();
// Get the numerator and denominator of each fraction.
$numerator1 = $this->getNumerator();
$denominator1 = $this->getDenominator();
$numerator2 = $reciprocal->getNumerator();
$denominator2 = $reciprocal->getDenominator();
// Calculate the quotient of the two fractions.
// Use BCMath if available.
if (function_exists('bcmul')) {
$numerator = bcmul($numerator1, $numerator2, 0);
$denominator = bcmul($denominator1, $denominator2, 0);
}
else {
$numerator = $numerator1 * $numerator2;
$denominator = $denominator1 * $denominator2;
}
// Create a new Fraction object and reduce it.
$fraction = new Fraction($numerator, $denominator);
$fraction = $fraction->reduce();
return $fraction;
}
/**
* Test if the fraction is terminating.
*
* @return bool
* Returns TRUE if the fraction is terminating, FALSE if it is repeating.
*/
protected function isTerminating() {
$d = $this->getDenominator();
$d /= $this->gcd();
while ($d % 2 == 0) {
$d /= 2;
}
while ($d % 5 == 0) {
$d /= 5;
}
return $d == 1;
}
/**
* Given the denominator of a terminating fraction, calculate the precision.
*
* @param string $denominator
* The denominator.
* @param int $exponent
* An exponent that is incremented with each iteration.
*
* @return int
* The number of decimal places required to represent the fraction as a
* decimal.
*/
protected function terminatingPrecision(string $denominator, int $exponent = 1) {
if (function_exists('bcpow')) {
$done = bcmod(bcpow(10, $exponent), $denominator) === '0';
}
else {
$done = pow(10, $exponent) % $denominator === 0;
}
return $done ? $exponent : $this->terminatingPrecision($denominator, $exponent + 1);
}
/**
* BCMath decimal rounding function.
*
* @param int|float|string $value
* The value to round.
* @param int $precision
* The desired decimal precision.
*
* @return string
* Returns a rounded decimal value, as a PHP string.
*/
protected function bcRound($value, $precision) {
if ($value[0] != '-') {
return bcadd($value, '0.' . str_repeat('0', $precision) . '5', $precision);
}
return bcsub($value, '0.' . str_repeat('0', $precision) . '5', $precision);
}
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\fraction;
use Drupal\Core\TypedData\TypedData;
/**
* A computed property for storing the fraction decimal value for validation.
*/
class FractionDecimalProperty extends TypedData {
/**
* Cached value.
*
* @var string|null
*/
protected $decimal = NULL;
/**
* Implements \Drupal\Core\TypedData\TypedDataInterface::getValue().
*/
public function getValue($langcode = NULL) {
// If a value is already available, return it.
if ($this->decimal !== NULL) {
return $this->decimal;
}
// Load the parent item.
$item = $this->getParent();
// If numerator or denominator are null, the decimal is also null.
if (is_null($item->numerator) || is_null($item->denominator)) {
$this->decimal = NULL;
}
// Otherwise, create a Fraction object and generate decimal value with
// automatic precision.
else {
$fraction = new Fraction($item->numerator, $item->denominator);
$this->decimal = $fraction->toDecimal(0, TRUE);
}
return $this->decimal;
}
/**
* {@inheritdoc}
*/
public function setValue($value, $notify = TRUE) {
$this->decimal = $value;
// Notify the parent of any changes.
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
}
}
@@ -0,0 +1,157 @@
<?php
namespace Drupal\fraction;
/**
* Defines the interface for Fraction class.
*
* @package fraction
*/
interface FractionInterface {
/**
* Sets the numerator.
*
* @param string|int $numerator
* The numerator value.
*
* @return Fraction
* Returns this Fraction object.
*/
public function setNumerator($numerator);
/**
* Sets the denominator.
*
* @param string|int $denominator
* The denominator value.
*
* @return Fraction
* Returns this Fraction object.
*/
public function setDenominator($denominator);
/**
* Gets the numerator.
*
* @return string
* Returns the numerator value.
*/
public function getNumerator();
/**
* Gets the denominator.
*
* @return string
* Returns the denominator value.
*/
public function getDenominator();
/**
* Return a string representation of the fraction.
*
* @param string $separator
* The separator to place between the numerator and denominator.
*
* @return string
* Returns a string with the numerator, separator, and denominator.
*/
public function toString(string $separator = '/');
/**
* Calculates the decimal equivalent of the fraction.
*
* @param int $precision
* The desired decimal precision, defaults to 0.
* @param bool $auto_precision
* Boolean, whether or not the precision should be automatically calculated.
* This option provides more precision when you need it, and less when you
* don't. If set to TRUE, it will try to determine the maximum precision
* (this only works if the denominator is base 10). If the resulting
* precision is greater than $precision, it will be used instead.
*
* @return string
* Returns the decimal equivalent of the fraction as a PHP string.
*/
public function toDecimal(int $precision, bool $auto_precision = FALSE);
/**
* Calculates the numerator and denominator from a decimal value.
*
* @param string|int|float $value
* The decimal value to start with.
*
* @return Fraction
* Returns this object.
*/
public static function createFromDecimal($value);
/**
* Calculate the fraction's greatest common divisor using Euclid's algorithm.
*
* @return string
* Returns the greatest common divisor.
*/
public function gcd();
/**
* Reduces the fraction to its simplest form.
*
* @return Fraction
* Returns the reduced fraction as a new Fraction object.
*/
public function reduce();
/**
* Reciprocates the fraction.
*
* @return Fraction
* Returns the reciprocal as a new Fraction object.
*/
public function reciprocate();
/**
* Adds another fraction to this one.
*
* @param Fraction $fraction
* Another fraction object to add to this one.
*
* @return Fraction
* Returns the arithmetic result as a new Fraction object.
*/
public function add(Fraction $fraction);
/**
* Subtracts another fraction from this one.
*
* @param Fraction $fraction
* Another fraction object to subtract this one.
*
* @return Fraction
* Returns the arithmetic result as a new Fraction object.
*/
public function subtract(Fraction $fraction);
/**
* Multiplies this fraction with another one.
*
* @param Fraction $fraction
* Another fraction object to multiply with.
*
* @return Fraction
* Returns the arithmetic result as a new Fraction object.
*/
public function multiply(Fraction $fraction);
/**
* Divides this fraction by another one.
*
* @param Fraction $fraction
* Another fraction object to divide by.
*
* @return Fraction
* Returns the arithmetic result as a new Fraction object.
*/
public function divide(Fraction $fraction);
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\fraction;
use Drupal\Core\TypedData\TypedData;
/**
* A computed property for storing the fraction.
*/
class FractionProperty extends TypedData {
/**
* Cached Fraction object.
*
* @var Fraction|null
*/
protected $fraction = NULL;
/**
* Implements \Drupal\Core\TypedData\TypedDataInterface::getValue().
*/
public function getValue($langcode = NULL) {
// If a Fraction object is already available, return it.
if ($this->fraction !== NULL) {
return $this->fraction;
}
// Load the parent item.
$item = $this->getParent();
// If numerator or denominator are null, the fraction is also null.
if (is_null($item->numerator) || is_null($item->denominator)) {
$this->fraction = NULL;
}
// Otherwise, create a Fraction object with the numerator and denominator.
else {
$this->fraction = new Fraction($item->numerator, $item->denominator);
}
return $this->fraction;
}
/**
* {@inheritdoc}
*/
public function setValue($value, $notify = TRUE) {
$this->fraction = $value;
// Notify the parent of any changes.
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
}
}
@@ -0,0 +1,100 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'fraction_decimal' formatter.
*
* @FieldFormatter(
* id = "fraction_decimal",
* label = @Translation("Decimal"),
* field_types = {
* "fraction"
* }
* )
*/
class FractionDecimalFormatter extends FractionFormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'precision' => 0,
'auto_precision' => TRUE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
// Decimal precision.
$elements['precision'] = [
'#type' => 'number',
'#title' => $this->t('Decimal precision'),
'#description' => $this->t('Specify the number of digits after the decimal place to display. When "Auto precision" is enabled, this value essentially becomes a minimum fallback precision.'),
'#default_value' => $this->getSetting('precision'),
'#required' => TRUE,
'#weight' => 0,
];
// Auto precision.
$elements['auto_precision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Auto precision'),
'#description' => $this->t('Automatically determine the maximum precision if the fraction has a base-10 denominator. For example, 1/100 would have a precision of 2, 1/1000 would have a precision of 3, etc.'),
'#default_value' => $this->getSetting('auto_precision'),
'#weight' => 1,
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
// Summarize the precision setting.
$precision = $this->getSetting('precision');
$auto_precision = !empty($this->getSetting('auto_precision')) ? 'On' : 'Off';
$summary[] = $this->t('Precision: @precision, Auto-precision: @auto_precision', [
'@precision' => $precision,
'@auto_precision' => $auto_precision,
]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Output fraction as a decimal with a fixed or automatic precision.
$precision = $this->getSetting('precision');
$auto_precision = !empty($this->getSetting('auto_precision')) ? TRUE : FALSE;
// Iterate through the items.
foreach ($items as $delta => $item) {
/** @var \Drupal\fraction\FractionInterface $fraction */
$fraction = $item->fraction;
$output = $fraction->toDecimal($precision, $auto_precision);
$elements[$delta] = [
'#markup' => $this->viewOutput($item, $output),
];
}
return $elements;
}
}
@@ -0,0 +1,83 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'fraction' formatter.
*
* @FieldFormatter(
* id = "fraction",
* label = @Translation("Fraction"),
* field_types = {
* "fraction"
* }
* )
*/
class FractionFormatter extends FractionFormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'separator' => '/',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
// Numerator and denominator separator.
$elements['separator'] = [
'#type' => 'textfield',
'#title' => $this->t('Separator'),
'#description' => $this->t('Specify the separator to display between the numerator and denominator.'),
'#default_value' => $this->getSetting('separator'),
'#required' => TRUE,
'#weight' => 0,
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
// Summarize the separator setting.
$separator = $this->getSetting('separator');
$summary[] = $this->t('Separator: @separator', [
'@separator' => $separator,
]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Load the separator setting.
$separator = $this->getSetting('separator');
// Iterate through the items.
foreach ($items as $delta => $item) {
$output = $item->fraction->toString($separator);
$elements[$delta] = [
'#markup' => $this->viewOutput($item, $output),
];
}
return $elements;
}
}
@@ -0,0 +1,78 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
/**
* Base class for fraction formatters.
*/
abstract class FractionFormatterBase extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'prefix_suffix' => FALSE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements = parent::settingsForm($form, $form_state);
$elements['prefix_suffix'] = [
'#type' => 'checkbox',
'#title' => $this->t('Display prefix and suffix'),
'#default_value' => $this->getSetting('prefix_suffix'),
'#weight' => 10,
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this->getSetting('prefix_suffix')) {
$summary[] = $this->t('Display with prefix and suffix.');
}
return $summary;
}
/**
* Account for extra output such as prefixes and suffixes.
*
* @param \Drupal\Core\Field\FieldItemInterface $item
* The field item to evaluate.
* @param string $output
* The output of the field.
*
* @return string
* The output with all relevant additions.
*/
protected function viewOutput(FieldItemInterface $item, $output = '') {
$field_settings = $this->getFieldSettings();
// Account for prefix and suffix.
if ($this->getSetting('prefix_suffix')) {
$prefixes = isset($field_settings['prefix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $field_settings['prefix'])) : [''];
$suffixes = isset($field_settings['suffix']) ? array_map(['Drupal\Core\Field\FieldFilteredMarkup', 'create'], explode('|', $field_settings['suffix'])) : [''];
$prefix = (count($prefixes) > 1) ? $this->formatPlural($item->decimal, $prefixes[0], $prefixes[1]) : $prefixes[0];
$suffix = (count($suffixes) > 1) ? $this->formatPlural($item->decimal, $suffixes[0], $suffixes[1]) : $suffixes[0];
$output = $prefix . $output . $suffix;
}
return $output;
}
}
@@ -0,0 +1,43 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\fraction\Fraction;
/**
* Format fraction as percentage.
*
* @FieldFormatter(
* id = "fraction_percentage",
* label = @Translation("Percentage"),
* field_types = {
* "fraction"
* }
* )
*/
class PercentageFormatter extends FractionDecimalFormatter {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
// Iterate through the items.
foreach ($items as $delta => $item) {
/** @var \Drupal\fraction\Fraction $percentage */
$percentage = $item->fraction->multiply(Fraction::createFromDecimal('100'));
$auto_precision = !empty($this->getSetting('auto_precision'));
$output = $percentage->toDecimal($this->getSetting('precision'), $auto_precision) . '%';
$elements[$delta] = [
'#markup' => $this->viewOutput($item, $output),
];
}
return $elements;
}
}
@@ -0,0 +1,161 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\NumericItemBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\MapDataDefinition;
use Drupal\fraction\Fraction;
/**
* Plugin implementation of the 'fraction' field type.
*
* @FieldType(
* id = "fraction",
* label = @Translation("Fraction (two integers)"),
* description = @Translation("This field stores a decimal in fraction form (with a numerator and denominator) for maximum precision."),
* category = @Translation("Number"),
* default_widget = "fraction",
* default_formatter = "fraction",
* constraints = {"FractionConstraint" = {}}
* )
*/
class FractionItem extends NumericItemBase {
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'numerator' => [
'description' => 'Fraction numerator value',
'type' => 'int',
'size' => 'big',
'not null' => FALSE,
],
'denominator' => [
'description' => 'Fraction denominator value',
'type' => 'int',
'not null' => FALSE,
],
],
];
}
/**
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = parent::fieldSettingsForm($form, $form_state);
$element['min']['#step'] = 'any';
$element['max']['#step'] = 'any';
return $element;
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$property_definitions['numerator'] = DataDefinition::create('integer')
->setLabel(t('Numerator value'));
$property_definitions['denominator'] = DataDefinition::create('integer')
->setLabel(t('Denominator value'));
$property_definitions['fraction'] = MapDataDefinition::create()
->setLabel(t('Fraction'))
->setDescription(t('A fraction object instance.'))
->setComputed(TRUE)
->setClass('\Drupal\fraction\FractionProperty');
$property_definitions['decimal'] = MapDataDefinition::create()
->setLabel(t('Fraction Decimal'))
->setDescription(t('Fraction decimal value.'))
->setComputed(TRUE)
->setInternal(FALSE)
->setClass('\Drupal\fraction\FractionDecimalProperty');
return $property_definitions;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$numerator = $this->get('numerator')->getValue();
$denominator = $this->get('denominator')->getValue();
return (((string) $numerator !== '0' && empty($numerator)) || ((string) $denominator !== '0' && empty($denominator)));
}
/**
* {@inheritdoc}
*/
public function setValue($values, $notify = TRUE) {
// Determine if we populate the fraction numerator and denominator field
// properties from a single decimal value.
$decimal = NULL;
// Treat the values as a decimal if no array is given.
if (isset($values) && !is_array($values)) {
$decimal = $values;
}
// If the decimal property is specified, use it.
if (is_array($values) && isset($values['decimal'])) {
$decimal = $values['decimal'];
}
// Populate the fraction field if decimal is numeric.
if (is_numeric($decimal) && $fraction = Fraction::createFromDecimal($decimal)) {
$values = [
'numerator' => $fraction->getNumerator(),
'denominator' => $fraction->getDenominator(),
];
}
parent::setValue($values, $notify);
}
/**
* {@inheritdoc}
*/
public function getConstraints() {
/** @var \Symfony\Component\Validator\Constraint[] $constraints */
$constraints = parent::getConstraints();
foreach ($constraints as &$constraint) {
// Replace 'value' with 'decimal' in min/max range constraints.
if (!empty($constraint->properties['value'])) {
$constraint->properties['decimal'] = $constraint->properties['value'];
unset($constraint->properties['value']);
}
}
return $constraints;
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
// Generate random decimal (float) with a max of 9 decimal places and then
// convert it to fraction.
$divisor = pow(10, rand(0, 9));
$number = mt_rand(1, 20 * $divisor) / $divisor;
$fraction = Fraction::createFromDecimal($number);
return [
'numerator' => $fraction->getNumerator(),
'denominator' => $fraction->getDenominator(),
];
}
/**
* {@inheritdoc}
*/
public static function mainPropertyName() {
return NULL;
}
}
@@ -0,0 +1,123 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'fraction_decimal' widget.
*
* @FieldWidget(
* id = "fraction_decimal",
* label = @Translation("Decimal"),
* field_types = {
* "fraction"
* }
* )
*/
class FractionDecimalWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'precision' => 0,
'auto_precision' => TRUE,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
// Decimal precision.
$elements['precision'] = [
'#type' => 'number',
'#title' => $this->t('Decimal precision'),
'#description' => $this->t('Specify the number of digits after the decimal place to display when converting the fraction to a decimal. When "Auto precision" is enabled, this value essentially becomes a minimum fallback precision.'),
'#default_value' => $this->getSetting('precision'),
'#required' => TRUE,
'#weight' => 0,
];
// Auto precision.
$elements['auto_precision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Auto precision'),
'#description' => $this->t('Automatically determine the maximum precision if the fraction has a base-10 denominator. For example, 1/100 would have a precision of 2, 1/1000 would have a precision of 3, etc.'),
'#default_value' => $this->getSetting('auto_precision'),
'#weight' => 1,
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
// Summarize the precision setting.
$precision = $this->getSetting('precision');
$auto_precision = !empty($this->getSetting('auto_precision')) ? 'On' : 'Off';
$summary[] = $this->t('Precision: @precision, Auto-precision: @auto_precision', [
'@precision' => $precision,
'@auto_precision' => $auto_precision,
]);
return $summary;
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
// Add a 'decimal' textfield for capturing the decimal value.
// The default value is converted to a decimal with the specified precision.
$precision = $this->getSetting('precision');
$auto_precision = !empty($this->getSetting('auto_precision')) ? TRUE : FALSE;
$element['decimal'] = $element + [
'#type' => 'fraction_decimal',
'#default_value' => $items->isEmpty() ? '' : $items[$delta]->fraction->toDecimal($precision, $auto_precision),
];
$field_settings = $this->getFieldSettings();
// Set minimum and maximum.
if (isset($field_settings['min']) && is_numeric($field_settings['min'])) {
$element['#min'] = $field_settings['min'];
}
if (isset($field_settings['max']) && is_numeric($field_settings['max'])) {
$element['#max'] = $field_settings['max'];
}
// Add prefix and suffix.
if ($field_settings['prefix']) {
$prefixes = explode('|', $field_settings['prefix']);
$element['decimal']['#field_prefix'] = FieldFilteredMarkup::create(array_pop($prefixes));
}
if ($field_settings['suffix']) {
$suffixes = explode('|', $field_settings['suffix']);
$element['decimal']['#field_suffix'] = FieldFilteredMarkup::create(array_pop($suffixes));
}
return $element;
}
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
// Remove the fraction form element wrapper if it exists to make the
// FractionItem::setValue method more consistent.
$value = $value['decimal'] ?? $value;
}
return $values;
}
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\fraction\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'fraction' widget.
*
* @FieldWidget(
* id = "fraction",
* label = @Translation("Fraction"),
* field_types = {
* "fraction"
* }
* )
*/
class FractionWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element += [
'#type' => 'details',
'#open' => TRUE,
];
$element['fraction'] = [
'#type' => 'fraction',
'#title' => $this->t('Fraction'),
'#default_value' => [
'numerator' => $items[$delta]->numerator ?? NULL,
'denominator' => $items[$delta]->denominator ?? NULL,
],
];
return $element;
}
/**
* {@inheritdoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
foreach ($values as &$value) {
// Remove the fraction form element wrapper if it exists to make the
// FractionItem::setValue method more consistent.
$value = $value['fraction'] ?? $value;
}
return $values;
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\fraction\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Plugin implementation of the 'fraction_constraint'.
*
* @Constraint(
* id = "FractionConstraint",
* label = @Translation("Fraction constraint", context = "Validation"),
* )
*/
class FractionConstraint extends Constraint {
/**
* Constraint message if denominator is empty or zero.
*
* @var string
*/
public $denominatorNotZero = 'The denominator of a fraction cannot be zero or empty.';
/**
* Constraint message if denominator is out of range from 1 to 2147483647.
*
* @var string
*/
public $denominatorOutOfRange = 'The denominator must be between 1 and 2147483647';
/**
* Constraint message if numerator is out of range.
*
* Range spans from -9223372036854775808 to 9223372036854775807
*
* @var string
*/
public $numeratorOutOfRange = 'The numerator must be between -9223372036854775808 and 9223372036854775807.';
/**
* Constraint message if number of decimal digits is greater than 9.
*
* @var string
*/
public $maxNumberOfDecimals = 'The maximum number of digits after the decimal place is 9.';
}
@@ -0,0 +1,39 @@
<?php
namespace Drupal\fraction\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the FractionConstraint constraint.
*/
class FractionConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
/** @var \Drupal\fraction\Plugin\Field\FieldType\FractionItem $fraction */
$fractionItem = $items;
$values = $fractionItem->getValue();
if (empty($values['denominator']) && !empty($values['numerator'])) {
$this->context->addViolation($constraint->denominatorNotZero);
return;
}
if (!empty($values['denominator']) && ((string) $values['denominator'] <= '0' || (string) $values['denominator'] > '2147483647')) {
$this->context->addViolation($constraint->denominatorOutOfRange);
return;
}
if (!empty($values['numerator']) && ((string) $values['numerator'] < '-9223372036854775808' || (string) $values['numerator'] > '9223372036854775807')) {
$this->context->addViolation($constraint->numeratorOutOfRange);
return;
}
if ((string) $values['denominator'] > '1000000000') {
$this->context->addViolation($constraint->maxNumberOfDecimals);
return;
}
}
}
@@ -0,0 +1,41 @@
<?php
namespace Drupal\fraction\Plugin\migrate\field\d7;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;
/**
* Migrate from d7 fraction structure.
*
* @MigrateField(
* id = "fraction",
* core = {7},
* source_module = "fraction",
* destination_module = "fraction"
* )
*/
class FractionField extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function getFieldWidgetMap() {
return [
'fraction_default' => 'fraction',
'fraction_decimal' => 'fraction_decimal',
'fraction_percentage' => 'fraction_percentage',
];
}
/**
* {@inheritdoc}
*/
public function getFieldFormatterMap() {
return [
'fraction_default' => 'fraction',
'fraction_decimal' => 'fraction_decimal',
'fraction_percentage' => 'fraction_percentage',
];
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\fraction\Plugin\migrate\process;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Drupal\fraction\Fraction;
/**
* Provides a 'DecimalFraction' migrate process plugin.
*
* @MigrateProcessPlugin(
* id = "decimal_fraction",
* handle_multiples = TRUE
* )
*
* Extracts the numerator and denominator that can be directly mapped to a
* Fraction field from a decimal input.
*
* Example:
*
* @code
* fraction:
* plugin: decimal_fraction
* source: decimal
* @endcode
*/
class DecimalFraction extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
if (!is_numeric($value) || $value === '') {
return [
'numerator' => '',
'denominator' => '',
];
}
else {
$fraction = Fraction::createFromDecimal($value);
return [
'numerator' => $fraction->getNumerator(),
'denominator' => $fraction->getDenominator(),
];
}
}
}
@@ -0,0 +1,101 @@
<?php
namespace Drupal\fraction\Plugin\views\field;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\ResultRow;
use Drupal\fraction\Fraction as FractionClass;
/**
* Field handler for Fraction database columns.
*
* @ingroup views_field_handlers
*
* @ViewsField("fraction")
*/
class Fraction extends FieldPluginBase {
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
// Default to automatic precision.
$options['precision'] = ['default' => 0];
$options['auto_precision'] = ['default' => TRUE];
return $options;
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
// Add fields for configuring precision and auto_precision.
$form['precision'] = [
'#type' => 'textfield',
'#title' => $this->t('Precision'),
'#description' => $this->t('Specify the number of digits after the decimal place to display when converting the fraction to a decimal. When "Auto precision" is enabled, this value essentially becomes a minimum fallback precision.'),
'#default_value' => $this->options['precision'],
];
$form['auto_precision'] = [
'#type' => 'checkbox',
'#title' => $this->t('Auto precision'),
'#description' => $this->t('Automatically determine the maximum precision if the fraction has a base-10 denominator. For example, 1/100 would have a precision of 2, 1/1000 would have a precision of 3, etc.'),
'#default_value' => $this->options['auto_precision'],
];
// Merge into the parent form.
parent::buildOptionsForm($form, $form_state);
// Remove the 'click_sort_column' form element, because we provide a custom
// click_sort function below to use the numerator and denominator columns
// simultaneously.
unset($form['click_sort_column']);
}
/**
* {@inheritdoc}
*/
public function clickSort($order) {
// Ensure the main table for this field is included.
$this->ensureMyTable();
// Formula for calculating the final value, by dividing numerator by
// denominator.
// These are available as additional fields.
$numerator = $this->tableAlias . '.' . $this->definition['additional fields']['numerator'];
$denominator = $this->tableAlias . '.' . $this->definition['additional fields']['denominator'];
// Multiply the numerator field by 1.0 so the database returns a decimal
// from the computation.
$formula = '1.0 * ' . $numerator . ' / ' . $denominator;
// Add the orderby.
$this->query->addOrderBy(NULL, $formula, $order, $this->tableAlias . '_decimal');
}
/**
* Loads the numerator and denominator values and converts to decimal.
*/
public function getValue(ResultRow $values, $field = NULL) {
// Find the numerator and denominator field aliases.
$numerator_alias = $this->aliases[$this->definition['additional fields']['numerator']];
$denominator_alias = $this->aliases[$this->definition['additional fields']['denominator']];
// If both values are available...
if (isset($values->{$numerator_alias}) && isset($values->{$denominator_alias})) {
// Convert to decimal.
$numerator = $values->{$numerator_alias};
$denominator = $values->{$denominator_alias};
$precision = $this->options['precision'];
$auto_precision = $this->options['auto_precision'];
$fraction = new FractionClass($numerator, $denominator);
return $fraction->toDecimal($precision, $auto_precision);
}
}
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\fraction\Plugin\views\field;
use Drupal\views\Plugin\views\field\EntityField;
use Drupal\Core\Form\FormStateInterface;
/**
* Field handler for Fraction fields.
*
* Overrides the clickSort() method to use a formula that divides
* the numerator by the denominator.
*
* Overrides the buildOptionsForm() method to remove the 'click_sort_column'
* form element.
*
* @ingroup views_field_handlers
*
* @ViewsField("fraction_field")
*/
class FractionField extends EntityField {
/**
* {@inheritdoc}
*/
public function clickSort($order) {
// Ensure the main table for this field is included.
$this->ensureMyTable();
// Formula for calculating the final value, by dividing numerator by
// denominator. These are available as additional fields.
$numerator = $this->tableAlias . '.' . $this->field . '_numerator';
$denominator = $this->tableAlias . '.' . $this->field . '_denominator';
// Multiply the numerator field by 1.0 so the database returns a decimal
// from the computation.
$formula = '1.0 * ' . $numerator . ' / ' . $denominator;
// Add the orderby.
$this->query->addOrderBy(NULL, $formula, $order, $this->tableAlias . '_decimal');
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
// Inherit the parent options form.
parent::buildOptionsForm($form, $form_state);
// Remove the 'click_sort_column' form element.
unset($form['click_sort_column']);
}
}
@@ -0,0 +1,78 @@
<?php
namespace Drupal\fraction\Plugin\views\filter;
use Drupal\views\Plugin\views\filter\NumericFilter;
/**
* Filter handler for Fraction fields.
*
* Overrides query function to use a formula which divides the numerator
* by the denominator.
*
* Overrides operator functions (op_between, op_simple, and op_regex).
* Alter the add_where() method call in each to use the formula.
* Note that op_empty() is not included because we are not setting
* 'allow empty'.
*
* @ingroup views_filter_handlers
*
* @ViewsFilter("fraction")
*/
class Fraction extends NumericFilter {
/**
* {@inheritdoc}
*/
public function query() {
// Ensure the main table for this field is included.
$this->ensureMyTable();
// Formula for calculating the final value, by dividing numerator by
// denominator. These are added as additional fields in
// hook_field_views_data_alter().
$numerator = $this->tableAlias . '.' . $this->definition['additional fields']['numerator'];
$denominator = $this->tableAlias . '.' . $this->definition['additional fields']['denominator'];
// Multiply the numerator field by 1.0 so the database returns a decimal
// from the computation.
$formula = '1.0 * ' . $numerator . ' / ' . $denominator;
// Perform the filter using the selected operator and the formula.
$info = $this->operators();
if (!empty($info[$this->operator]['method'])) {
$this->{$info[$this->operator]['method']}($formula);
}
}
/**
* {@inheritdoc}
*/
protected function opBetween($field) {
if ($this->operator == 'between') {
$expression = $field . ' BETWEEN :min AND :max';
$this->query->addWhereExpression($this->options['group'], $expression, [':min' => $this->value['min'], ':max' => $this->value['max']]);
}
else {
$expression = $field . ' <= :min OR ' . $field . ' >= :max';
$this->query->addWhereExpression($this->options['group'], $expression, [':min' => $this->value['min'], ':max' => $this->value['max']]);
}
}
/**
* {@inheritdoc}
*/
protected function opSimple($field) {
$expression = $field . ' ' . $this->operator . ' :value';
$this->query->addWhereExpression($this->options['group'], $expression, [':value' => $this->value['value']]);
}
/**
* {@inheritdoc}
*/
protected function opRegex($field) {
$expression = $field . ' RLIKE :value';
$this->query->addWhereExpression($this->options['group'], $expression, [':value' => $this->value['value']]);
}
}
@@ -0,0 +1,40 @@
<?php
namespace Drupal\fraction\Plugin\views\sort;
use Drupal\views\Plugin\views\sort\SortPluginBase;
/**
* Sort handler for Fraction fields.
*
* Overrides query function to use a formula which divides the numerator
* by the denominator.
*
* @ingroup views_sort_handlers
*
* @ViewsSort("fraction")
*/
class Fraction extends SortPluginBase {
/**
* {@inheritdoc}
*/
public function query() {
// Ensure the main table for this field is included.
$this->ensureMyTable();
// Formula for calculating the final value, by dividing numerator by
// denominator. These are added as additional fields in
// hook_field_views_data_alter().
$numerator = $this->tableAlias . '.' . $this->definition['additional fields']['numerator'];
$denominator = $this->tableAlias . '.' . $this->definition['additional fields']['denominator'];
// Multiply the numerator field by 1.0 so the database returns a decimal
// from the computation.
$formula = '1.0 * ' . $numerator . ' / ' . $denominator;
// Add the orderby.
$this->query->addOrderBy(NULL, $formula, $this->options['order'], $this->tableAlias . '_decimal');
}
}