You are here

class PriceTwigExtension in Price 3.x

Same name and namespace in other branches
  1. 8 src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension
  2. 2.0.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension
  3. 2.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension
  4. 3.0.x src/TwigExtension/PriceTwigExtension.php \Drupal\price\TwigExtension\PriceTwigExtension

Provides Price-specific Twig extensions.

Hierarchy

  • class \Drupal\price\TwigExtension\PriceTwigExtension extends \Drupal\price\TwigExtension\Twig_Extension

Expanded class hierarchy of PriceTwigExtension

1 string reference to 'PriceTwigExtension'
price.services.yml in ./price.services.yml
price.services.yml
1 service uses PriceTwigExtension
price.twig_extension in ./price.services.yml
Drupal\price\TwigExtension\PriceTwigExtension

File

src/TwigExtension/PriceTwigExtension.php, line 10

Namespace

Drupal\price\TwigExtension
View source
class PriceTwigExtension extends \Twig_Extension {

  /**
   * @inheritdoc
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('price_format', [
        $this,
        'formatPrice',
      ]),
    ];
  }

  /**
   * @inheritdoc
   */
  public function getName() {
    return 'price.twig_extension';
  }

  /**
   * Formats a price object/array.
   *
   * Examples:
   * {{ order.getTotalPrice|price_format }}
   * {{ order.getTotalPrice|price_format|default('N/A') }}
   *
   * @param mixed $price
   *   Either a Price object, or an array with number and currency_code keys.
   *
   * @return mixed
   *   A formatted price, suitable for rendering in a twig template.
   *
   * @throws \InvalidArgumentException
   */
  public static function formatPrice($price) {
    if (empty($price)) {
      return '';
    }
    if ($price instanceof Price) {
      $price = $price
        ->toArray();
    }
    if (is_array($price) && isset($price['currency_code']) && isset($price['number'])) {
      $currency_formatter = \Drupal::service('price.currency_formatter');
      return $currency_formatter
        ->format($price['number'], $price['currency_code']);
    }
    else {
      throw new \InvalidArgumentException('The "price_format" filter must be given a price object or an array with "number" and "currency_code" keys.');
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
PriceTwigExtension::formatPrice public static function Formats a price object/array.
PriceTwigExtension::getFilters public function @inheritdoc
PriceTwigExtension::getName public function @inheritdoc