You are here

trait QuickQuantityTrait in farmOS 2.x

Provides methods for working with quantities.

Hierarchy

1 file declares its use of QuickQuantityTrait
Test.php in modules/core/quick/tests/modules/farm_quick_test/src/Plugin/QuickForm/Test.php

File

modules/core/quick/src/Traits/QuickQuantityTrait.php, line 11

Namespace

Drupal\farm_quick\Traits
View source
trait QuickQuantityTrait {
  use QuickTermTrait;

  /**
   * Create a quantity.
   *
   * @param array $values
   *   An array of values to initialize the quantity with.
   *
   * @return \Drupal\quantity\Entity\QuantityInterface
   *   The quantity entity that was created.
   */
  public function createQuantity(array $values = []) {

    // If a type isn't set, default to "standard".
    if (empty($values['type'])) {
      $values['type'] = 'standard';
    }

    // Split value into numerator and denominator, if it isn't already.
    if (!empty($values['value']) && !is_array($values['value'])) {
      $fraction = Fraction::createFromDecimal($values['value']);
      $values['value'] = [
        'numerator' => $fraction
          ->getNumerator(),
        'denominator' => $fraction
          ->getDenominator(),
      ];
    }

    // If the units are a term name, create or load the unit taxonomy term.
    if (!empty($values['units'])) {
      $term = $this
        ->createOrLoadTerm($values['units'], 'unit');
      $values['units'] = $term;
    }

    // Start a new quantity entity with the provided values.

    /** @var \Drupal\quantity\Entity\QuantityInterface $quantity */
    $quantity = Quantity::create($values);

    // Save the quantity.
    $quantity
      ->save();

    // Return the quantity entity.
    return $quantity;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
QuickQuantityTrait::createQuantity public function Create a quantity.
QuickTermTrait::createOrLoadTerm public function Given a term name, create or load a matching term entity.
QuickTermTrait::createTerm public function Create a term.