S
S
Svetlana Galenko2018-12-02 21:01:42
This
Svetlana Galenko, 2018-12-02 21:01:42

Unable to submit and find request in database Class 'app\models\' not found?

Hello, I ran into such a problem, a certain query "name" that the user entered is not saved in the database, and even this stupid error flies out that I can't handle at all .. apparently I'm dumber than her .. please tell me what's the catch?
Here is the error in full:

PHP Fatal Error – yii\base\ErrorException
Class 'app\models\' not found

 1. in /var/www/u0598324/public_html/webstels.com/models/ShopPromoItem.php at line 40

                                return [
                'status' => 'Статус',
            ];
        }
     
        public static function get($id)
        {
            $item = ShopPromoItem::findOne($id);
            $class = 'app\\models\\' . $item->class;
            return $class::findOne($id);
        }
     
        public function getTitle()
        {
            return Html::encode($this->title);
        }
     
        public function getPriceArray()
        {
                    

    2. yii\base\ErrorHandler::handleFatalError()

$_GET = [
    'username' => 'swallowsveta1997',
];

$_POST = [
    '_csrf' => '2dWdOMdf_z2HrgmbtpnKKN1f-mQnpLEkeqpEkFg8zj6OoOR-sAa2DrOcQ-GG7otyuxSIXEzn6R0M5jX5Cw2cVw==',
    'ShopPromoItemBuyForm' => [
        'name' => 'name',
        'item_id' => '1',
    ],
];

$_COOKIE = [
    '_identity' => 'd669e918ca5f102ab0802a521e1d3fc241689f04dbb51253b7b8ab7b54713c5ca:2:{i:0;s:9:"_identity";i:1;s:50:"[22727,"gkEvlaqhpnAtz8mz4v9Fk96QOpkIrssI",2592000]";}',
    'PHPSESSID' => 'abe468adef98b859d2100b97cb6da127',
    '_csrf' => '542d3bc58acd73dd28aadc1e388c74c2697098a4c8d8bb4b855417ada2ebe4ffa:2:{i:0;s:5:"_csrf";i:1;s:32:"WuyFwYI342Jz0wAZfKr8kCX9vLqiS1Ri";}',
];

$_SESSION = [
    '__flash' => [],
    '__id' => 22727,
    '__authKey' => 'gkEvlaqhpnAtz8mz4v9Fk96QOpkIrssI',
    '__expire' => 1543857954,
    '__captcha/site/captcha' => 'lesafiq',
    '__captcha/site/captchacount' => 1,
];

Here is the ShopPromoItem.php model:
public static function get($id)
    {
        $item = ShopPromoItem::findOne($id);
        $class = 'app\\models\\' . $item->class;
        return $class::findOne($id);
    }

Вот ShopPromoItemBuyForm.php:
class ShopPromoItemBuyForm extends UserPromo
{
    public $item_id;

    public function rules()
    {
        return [
            ['item_id', 'required'],
            ['item_id', 'integer'],
            ['item_id', 'exist',
                'targetClass' => '\app\models\ShopPromoItem',
                'targetAttribute' => 'id',
                'filter' => ['status' => ShopPromoItem::STATUS_ENABLED]
            ],

            ['name', 'multProtect']
        ];
    }

    public function scenarios()
    {
        return [
            self::SCENARIO_DEFAULT => ['name']
        ];
    }

    public function multProtect()
    {
        return;

        // disable for debug mode
        if (YII_DEBUG)
            return;

        // check evercookie
        if (isset($_COOKIE['was_promo']) && $_COOKIE['was_promo'] == "true") {
            $this->addError('name', \Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
        }
        $validator = new IpValidator();
        if ($validator->validate(\Yii::$app->request->userPromoIP)) {
            $ip = \Yii::$app->request->userPromoIP;
            $userPromo = UserPromo::find()->where(['id' => $ip])->limit(1)->one();
            if ($userPromo !== null) {
                $this->addError('name', \Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
            }
        } else {
            $this->addError('name', \Yii::t('app', 'Вы уже заказывали сайт с таким названием на проекте, повторный заказ сайта с таким именем запрещён'));
        }
    }

    public function buy(User $user)
    {
        if (!$this->validate()) {
            \Yii::$app->getSession()->setFlash('warning', implode('<br />', $this->getFirstErrors()));
            return false;
        }

        if (\Yii::$app->mutex->acquire('balance_' . $user->id)) {
            \Yii::$app->db->transaction(function() use ($user) {
                $item = ShopPromoItem::get($this->item_id);
                $prices = $item->getPriceArray();

                // check balance
                foreach ($prices as $currency => $price) {
                    if (!$user->balance->has($currency, BalanceHelper::convertToDigits($price))) {
                        \Yii::$app->getSession()->setFlash('warning', \Yii::t('app', 'Недостаточно средств на балансе'));
                        return false;
                    }
                }

                // decrease balance
                foreach ($prices as $currency => $price) {
                    $user->balance->decrease($currency, BalanceHelper::convertToDigits($price));
                    $user->operation->create(UserOperation::OPERATION_SHOP_PROMO_BUY, $currency, BalanceHelper::convertToDigits($price), [
                        'ShopPromoItem_id' => $this->item_id
                    ]);
                }

                $item->giveTo($user);

                // give reward to referer
                RefererHelper::giveReward($user, UserBalance::CURRENCY_USD, BalanceHelper::convertToDigits($prices['usd']));

                $message = '';
                foreach ($prices as $currency => $price) {
                    $message .= \Yii::t('app', '{sum} долларов', ['sum' => BalanceHelper::convertToDigits($price)]);
                }

                \Yii::$app->getSession()->setFlash('success', \Yii::t('app', 'Вы купили «{title}»', ['title' => \Yii::t('app', $item->getTitle())]) .
                    '<br />' . \Yii::t('app', 'Потрачено {price}', ['price' => $message]));

                return true;
            });
        }
    }
}

UserPromo.php:
class UserPromo extends ActiveRecord
{
    const STATUS_ENABLED = 'enabled';
    const STATUS_DISABLED = 'disabled';
    const STATUS_DELETED = 'deleted';

    public static function tableName()
    {
        return '{{%user_promo}}';
    }

    public function rules()
    {
        return [
            ['id', 'exist'],
            ['user_id', 'integer'],

            ['name', 'required'],
            ['name', 'filter', 'filter' => 'trim'],
            ['name', 'match', 'pattern' => '#^[\w_-]+$#i'],
            ['name', 'unique', 'targetClass' => self::className(), 'message' => \Yii::t('app', 'Указанное название для вашего сайта уже занято')],
            ['name', 'string', 'min' => 2, 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'status' => 'Статус',
            'name' => \Yii::t('app', 'Название'),
        ];
    }

    public static function findIdentity($id)
    {
        $identity = static::findOne(['id' => $id]);
        return $identity;
    }

    public static function findByName($name)
    {
        return static::findOne(['name' => $name]);
    }

    public function getName()
    {
        return Html::encode($this->name);
    }

    public function getPromo()
    {
        return $this->hasOne(Promo::className(), ['id' => 'promo_id']);
    }

    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getTitle()
    {
        return $this->promo->getTitle();
    }

    public function getType()
    {
        return $this->promo->getType();
    }

    public function getProfit($type)
    {
        return $this->promo->{$type . '_profit'};
    }
}

Controller:
class PromoController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
        if (\Yii::$app->params['user']['promo']['temporaryDisabled']) {
            throw new ForbiddenHttpException('Заказ временно приостановлен');
        }
        return parent::beforeAction($action);
    }

    public function actionIndex()
    {
        $this->layout = 'page';

        $items = ShopPromoItem::find()->where([
            'status' => ShopPromoItem::STATUS_ENABLED
        ])->all();

        $model = new ShopPromoItemBuyForm();
        if ($model->load(\Yii::$app->request->post())) {
            $model->buy(\Yii::$app->user->identity);
        }

        $promo = UserPromo::find()->where([
            'user_id' => \Yii::$app->user->identity->id,
            'status' => UserPromo::STATUS_ENABLED
        ])->with('promo')->orderBy('promo_id DESC')->all();

        return $this->render('index', [
            'items' => $items,
            'model' => $model,
            'promo' => $promo,
        ]);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-12-02
@ swallow_97

Good evening.
I think the problem starts here

public static function get($id)
    {
        $item = ShopPromoItem::findOne($id);
        $class = 'app\\models\\' . $item->class;
        return $class::findOne($id);
    }

Are you sure $item->class is not empty? Check what returns ShopPromoItem::findOne($id);
AND, something is not visible in your code of this static method...
You can do this: ps If you are not using xdebug + phpstorm, then it's time to start using...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question