You are here

class Currency in Currency 8.3

Same name in this branch
  1. 8.3 src/Entity/Currency.php \Drupal\currency\Entity\Currency
  2. 8.3 src/Plugin/views/filter/Currency.php \Drupal\currency\Plugin\views\filter\Currency
  3. 8.3 src/Plugin/views/field/Currency.php \Drupal\currency\Plugin\views\field\Currency

Defines a currency entity class.

Plugin annotation


@ConfigEntityType(
  handlers = {
    "access" = "Drupal\currency\Entity\Currency\CurrencyAccessControlHandler",
    "form" = {
      "default" = "Drupal\currency\Entity\Currency\CurrencyForm",
      "delete" = "Drupal\currency\Entity\Currency\CurrencyDeleteForm"
    },
    "list_builder" = "Drupal\currency\Entity\Currency\CurrencyListBuilder",
    "storage" = "Drupal\Core\Config\Entity\ConfigEntityStorage",
  },
  entity_keys = {
    "id" = "currencyCode",
    "label" = "label",
    "uuid" = "uuid",
    "status" = "status"
  },
  config_export = {
    "alternativeSigns",
    "currencyCode",
    "currencyNumber",
    "label",
    "roundingStep",
    "sign",
    "subunits",
    "status",
    "usages",
    "uuid",
  },
  id = "currency",
  label = @Translation("Currency"),
  links = {
    "collection" = "/admin/config/regional/currency",
    "create-form" = "/admin/config/regional/currency/add",
    "edit-form" = "/admin/config/regional/currency/{currency}",
    "delete-form" = "/admin/config/regional/currency/{currency}/delete"
  }
)

Hierarchy

Expanded class hierarchy of Currency

7 files declare their use of Currency
Currency.php in src/Plugin/views/filter/Currency.php
CurrencyAmount.php in src/Element/CurrencyAmount.php
CurrencyFormWebTest.php in tests/src/Functional/Entity/Currency/CurrencyFormWebTest.php
CurrencyTest.php in tests/src/Kernel/CurrencyTest.php
CurrencyTest.php in tests/src/Unit/Entity/CurrencyTest.php

... See full list

6 string references to 'Currency'
currency.info.yml in ./currency.info.yml
currency.info.yml
currency.schema.yml in config/schema/currency.schema.yml
config/schema/currency.schema.yml
currency.views.schema.yml in config/schema/currency.views.schema.yml
config/schema/currency.views.schema.yml
CurrencyAmount::process in src/Element/CurrencyAmount.php
Implements form #process callback.
CurrencyImportForm::buildForm in src/Form/CurrencyImportForm.php
Form constructor.

... See full list

File

src/Entity/Currency.php, line 53

Namespace

Drupal\currency\Entity
View source
class Currency extends ConfigEntityBase implements CurrencyInterface {

  /**
   * Alternative (non-official) currency signs.
   *
   * @var array
   *   An array of strings that are similar to self::sign.
   */
  protected $alternativeSigns = [];

  /**
   * The currency amount formatter manager.
   *
   * @var \Drupal\currency\Plugin\Currency\AmountFormatter\AmountFormatterManagerInterface
   */
  protected $currencyAmountFormatterManager;

  /**
   * ISO 4217 currency code.
   *
   * @var string
   */
  public $currencyCode;

  /**
   * ISO 4217 currency number.
   *
   * @var string
   */
  protected $currencyNumber;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The human-readable name.
   *
   * @var string
   */
  public $label;

  /**
   * The number of subunits to round amounts in this currency to.
   *
   * @see Currency::getRoundingStep()
   *
   * @var integer
   */
  protected $roundingStep;

  /**
   * The currency's official sign, such as '€' or '$'.
   *
   * @var string
   */
  protected $sign = '¤';

  /**
   * The number of subunits this currency has.
   *
   * @var integer|null
   */
  protected $subunits;

  /**
   * This currency's usages.
   *
   * @var \Commercie\Currency\UsageInterface[]
   */
  protected $usages = [];

  /**
   * The UUID for this entity.
   *
   * @var string
   */
  public $uuid;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $values, $entity_type) {
    if (isset($values['usages'])) {
      $usages_data = $values['usages'];
      $values['usages'] = [];
      foreach ($usages_data as $usage_data) {
        $usage = new Usage();
        $usage
          ->setStart($usage_data['start'])
          ->setEnd($usage_data['end'])
          ->setCountryCode($usage_data['countryCode']);
        $values['usages'][] = $usage;
      }
    }
    parent::__construct($values, $entity_type);
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() {
    return $this
      ->label();
  }

  /**
   * {@inheritdoc}
   */
  public function setAlternativeSigns(array $signs) {
    $this->alternativeSigns = $signs;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getAlternativeSigns() {
    return $this->alternativeSigns;
  }

  /**
   * {@inheritdoc}
   */
  public function setCurrencyCode($code) {
    $this->currencyCode = $code;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCurrencyCode() {
    return $this->currencyCode;
  }

  /**
   * {@inheritdoc}
   */
  public function setCurrencyNumber($number) {
    $this->currencyNumber = $number;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getCurrencyNumber() {
    return $this->currencyNumber;
  }

  /**
   * {@inheritdoc}
   */
  public function setLabel($label) {
    $this->label = $label;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setRoundingStep($step) {
    $this->roundingStep = $step;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setSign($sign) {
    $this->sign = $sign;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getSign() {
    return $this->sign;
  }

  /**
   * {@inheritdoc}
   */
  public function setSubunits($subunits) {
    $this->subunits = $subunits;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getSubunits() {
    return $this->subunits;
  }

  /**
   * {@inheritdoc}
   */
  public function setUsages(array $usages) {
    $this->usages = $usages;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getUsages() {
    return $this->usages;
  }

  /**
   * {@inheritdoc}
   */
  public function id() {
    return $this->currencyCode;
  }

  /**
   * {@inheritdoc}
   */
  public function getDecimals() {
    $decimals = 0;
    if ($this
      ->getSubunits() > 0) {
      $decimals = 1;
      while (pow(10, $decimals) < $this
        ->getSubunits()) {
        $decimals++;
      }
    }
    return $decimals;
  }

  /**
   * {@inheritdoc}
   */
  function formatAmount($amount, $use_currency_precision = TRUE, $language_type = LanguageInterface::TYPE_CONTENT) {
    if ($use_currency_precision && $this
      ->getSubunits()) {

      // Round the amount according the currency's configuration.
      $amount = bcmul(round(bcdiv($amount, $this
        ->getRoundingStep(), 6)), $this
        ->getRoundingStep(), 6);
      $decimal_mark_position = strpos($amount, '.');

      // The amount has no decimals yet, so add a decimal mark.
      if ($decimal_mark_position === FALSE) {
        $amount .= '.';
      }

      // Remove any existing trailing zeroes.
      $amount = rtrim($amount, '0');

      // Add the required number of trailing zeroes.
      $amount_decimals = strlen(substr($amount, $decimal_mark_position + 1));
      if ($amount_decimals < $this
        ->getDecimals()) {
        $amount .= str_repeat('0', $this
          ->getDecimals() - $amount_decimals);
      }
    }
    return $this
      ->getCurrencyAmountFormatterManager()
      ->getDefaultPlugin()
      ->formatAmount($this, $amount, $language_type);
  }

  /**
   * Sets the entity manager.
   *
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *
   * @return $this
   *
   * @deprecated
   */
  public function setEntityManager(EntityManagerInterface $entity_manager) {
    $this->entityManager = $entity_manager;
    return $this;
  }

  /**
   * Sets the entity type manager.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   *
   * @return $this
   */
  public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
    return $this;
  }

  /**
   * Gets the entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected function entityTypeManager() {
    if (!$this->entityTypeManager) {
      $this->entityTypeManager = parent::entityTypeManager();
    }
    return $this->entityTypeManager;
  }

  /**
   * Sets the currency amount formatter manager.
   *
   * @param \Drupal\currency\Plugin\Currency\AmountFormatter\AmountFormatterManagerInterface $currency_amount_formatter_manager
   *
   * @return $this
   */
  public function setCurrencyAmountFormatterManager(AmountFormatterManagerInterface $currency_amount_formatter_manager) {
    $this->currencyAmountFormatterManager = $currency_amount_formatter_manager;
    return $this;
  }

  /**
   * Gets the currency amount formatter manager.
   *
   * @return \Drupal\currency\Plugin\Currency\AmountFormatter\AmountFormatterManagerInterface
   */
  protected function getCurrencyAmountFormatterManager() {
    if (!$this->currencyAmountFormatterManager) {
      $this->currencyAmountFormatterManager = \Drupal::service('plugin.manager.currency.amount_formatter');
    }
    return $this->currencyAmountFormatterManager;
  }

  /**
   * {@inheritdoc}
   */
  function getRoundingStep() {
    if (is_numeric($this->roundingStep)) {
      return $this->roundingStep;
    }
    elseif (is_numeric($this
      ->getSubunits())) {
      return $this
        ->getSubunits() > 0 ? bcdiv(1, $this
        ->getSubunits(), 6) : 1;
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  function isObsolete($reference = NULL) {

    // Without usage information, we cannot know if the currency is obsolete.
    if (!$this
      ->getUsages()) {
      return FALSE;
    }

    // Default to the current date and time.
    if (is_null($reference)) {
      $reference = time();
    }

    // Mark the currency obsolete if all usages have an end date that comes
    // before $reference.
    $obsolete = 0;
    foreach ($this
      ->getUsages() as $usage) {
      if ($usage
        ->getEnd()) {
        $to = strtotime($usage
          ->getEnd());
        if ($to !== FALSE && $to < $reference) {
          $obsolete++;
        }
      }
    }
    return $obsolete == count($this
      ->getUsages());
  }

  /**
   * {@inheritdoc}
   */
  public function toArray() {
    $properties = parent::toArray();
    $properties['usages'] = [];
    foreach ($this
      ->getUsages() as $usage) {
      $properties['usages'][] = array(
        'start' => $usage
          ->getStart(),
        'end' => $usage
          ->getEnd(),
        'countryCode' => $usage
          ->getCountryCode(),
      );
    }
    return $properties;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
ConfigEntityBase::$isUninstalling private property Whether the config is being deleted by the uninstall process.
ConfigEntityBase::$langcode protected property The language code of the entity's default language.
ConfigEntityBase::$originalId protected property The original ID of the configuration entity.
ConfigEntityBase::$status protected property The enabled/disabled status of the configuration entity. 4
ConfigEntityBase::$third_party_settings protected property Third party entity settings.
ConfigEntityBase::$trustedData protected property Trust supplied data and not use configuration schema on save.
ConfigEntityBase::$_core protected property Information maintained by Drupal core about configuration.
ConfigEntityBase::addDependency protected function Overrides \Drupal\Core\Entity\DependencyTrait:addDependency().
ConfigEntityBase::calculateDependencies public function Calculates dependencies and stores them in the dependency property. Overrides ConfigEntityInterface::calculateDependencies 13
ConfigEntityBase::createDuplicate public function Creates a duplicate of the entity. Overrides EntityBase::createDuplicate 1
ConfigEntityBase::disable public function Disables the configuration entity. Overrides ConfigEntityInterface::disable 1
ConfigEntityBase::enable public function Enables the configuration entity. Overrides ConfigEntityInterface::enable
ConfigEntityBase::get public function Returns the value of a property. Overrides ConfigEntityInterface::get
ConfigEntityBase::getCacheTagsToInvalidate public function Returns the cache tags that should be used to invalidate caches. Overrides EntityBase::getCacheTagsToInvalidate 1
ConfigEntityBase::getConfigDependencyName public function Gets the configuration dependency name. Overrides EntityBase::getConfigDependencyName
ConfigEntityBase::getConfigManager protected static function Gets the configuration manager.
ConfigEntityBase::getConfigTarget public function Gets the configuration target identifier for the entity. Overrides EntityBase::getConfigTarget
ConfigEntityBase::getDependencies public function Gets the configuration dependencies. Overrides ConfigEntityInterface::getDependencies
ConfigEntityBase::getOriginalId public function Gets the original ID. Overrides EntityBase::getOriginalId
ConfigEntityBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
ConfigEntityBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
ConfigEntityBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
ConfigEntityBase::getTypedConfig protected function Gets the typed config manager.
ConfigEntityBase::hasTrustedData public function Gets whether on not the data is trusted. Overrides ConfigEntityInterface::hasTrustedData
ConfigEntityBase::invalidateTagsOnDelete protected static function Override to never invalidate the individual entities' cache tags; the config system already invalidates them. Overrides EntityBase::invalidateTagsOnDelete
ConfigEntityBase::invalidateTagsOnSave protected function Override to never invalidate the entity's cache tag; the config system already invalidates it. Overrides EntityBase::invalidateTagsOnSave
ConfigEntityBase::isInstallable public function Checks whether this entity is installable. Overrides ConfigEntityInterface::isInstallable 2
ConfigEntityBase::isNew public function Overrides Entity::isNew(). Overrides EntityBase::isNew
ConfigEntityBase::isUninstalling public function Returns whether this entity is being changed during the uninstall process. Overrides ConfigEntityInterface::isUninstalling
ConfigEntityBase::link public function Deprecated way of generating a link to the entity. See toLink(). Overrides EntityBase::link
ConfigEntityBase::onDependencyRemoval public function Informs the entity that entities it depends on will be deleted. Overrides ConfigEntityInterface::onDependencyRemoval 7
ConfigEntityBase::preDelete public static function Acts on entities before they are deleted and before hooks are invoked. Overrides EntityBase::preDelete 8
ConfigEntityBase::preSave public function Acts on an entity before the presave hook is invoked. Overrides EntityBase::preSave 13
ConfigEntityBase::save public function Saves an entity permanently. Overrides EntityBase::save 1
ConfigEntityBase::set public function Sets the value of a property. Overrides ConfigEntityInterface::set
ConfigEntityBase::setOriginalId public function Sets the original ID. Overrides EntityBase::setOriginalId
ConfigEntityBase::setStatus public function Sets the status of the configuration entity. Overrides ConfigEntityInterface::setStatus
ConfigEntityBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
ConfigEntityBase::setUninstalling public function
ConfigEntityBase::sort public static function Helper callback for uasort() to sort configuration entities by weight and label. 6
ConfigEntityBase::status public function Returns whether the configuration entity is enabled. Overrides ConfigEntityInterface::status 4
ConfigEntityBase::toUrl public function Gets the URL object for the entity. Overrides EntityBase::toUrl
ConfigEntityBase::trustData public function Sets that the data should be trusted. Overrides ConfigEntityInterface::trustData
ConfigEntityBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
ConfigEntityBase::url public function Gets the public URL for this entity. Overrides EntityBase::url
ConfigEntityBase::urlInfo public function Gets the URL object for the entity. Overrides EntityBase::urlInfo
ConfigEntityBase::__sleep public function Overrides EntityBase::__sleep 4
Currency::$alternativeSigns protected property Alternative (non-official) currency signs.
Currency::$currencyAmountFormatterManager protected property The currency amount formatter manager.
Currency::$currencyCode public property ISO 4217 currency code.
Currency::$currencyNumber protected property ISO 4217 currency number.
Currency::$entityTypeManager protected property The entity type manager.
Currency::$label public property The human-readable name.
Currency::$roundingStep protected property The number of subunits to round amounts in this currency to.
Currency::$sign protected property The currency's official sign, such as '€' or '$'.
Currency::$subunits protected property The number of subunits this currency has.
Currency::$usages protected property This currency's usages.
Currency::$uuid public property The UUID for this entity. Overrides ConfigEntityBase::$uuid
Currency::entityTypeManager protected function Gets the entity type manager. Overrides EntityBase::entityTypeManager
Currency::formatAmount function Format an amount using this currency and the environment's default currency locale. pattern. Overrides CurrencyInterface::formatAmount
Currency::getAlternativeSigns public function
Currency::getCurrencyAmountFormatterManager protected function Gets the currency amount formatter manager.
Currency::getCurrencyCode public function
Currency::getCurrencyNumber public function
Currency::getDecimals public function
Currency::getLabel public function
Currency::getRoundingStep function
Currency::getSign public function
Currency::getSubunits public function
Currency::getUsages public function
Currency::id public function Gets the identifier. Overrides EntityBase::id
Currency::isObsolete function
Currency::setAlternativeSigns public function
Currency::setCurrencyAmountFormatterManager public function Sets the currency amount formatter manager.
Currency::setCurrencyCode public function
Currency::setCurrencyNumber public function
Currency::setEntityManager public function Sets the entity manager.
Currency::setEntityTypeManager public function Sets the entity type manager.
Currency::setLabel public function
Currency::setRoundingStep public function
Currency::setSign public function
Currency::setSubunits public function
Currency::setUsages public function
Currency::toArray public function Gets an array of all property values. Overrides ConfigEntityBase::toArray
Currency::__construct public function Constructs an Entity object. Overrides ConfigEntityBase::__construct
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function Aliased as: traitSleep 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency. Aliased as: addDependencyTrait
EntityBase::$enforceIsNew protected property Boolean indicating whether the entity should be forced to be new.
EntityBase::$entityTypeId protected property The entity type.
EntityBase::$typedData protected property A typed data object wrapping this entity.
EntityBase::access public function Checks data value access. Overrides AccessibleInterface::access 1
EntityBase::bundle public function Gets the bundle of the entity. Overrides EntityInterface::bundle 1
EntityBase::create public static function Constructs a new entity object, without permanently saving it. Overrides EntityInterface::create
EntityBase::delete public function Deletes an entity permanently. Overrides EntityInterface::delete 2
EntityBase::enforceIsNew public function Enforces an entity to be new. Overrides EntityInterface::enforceIsNew
EntityBase::entityManager Deprecated protected function Gets the entity manager.
EntityBase::entityTypeBundleInfo protected function Gets the entity type bundle info service.
EntityBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyTrait::getCacheContexts
EntityBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyTrait::getCacheMaxAge
EntityBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyTrait::getCacheTags
EntityBase::getConfigDependencyKey public function Gets the key that is used to store configuration dependencies. Overrides EntityInterface::getConfigDependencyKey
EntityBase::getEntityType public function Gets the entity type definition. Overrides EntityInterface::getEntityType
EntityBase::getEntityTypeId public function Gets the ID of the type of the entity. Overrides EntityInterface::getEntityTypeId
EntityBase::getListCacheTagsToInvalidate protected function The list cache tags to invalidate for this entity.
EntityBase::getTypedData public function Gets a typed data object for this entity object. Overrides EntityInterface::getTypedData
EntityBase::hasLinkTemplate public function Indicates if a link template exists for a given key. Overrides EntityInterface::hasLinkTemplate
EntityBase::label public function Gets the label of the entity. Overrides EntityInterface::label 6
EntityBase::language public function Gets the language of the entity. Overrides EntityInterface::language 1
EntityBase::languageManager protected function Gets the language manager.
EntityBase::linkTemplates protected function Gets an array link templates. 1
EntityBase::load public static function Loads an entity. Overrides EntityInterface::load
EntityBase::loadMultiple public static function Loads one or more entities. Overrides EntityInterface::loadMultiple
EntityBase::postCreate public function Acts on a created entity before hooks are invoked. Overrides EntityInterface::postCreate 4
EntityBase::postDelete public static function Acts on deleted entities before the delete hook is invoked. Overrides EntityInterface::postDelete 16
EntityBase::postLoad public static function Acts on loaded entities. Overrides EntityInterface::postLoad 2
EntityBase::postSave public function Acts on a saved entity before the insert or update hook is invoked. Overrides EntityInterface::postSave 14
EntityBase::preCreate public static function Changes the values of an entity before it is created. Overrides EntityInterface::preCreate 5
EntityBase::referencedEntities public function Gets a list of entities referenced by this entity. Overrides EntityInterface::referencedEntities 1
EntityBase::toLink public function Generates the HTML for a link to this entity. Overrides EntityInterface::toLink
EntityBase::uriRelationships public function Gets a list of URI relationships supported by this entity. Overrides EntityInterface::uriRelationships
EntityBase::urlRouteParameters protected function Gets an array of placeholders for this entity. 2
EntityBase::uuid public function Gets the entity UUID (Universally Unique Identifier). Overrides EntityInterface::uuid 1
EntityBase::uuidGenerator protected function Gets the UUID generator.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SynchronizableEntityTrait::$isSyncing protected property Whether this entity is being created, updated or deleted through a synchronization process.
SynchronizableEntityTrait::isSyncing public function
SynchronizableEntityTrait::setSyncing public function