<?php
namespace app\modules\shop\models;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
class Currency extends ActiveRecord
{
const STATUS_ACTIVE = 1;
const STATUS_INACTIVE = 0;
public function behaviors()
{
return [
'timestamp' => [
'class' => \yii\behaviors\TimestampBehavior::class,
],
'blameable' => [
'class' => \yii\behaviors\BlameableBehavior::class,
],
'ip' => [
'class' => \yii\behaviors\AttributeBehavior::class,
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => 'created_ip',
ActiveRecord::EVENT_BEFORE_UPDATE => 'updated_ip',
],
'value' => function ($event) {
return Yii::$app->request->getUserIP();
},
],
];
}
public static function tableName()
{
return 'currency';
}
public function rules()
{
return [
[['name', 'code'], 'required'],
[['is_default', 'sort', 'status'], 'integer'],
[['decimal_places'], 'integer', 'max' => 9],
[['rate'], 'number'],
[['code'], 'string', 'length' => 3],
[['code'], 'unique'],
[['code'], 'match', 'pattern' => '/^[A-Z]+$/', 'message' => Yii::t('app', 'Это поле может содержать только строчные буквы, цифры и дефис')],
[['name', 'symbol'], 'string', 'max' => 32],
];
}
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'created_at' => Yii::t('app', 'Дата создания'),
'updated_at' => Yii::t('app', 'Дата обновления'),
'created_by' => Yii::t('app', 'Создано пользователем'),
'updated_by' => Yii::t('app', 'Обновлено пользователем'),
'created_ip' => Yii::t('app', 'Создано c IP'),
'updated_ip' => Yii::t('app', 'Обновлено c IP'),
'code' => Yii::t('app', 'Код'),
'name' => Yii::t('app', 'Название'),
'symbol' => Yii::t('app', 'Символ'),
'rate' => Yii::t('app', 'Курс'),
'decimal_places' => Yii::t('app', 'Количество знаков после запятой'),
'is_default' => Yii::t('app', 'По умолчанию'),
'sort' => Yii::t('app', 'Сортировка'),
'status' => Yii::t('app', 'Опубликован'),
];
}
public function afterSave($insert, $changedAttributes)
{
return Yii::$app->session->remove('currency');
}
public static function listItems()
{
$items = self::find()
->select(['code'])
->where(['status' => self::STATUS_ACTIVE])
->orderBy(['sort' => SORT_ASC])
->asArray()
->all();
return ArrayHelper::map($items, 'code', 'code');
}
public static function statuses()
{
return [
self::STATUS_ACTIVE => Yii::t('app', 'Опубликован'),
self::STATUS_INACTIVE => Yii::t('app', 'Не опубликован'),
];
}
}
<?php
namespace app\modules\shop\components;
use Yii;
use yii\base\BaseObject;
use app\modules\shop\models\Currency;
class CurrencyManager extends BaseObject
{
public $currencies;
public $defaultCurrency;
public $siteCurrency;
public function init()
{
parent::init();
$this->currencies = Currency::find()
->where(['status' => Currency::STATUS_ACTIVE])
->orderBy(['sort' => SORT_ASC])
->asArray()
->all();
foreach ($this->currencies as $item) {
if ($item['is_default'] == 1) {
$this->defaultCurrency = $item;
}
}
if (!Yii::$app->session['currency']) {
Yii::$app->session['currency'] = $this->defaultCurrency;
}
$this->siteCurrency = Yii::$app->session['currency'];
}
public function listCurrencies()
{
$result = [];
foreach ($this->currencies as $item) {
$result[$item['code']] = $item['code'];
}
return $result;
}
public function showPrice($offer, $symbol = true)
{
if ($offer['currency_code'] == $this->siteCurrency['code']) {
$price = $offer['price'];
} else {
foreach ($this->currencies as $item) {
if ($item['code'] == $offer['currency_code']) {
$rate = $item['rate'];
}
}
$price = ($offer['price'] * $rate) / $this->siteCurrency['rate'];
}
if ($symbol === true) {
return number_format($price, $this->siteCurrency['decimal_places'], '.', '') . ' ' . $this->siteCurrency['symbol'];
} else {
//return round($price, $this->siteCurrency['decimal_places']);
return number_format($price, $this->siteCurrency['decimal_places'], '.', '');
}
}
public function showOldPrice($offer, $symbol = true)
{
if ($offer['currency_code'] == $this->siteCurrency['code']) {
$price = $offer['old_price'];
} else {
foreach ($this->currencies as $item) {
if ($item['code'] == $offer['currency_code']) {
$rate = $item['rate'];
}
}
$price = ($offer['old_price'] * $rate) / $this->siteCurrency['rate'];
}
if ($symbol === true) {
return number_format($price, $this->siteCurrency['decimal_places'], '.', '') . ' ' . $this->siteCurrency['symbol'];
} else {
return round($price, $this->siteCurrency['decimal_places']);
}
}
}
public function getPageContent()
{
return $this->hasOne(PageContent::className(), ['page_id' => 'id'])->andWhere(['page_content.language_code' => Yii::$app->language]);
}