PHP code example of hao-li / laravel-amount

1. Go to this page and download the library: Download hao-li/laravel-amount library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hao-li / laravel-amount example snippets


public function getAmountAttribute($value)
{
    return $value / 100;
}

public function setAmountAttribute($value)
{
    $this->attributes['amount'] = (int)($value * 100);
}

public function getMutatedAttributes()
{
    $attributes = parent::getMutatedAttributes();

    return array_merge($attributes, $this->getAmountFields());
}

protected function mutateAttributeForArray($key, $value)
{
    return (in_array($key, $this->getAmountFields()))
        ? $value / $this->getAmountTimes($key)
        : parent::mutateAttributeForArray($key, $value);
}

public function getAttributeValue($key)
{
    $value = parent::getAttributeValue($key);
    if (in_array($key, $this->getAmountFields())) {
        $value = $value / $this->getAmountTimes($key);
    }

    return $value;
}

public function setAttribute($key, $value)
{
    if (in_array($key, $this->getAmountFields())) {
        $value = (int) round($value * $this->getAmountTimes($key));
    }
    parent::setAttribute($key, $value);
}

public function getAmountFields()
{
    return (property_exists($this, 'amountFields')) ? $this->amountFields : [];
}

public function getAmountTimes($key)
{
    $ret = 100;

    if (property_exists($this, 'amountTimes')) {
        if (is_array($this->amountTimes) && array_key_exists($key, $this->amountTimes)) {
            $ret = $this->amountTimes[$key];
        } elseif (is_numeric($this->amountTimes)) {
            $ret = $this->amountTimes;
        }
    }

    return $ret;
}

  use HaoLi\LaravelAmount\Traits\AmountTrait;
  

  use AmountTrait;
  

  protected $amountFields = ['amount'];
  

    protected $amountTimes = 100;
    

    protected $amountTimes = [
        'amount' => 100,
    ]
    

  use AmountTrait, BTrait {
      AmountTrait::setRawAttributes as amountTraitSetRawAttributes;
      BTrait::setRawAttributes as BTraitSetRawAttributes;
  }
  

  public function setRawAttributes(array $attributes, $sync = false)
  {
      $this->BTraitSetRawAttributes($attributes, $sync);
      $attributes = $this->getAttributes();
      $this->amountTraitSetRawAttributes($attributes, $sync);
  }