public function Run() { $resArray = []; $objPHPExcel = @\PHPExcel_IOFactory::load($this->filePath); if ($objPHPExcel) { $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $headerArray = $sheetData[1]; unset($sheetData[1]); foreach ($sheetData as $k => $itemArray) { $itemArray = @array_combine($headerArray, $itemArray); if ($itemArray) { try { $model = DynamicModel::validateData($itemArray, [[['id', 'type', 'available', 'bid', 'price', 'currencyId', 'categoryId', 'name', 'ISBN'], 'required']]); } catch (UnknownPropertyException $e) { continue; } if (isset($model) && !$model->hasErrors()) { $resArray[] = $itemArray; } } } } $this->response = $resArray; unlink($this->filePath); return $this; }
/** * Create jobs from recived data * * ```php * $_POST = [ * 'callback' => 'http://www.bn.ru/../', // Callback url * 'name' => 'www.bn.ru', * 'data' => [ * [ * 'command' => 0, * 'object_id' => '772dab1a-4b4f-11e5-885d-feff819cdc9f', * 'url' => 'http://www.bn.ru/images/photo/2015_08/201508252016081835551362b.jpg', * 'file_id' => 'a34c0e31-aaf8-43d9-a6ca-be9800dea5b7', * ], * [ * 'command' => 1, * 'object_id' => 'c1b270c4-4b51-11e5-885d-feff819cdc9f', * 'url' => 'http://www.bn.ru/images/photo/2015_08/201508252016121946987850b.jpg', * 'file_id' => '92d05f7c-c8fb-472f-9f9a-b052521924e1', * ], * ], * ]; * ``` * * @return string JSON */ public function actionCreate() { $return = ['status' => false]; $errors = []; $name = \Yii::$app->request->post('name', null); $callback = \Yii::$app->request->post('callback', null); $data = \Yii::$app->request->post('data', null); $config = [[['name', 'callback', 'data'], 'required'], ['callback', 'url', 'enableIDN' => true, 'message' => \Yii::t('yii', "{attribute} is not a valid URL: '{$callback}'!")]]; $model = \yii\base\DynamicModel::validateData(compact('name', 'callback', 'data'), $config); if ($model->hasErrors()) { throw new BadRequestHttpException(json_encode($model->getErrors())); } $name = $name . '::' . microtime(true); $sources = array_chunk($data, $this->maxPostCount); $countJobs = 0; $jobsModel = static::$component->jobsModel(); foreach ($sources as $source) { static::$component->addSource($name, $source); if (static::$component->addJob($name, $callback, $jobsModel::STATUS_WAIT)) { ++$countJobs; } } if ($countJobs) { $return['status'] = true; } else { throw new BadRequestHttpException(\Yii::t('yii', 'Error create project!')); } return $return; }
/** * @inheritdoc */ public function run() { if (Yii::$app->request->isPost) { $file = UploadedFile::getInstanceByName($this->incomingFieldName); $model = DynamicModel::validateData(compact('file')); $model->addRule('file', $this->isImage ? 'image' : 'file', $this->validationOptions); if ($model->hasErrors()) { return $this->getResult(false, implode('; ', $model->getErrors('file'))); } else { if ($this->isUseUniqueFileNames) { $filename = uniqid($this->isUseFileNamesAsPrefix ? $file->baseName : $this->customPrefix) . '.' . $file->extension; } else { $filename = $file->baseName . '.' . $file->extension; } if (@$file->saveAs($this->savePath . $filename)) { return $this->getResult(true, '', ['access_link' => $this->accessUrl . $filename]); } return $this->getResult(false, 'File can\'t be placed to destination folder'); } } else { throw new BadRequestHttpException('Only Post request allowed for this action!'); } $uploads_dir = '/var/tmp'; if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) { $tmp_name = $_FILES["file"]["tmp_name"]; $name = $_FILES["file"]["name"]; move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}"); } return ['success' => true, 'value' => '/uploads/some.file.txt']; }
/** * 发送短信 * @param string $receiveMobileTel 接收手机号,多个号码可以使用;号分隔 * @param string $message 消息 * @param string $actionMark 功能点标识 * @throws InvalidConfigException 初始化配置错误 * @throws InvalidParamException 参数错误 * @throws InvalidCallException 调用短信服务发短信出错 */ public function send($receiveMobileTel, $message, $actionMark = '') { if (!$this->validate()) { throw new InvalidConfigException(implode(" ", $this->firstErrors)); } $modeTemp = DynamicModel::validateData(compact('receiveMobileTel', 'message'), [[['message', 'receiveMobileTel'], 'filter', 'filter' => 'trim'], [['receiveMobileTel', 'message'], 'required']]); if ($modeTemp->hasErrors()) { throw new InvalidParamException(implode(' ', $modeTemp->firstErrors)); } $sendResult = explode(',', $this->sendSms($receiveMobileTel, $message), 2); $code = is_int($sendResult[0] + 0) ? $sendResult[0] + 0 : -127; $msgId = isset($sendResult[1]) ? $sendResult[1] : ''; try { $log = new SmsSendLog(); $log->receive_mobile_tel = $receiveMobileTel; $log->message = $message; $log->action_mark = $actionMark; $log->result = $code; $log->msg_ids = $msgId; $log->save(); } catch (\Exception $ex) { Yii::error($ex); } if ($code <= 0) { throw new InvalidCallException($this->getSendErrorMsg($code)); } }
public function actionImport() { $field = ['fileImport' => 'File Import']; $modelImport = DynamicModel::validateData($field, [[['fileImport'], 'required'], [['fileImport'], 'file', 'extensions' => 'xls,xlsx', 'maxSize' => 1024 * 1024]]); if (Yii::$app->request->post()) { $modelImport->fileImport = \yii\web\UploadedFile::getInstance($modelImport, 'fileImport'); if ($modelImport->fileImport && $modelImport->validate()) { $inputFileType = \PHPExcel_IOFactory::identify($modelImport->fileImport->tempName); $objReader = \PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($modelImport->fileImport->tempName); $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true); $baseRow = 2; while (!empty($sheetData[$baseRow]['A'])) { $model = new Mahasiswa(); $model->nama = (string) $sheetData[$baseRow]['B']; $model->nim = (string) $sheetData[$baseRow]['C']; $model->save(); //die(print_r($model->errors)); $baseRow++; } Yii::$app->getSession()->setFlash('success', 'Success'); } else { Yii::$app->getSession()->setFlash('error', 'Error'); } } return $this->redirect(['index']); }
private function runGet() { $request = Yii::$app->getRequest(); $model = DynamicModel::validateData(['id' => $request->get('id'), 'screen_name' => $request->get('screen_name'), 'count' => $request->get('count'), 'newer_than' => $request->get('newer_than'), 'older_than' => $request->get('older_than')], [[['id'], 'exist', 'targetClass' => Battle::className(), 'targetAttribute' => 'id'], [['screen_name'], 'exist', 'targetClass' => User::className(), 'targetAttribute' => 'screen_name'], [['newer_than', 'older_than'], 'integer'], [['count'], 'default', 'value' => 10], [['count'], 'integer', 'min' => 1, 'max' => 100]]); if (!$model->validate()) { return $this->formatError($model->getErrors(), 400); } $query = Battle::find()->innerJoinWith('user')->with(['user', 'user.userStat', 'lobby', 'rule', 'map', 'weapon', 'weapon.subweapon', 'weapon.special', 'rank', 'battleImageResult', 'battleImageJudge'])->orderBy('{{battle}}.[[id]] DESC')->limit((int) $model->count); if ($model->id != '') { $query->andWhere(['{{battle}}.[[id]]' => $model->id]); } if ($model->screen_name != '') { $query->andWhere(['{{user}}.[[screen_name]]' => $model->screen_name]); } if ($model->newer_than > 0) { $query->andWhere(['>', '{{battle}}.[[id]]', $model->newer_than]); } if ($model->older_than > 0) { $query->andWhere(['<', '{{battle}}.[[id]]', $model->older_than]); } $list = $query->all(); if ($model->id != '') { return empty($list) ? null : $this->runGetImpl(array_shift($list)); } $resp = Yii::$app->getResponse(); $resp->format = 'json'; return array_map(function ($model) { return $model->toJsonArray(); }, $list); }
public function testFormatting() { $model = DynamicModel::validateData(['phone' => '04 978 0738'], [['phone', PhoneNumberValidator::className(), 'expectedRegion' => 'NZ', 'format' => PhoneNumberValidator::FORMAT_NATIONAL]]); $this->assertEquals('04-978 0738', $model->phone); $model = DynamicModel::validateData(['phone' => '04 978 0738'], [['phone', PhoneNumberValidator::className(), 'expectedRegion' => 'NZ', 'format' => PhoneNumberValidator::FORMAT_INTERNATIONAL]]); $this->assertEquals('+64 4-978 0738', $model->phone); $model = DynamicModel::validateData(['phone' => '04 978 0738'], [['phone', PhoneNumberValidator::className(), 'expectedRegion' => 'NZ', 'format' => PhoneNumberValidator::FORMAT_E164]]); $this->assertEquals('+6449780738', $model->phone); }
private function createAndValidateRequestForm() { $req = Yii::$app->request; $model = DynamicModel::validateData(['region' => $req->get('region'), 'order' => $req->get('order')], [[['region', 'order'], 'required'], [['region'], 'string', 'min' => 2, 'max' => 2], [['order'], 'integer', 'min' => 1]]); if ($model->validate()) { return $model; } return false; }
public function dynamicFileValidate() { $model = DynamicModel::validateData(['file' => $this->file], [['file', 'file', 'maxSize' => $this->validateCategoryMaxSize(), 'extensions' => $this->validateCategoryExtensions()]]); if ($model->hasErrors()) { $this->addErrors($model->getErrors()); return false; } else { return true; } }
public function testValidateData() { $email = 'invalid'; $name = 'long name'; $age = ''; $model = DynamicModel::validateData(compact('name', 'email', 'age'), [[['email', 'name', 'age'], 'required'], ['email', 'email'], ['name', 'string', 'max' => 3]]); $this->assertTrue($model->hasErrors()); $this->assertTrue($model->hasErrors('email')); $this->assertTrue($model->hasErrors('name')); $this->assertTrue($model->hasErrors('age')); }
/** * Updates an existing User model. * If update is successful, the browser will be redirected to the 'view' page. * @param null $id * @return string|\yii\web\Response * @throws ForbiddenHttpException * @throws NotFoundHttpException * @throws \yii\base\InvalidConfigException */ public function actionUpdate($id = null) { if ($id === null) { $id = Adm::getInstance()->user->getId(); } /* @var $model \pavlinter\adm\models\User */ $model = $this->findModel($id); if (Adm::getInstance()->user->can('Adm-UpdateOwnUser', $model)) { $model->setScenario('adm-updateOwn'); } elseif (Adm::getInstance()->user->can('AdmRoot')) { $model->setScenario('adm-update'); } else { throw new ForbiddenHttpException('Access denied'); } $dynamicModel = DynamicModel::validateData(['password', 'password2'], [[['password', 'password2'], 'string', 'min' => 6], ['password2', 'compare', 'compareAttribute' => 'password']]); $post = Yii::$app->request->post(); if ($model->load($post) && $dynamicModel->load($post)) { if ($model->validate() && $dynamicModel->validate()) { if (!empty($dynamicModel->password)) { $model->setPassword($dynamicModel->password); } if (!Adm::getInstance()->user->can('Adm-UpdateOwnUser', $model)) { //AdmRoot $auth = Yii::$app->authManager; $roles = Yii::$app->request->post('roles', []); $auth->revokeAll($model->id); //remove all assignments if (in_array('AdmRoot', $roles) || in_array('AdmAdmin', $roles)) { $model->role = \app\models\User::ROLE_ADM; } else { $model->role = \app\models\User::ROLE_USER; } foreach ($roles as $role) { $newRole = $auth->createRole($role); $auth->assign($newRole, $model->id); } } $model->save(false); Yii::$app->getSession()->setFlash('success', Adm::t('', 'Data successfully changed!')); if (Adm::getInstance()->user->can('Adm-UpdateOwnUser', $model)) { return $this->refresh(); } else { //AdmRoot return Adm::redirect(['update', 'id' => $model->id]); } } } return $this->render('update', ['model' => $model, 'dynamicModel' => $dynamicModel]); }
public function beforeSave($insert) { $validators = $this->getTypes(false); if (!array_key_exists($this->type, $validators)) { $this->addError('type', Module::t('settings', 'Please select correct type')); return false; } $model = DynamicModel::validateData(['value' => $this->value], [$validators[$this->type]]); if ($model->hasErrors()) { $this->addError('value', $model->getFirstError('value')); return false; } if ($this->hasErrors()) { return false; } return parent::beforeSave($insert); }
public function run() { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $root = $this->folder === null ? Yii::getAlias('@webroot/images') : $this->folder; if (!is_dir($root)) { mkdir($root, 0700, true); } $webroot = $this->webroot === null ? Yii::getAlias('@webroot') : $this->webroot; $relpath = Yii::$app->request->post('path', ''); $this->path = $root; if (realpath($root . $relpath) && strpos(realpath($root . $relpath), $root) !== false) { $this->path = realpath($root . $relpath) . DIRECTORY_SEPARATOR; } $folder = str_replace($webroot, '', $this->path); $result = (object) ['error' => 0, 'msg' => '', 'files' => [], 'path' => '', 'baseurl' => '']; $msg = []; if (true || Yii::$app->request->isPost) { if ($this->uploadModel === null) { $uploadModel = \yii\base\DynamicModel::validateData(['images' => UploadedFile::getInstancesByName('files')], [[['images'], 'file', 'extensions' => 'jpg, png, jpeg', 'maxFiles' => 10, 'mimeTypes' => 'image/jpeg, image/png']]); } else { $uploadModel = $this->uploadModel; $uploadModel->images = UploadedFile::getInstancesByName('files'); $uploadModel->validate(); } if (!$uploadModel->hasErrors() && count($uploadModel->images)) { foreach ($uploadModel->images as $image) { $uploadedFile = $this->saveImage($image); if ($uploadedFile === false) { $result->error = 4; } else { $result->files[] = $folder . $uploadedFile; $this->afterFileSave($uploadedFile, $this->path, $folder); } } } else { $result->error = 3; } } else { $result->error = 2; } $result->msg = $this->messages[$result->error]; // \yii\helpers\VarDumper::dump($_FILES['files']); // \yii\helpers\VarDumper::dump($uploadModel); return $result; }
public function actionSettings() { if (\Yii::$app->user->isGuest) { return $this->redirect(Url::toRoute('/')); } if (\Yii::$app->user->identity && \Yii::$app->user->identity->role != User::ROLE_ADMIN) { return $this->redirect(Url::toRoute('/')); } $page = Yii::$app->request->get('page', 'general'); $_dynamicModel = $this->_dynamicModel; $sidemenus = ['general' => ['title' => Yii::t('app', 'Общие настройки'), 'url' => Url::toRoute(['super-admin/settings', 'page' => 'general']), 'active' => $page == 'general', 'settings' => ['site_name', 'demo_account_id', 'manager_notification_email', 'manager_notification_status-' . Photobook::STATUS_NEW, 'manager_notification_status-' . Photobook::STATUS_SENT_TO_CUSTOMER, 'manager_notification_status-' . Photobook::STATUS_WAIT_EDIT_FROM_CUSTOMER, 'manager_notification_status-' . Photobook::STATUS_SENT_TO_PRINT, 'manager_notification_status-' . Photobook::STATUS_READY_FOR_PRINT_WAIT_PAYMENT, 'manager_notification_status-' . Photobook::STATUS_READY_FOR_PRINT_PAID, 'manager_notification_status-' . Photobook::STATUS_READY_SENT_TO_PRINT, 'manager_notification_status-' . Photobook::STATUS_READY, 'manager_notification_status-' . Photobook::STATUS_READY_SENT_TO_CLIENT, 'manager_notification_status-' . Photobook::STATUS_RECEIVED_FEEDBACK, 'manager_notification_status-' . Photobook::STATUS_ARCHIVE, 'note_upload_page', 'photobook_thumb_as_object'], 'validation' => ['site_name' => [['value', 'required'], ['value', 'string', 'min' => 2, 'max' => 255]], 'manager_notification_email' => [['value', 'filter', 'filter' => 'trim'], ['value', 'email']], 'demo_account_id' => [['value', 'filter', 'filter' => 'trim'], ['value', 'app\\components\\DemoAccountIdValidator']]]], 'currency' => ['title' => Yii::t('app', 'Курсы валют'), 'url' => Url::toRoute(['super-admin/settings', 'page' => 'currency']), 'active' => $page == 'currency', 'settings' => ['currencies', 'main_currency', 'default_currency']], 'email_notification' => ['title' => Yii::t('app', 'Шаблоны Email оповещений'), 'url' => Url::toRoute(['super-admin/settings', 'page' => 'email_notification']), 'active' => $page == 'email_notification', 'settings' => ['manager_notification_change_status', 'manager_notification_new_user', 'user_notification_change_status', 'user_notification_invoice_link', 'user_notification_payment_received', 'customer_notification_link_for_comments']], 'liqpay' => ['title' => Yii::t('app', 'Настройки LiqPay'), 'url' => Url::toRoute(['super-admin/settings', 'page' => 'liqpay']), 'active' => $page == 'liqpay', 'settings' => ['liqpay_public_key', 'liqpay_private_key']]]; $active_page = $sidemenus[$page]; // Yii::$app->request->v Yii::getLogger()->log('TEST1', YII_DEBUG); $form = Yii::$app->request->post('SettingForm', null); $model = new SettingForm(); $errors_list_data = []; if (!empty($form)) { foreach ($form as $name => $value) { if (!empty($active_page['validation']) && !empty($active_page['validation'][$name])) { $this->_dynamicModel = DynamicModel::validateData(compact('value'), $active_page['validation'][$name]); if ($this->_dynamicModel->hasErrors()) { $active_page['errors'][$name] = $this->_dynamicModel->errors['value']; $errors_list_data[$name] = $value; } else { $model->setValue($name, $value); } } else { $model->setValue($name, $value); } } } $settings = []; foreach ($active_page['settings'] as $key => $setting) { if (!isset($errors_list_data[$setting])) { $settings[$setting] = $model->getValue($setting, ''); } else { $settings[$setting] = $errors_list_data[$setting]; } } $this->layout = 'default'; return $this->render($page, ['sidemenus' => $sidemenus, 'settings' => $settings, 'active_page' => $active_page]); }
public function Run() { $resArray = []; $json = @file_get_contents($this->filePath); if (isset($json) && ($priceArray = json_decode($json, true))) { foreach ($priceArray as $k => $itemArray) { try { $model = DynamicModel::validateData($itemArray, [[['id', 'type', 'available', 'bid', 'price', 'currencyId', 'categoryId', 'name', 'ISBN'], 'required']]); } catch (UnknownPropertyException $e) { continue; } if (isset($model) && !$model->hasErrors()) { $resArray[] = $itemArray; } } } $this->response = $resArray; unlink($this->filePath); return $this; }
/** * @return bool|string * @throws \yii\base\InvalidConfigException */ public function getContent() { if ($this->rules()) { $data = []; $fields = $this->fields(); if ($fields) { foreach ($fields as $val) { if (property_exists($this, $val)) { $data[$val] = $this->{$val}; } } } $model = DynamicModel::validateData($data, $this->rules()); if ($model->hasErrors()) { // todo: 记录错误日志 return false; } else { return Json::encode($data); } } }
public function run() { $response = []; $uploadedFiles = UploadedFile::getInstancesByName($this->fileParam); foreach ($uploadedFiles as $uploadedFile) { $responseFile = new \stdClass(); $responseFile->{$this->responseParamsMap['name']} = $uploadedFile->name; $responseFile->{$this->responseParamsMap['type']} = $uploadedFile->type; $responseFile->{$this->responseParamsMap['size']} = $uploadedFile->size; if (!$uploadedFile->hasError) { $model = DynamicModel::validateData(['file' => $uploadedFile], $this->validationRules); if (!$model->hasErrors()) { $filesystemComponent = $this->getFilesystemComponent(); $filesystem = $this->getFilesystem(); /** @var FileInterface $fileClass */ $fileClass = $this->fileClass; $file = $fileClass::getInstanceFromUploadedFile($uploadedFile); //$path = $this->path . DIRECTORY_SEPARATOR . $uploadedFile->name; $path = $this->path . DIRECTORY_SEPARATOR . date('dmYHis') . '-' . $file->getBasename() . '.' . $uploadedFile->extension; $path = $filesystemComponent->saveFile($file, $filesystem, $path); if ($path) { $file->setPath($path); $responseFile->{$this->responseParamsMap['filesystem']} = $filesystem; $responseFile->{$this->responseParamsMap['path']} = $path; $responseFile->{$this->responseParamsMap['name']} = $uploadedFile->name; $responseFile->{$this->responseParamsMap['url']} = $filesystemComponent->getUrl($file, $filesystem); $responseFile->{$this->responseParamsMap['deleteUrl']} = Url::to([$this->deleteRoute, 'path' => $path]); } else { $responseFile->{$this->responseParamsMap['error']} = 'Saving error'; } } else { $responseFile->{$this->responseParamsMap['error']} = $model->errors; } } else { $responseFile->{$this->responseParamsMap['error']} = $uploadedFile->error; } $response['files'][] = $responseFile; } return $this->multiple ? $response : array_shift($response); }
public function Run() { $resArray = []; libxml_use_internal_errors(true); $xmlstr = @file_get_contents($this->filePath); try { $xml = new \SimpleXMLElement($xmlstr); } catch (\Exception $e) { echo $e->getMessage(); } if (isset($xml)) { if (strtolower($xml->getName()) === 'yml_catalog') { $priceArray =& $xml->shop->offers->offer; foreach ($priceArray as $key => $subArray) { $itemArray = []; foreach ($subArray->attributes() as $k => $v) { $itemArray[$k] = $v->__toString(); } foreach ($subArray as $k => $v) { $itemArray[$k] = $v->__toString(); } try { $model = DynamicModel::validateData($itemArray, [[['id', 'type', 'available', 'bid', 'price', 'currencyId', 'categoryId', 'name', 'ISBN'], 'required']]); } catch (UnknownPropertyException $e) { continue; } if (isset($model) && !$model->hasErrors()) { $resArray[] = $itemArray; } } } } $this->response = $resArray; unlink($this->filePath); return $this; }
public function Run() { $file = @fopen($this->filePath, 'r'); $resArray = []; if ((isset($file) && ($line = fgetcsv($file, 0, ';'))) !== FALSE) { $headerArray = $line; while (($line = fgetcsv($file, 0, ';')) !== FALSE) { $itemArray = @array_combine($headerArray, $line); if ($itemArray) { try { $model = DynamicModel::validateData($itemArray, [[['id', 'type', 'available', 'bid', 'price', 'currencyId', 'categoryId', 'name', 'ISBN'], 'required']]); } catch (UnknownPropertyException $e) { continue; } if (isset($model) && !$model->hasErrors()) { $resArray[] = $itemArray; } } } } $this->response = $resArray; unlink($this->filePath); return $this; }
private function makeValidationModel() { $model = DynamicModel::validateData(['language' => null], [[['language'], 'required'], [['language'], 'exist', 'targetClass' => Language::className(), 'targetAttribute' => 'lang']]); return $model; }
public function __construct() { $request = Yii::$app->request->get(); list($this->checkField, $this->checkValue) = isset($request['login']) ? ['login', $request['login']] : ['card_number', $request['card_number']]; $this->model = DynamicModel::validateData(['checkField' => $this->checkValue], [['checkField', 'required', 'message' => Yii::t('terminal', 'error_checkField_required')]]); }
/** * @return array * @throws \HttpException */ public function run() { $result = []; $uploadedFiles = UploadedFile::getInstancesByName($this->fileparam); foreach ($uploadedFiles as $uploadedFile) { /* @var \yii\web\UploadedFile $uploadedFile */ $output = [$this->responseNameParam => Html::encode($uploadedFile->name), $this->responseMimeTypeParam => $uploadedFile->type, $this->responseSizeParam => $uploadedFile->size, $this->responseBaseUrlParam => $this->getFileStorage()->baseUrl]; if ($uploadedFile->error === UPLOAD_ERR_OK) { $validationModel = DynamicModel::validateData(['file' => $uploadedFile], $this->validationRules); if (!$validationModel->hasErrors()) { $path = $this->getFileStorage()->save($uploadedFile); if ($path) { $output[$this->responsePathParam] = $path; $output[$this->responseUrlParam] = $this->getFileStorage()->baseUrl . '/' . $path; $output[$this->responseDeleteUrlParam] = Url::to([$this->deleteRoute, 'path' => $path]); $paths = \Yii::$app->session->get($this->sessionKey, []); $paths[] = $path; \Yii::$app->session->set($this->sessionKey, $paths); $this->afterSave($path); } else { $output['error'] = true; $output['errors'] = []; } } else { $output['error'] = true; $output['errors'] = $validationModel->errors; } } else { $output['error'] = true; $output['errors'] = $this->resolveErrorMessage($uploadedFile->error); } $result['files'][] = $output; } return $this->multiple ? $result : array_shift($result); }
public function __construct() { $payAmount = Yii::$app->request->get('pay_amount'); $this->model = DynamicModel::validateData(compact('payAmount'), [['payAmount', 'required', 'message' => Yii::t('terminal', 'error_payAmount_required')], ['payAmount', 'integer', 'message' => Yii::t('terminal', 'error_payAmount_should_be_integer')]]); }
/** * @inheritdoc * @return \Closure */ public function getEmailFilter() { if ($this->_emailFilter === null) { $this->setEmailFilter(function ($email, $row) { $model = \yii\base\DynamicModel::validateData(['email' => $email], [['email', 'email']]); return !$model->hasErrors(); }); } return $this->_emailFilter; }
/** * Экшн для вывода из базы таблицы с фильтрацией по дате. * Динамическая валидация POST. * Обращается к static search(() из app\models\DatabaseSearch; */ public function actionList() { if ($input = Yii::$app->request->post()) { try { /*Валидация*/ $input_as_array = array_keys($input); $model = DynamicModel::validateData($input, [[$input_as_array, 'required']]); if ($model->hasErrors() || $input[date1] >= $input[date2]) { throw new ErrorException("Не верные даты!"); } else { try { $result = DatabaseSearch::search($input); } catch (Exception $e) { return $this->render('info', ['msg' => "Нет соединения с базой"]); } return $this->render('getlist', ['result' => $result]); } } catch (ErrorException $e) { return $this->render('info', ['msg' => $e->getMessage()]); } } return $this->render('getlist'); }
private function makeValidationModel() { $model = DynamicModel::validateData(['timezone' => null], [[['timezone'], 'required'], [['timezone'], 'exist', 'targetClass' => Timezone::className(), 'targetAttribute' => 'identifier']]); return $model; }
/** * @return array * @throws \HttpException */ public function run() { $result = []; $uploadedFiles = UploadedFile::getInstancesByName($this->fileparam); foreach ($uploadedFiles as $uploadedFile) { /* @var \yii\web\UploadedFile $uploadedFile */ $output = []; $output['id'] = -1; $output[$this->responseUrlParam] = ""; $output['thumbnailUrl'] = ""; $output['deleteUrl'] = ""; $output['updateUrl'] = ""; $output['path'] = ""; if ($uploadedFile->error === UPLOAD_ERR_OK) { $validationModel = DynamicModel::validateData(['file' => $uploadedFile], $this->validationRules); if (!$validationModel->hasErrors()) { $attachment = new Attachment(); if ($this->storageLocation == static::STORAGE_LOCATION_TEMPPATH) { $attachment->setStorageDirectory($attachment->getTempDirectory()); $attachment->uploadFromPost($uploadedFile); } else { if ($this->storageLocation == static::STORAGE_LOCATION_USERPATH_DATABASE) { $attachment->uploadFromPost($uploadedFile); $attachment->save(); } } $output = array_merge($output, $attachment->toArray()); if ($attachment->primaryKey) { $output["id"] = $attachment->primaryKey; } $output["path"] = $attachment->getPath(); $output[$this->responseUrlParam] = $attachment->getUrl(); $output["thumbnailUrl"] = $attachment->getUrl(); $output["deleteUrl"] = Url::to(array_merge($this->deleteUrl, ['path' => $output["path"], 'id' => $output['id']])); $output["updateUrl"] = Url::to(array_merge($this->updateUrl, ['path' => $output["path"], 'id' => $output['id']])); } else { $output['error'] = true; $output['errors'] = $validationModel->errors; } } else { $output['error'] = true; $output['errors'] = $this->resolveErrorMessage($uploadedFile->error); } $result["files"][] = $output; } $result = $this->multiple ? $result : array_shift($result); return $result; }
public function actionSetContacts() { \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $post = Yii::$app->request->post(); $model = DynamicModel::validateData($post, [[Domain::$contactOptions, 'required']]); if ($model->hasErrors()) { return ['errors' => $model->errors]; } $ids = Yii::$app->request->post('id'); $data = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator(array_map(function ($i) use($post) { return [$i => $post[$i]]; }, Domain::$contactOptions)))); $preparedData = []; foreach ($ids as $id) { $preparedData[] = ArrayHelper::merge(['id' => $id], $data); } try { $result = Domain::perform('SetContacts', $preparedData, true); } catch (\Exception $e) { $result = ['errors' => ['title' => $e->getMessage(), 'detail' => $e->getMessage()]]; } return $result; }
/** * Updates an existing User model. * If update is successful, the browser will be redirected to the 'view' page. * @param null $id * @return string|\yii\web\Response * @throws ForbiddenHttpException * @throws NotFoundHttpException * @throws \yii\base\InvalidConfigException */ public function actionUpdate($id = null) { if ($id === null) { $id = Adm::getInstance()->user->getId(); } /* @var $model \pavlinter\adm\models\User */ $model = $this->findModel($id); if (Adm::getInstance()->user->can('Adm-UpdateOwnUser', $model)) { $model->setScenario('adm-updateOwn'); } elseif (Adm::getInstance()->user->can('AdmRoot')) { $model->setScenario('adm-update'); } else { throw new ForbiddenHttpException('Access denied'); } $dynamicModel = DynamicModel::validateData(['password', 'password2'], [[['password', 'password2'], 'string', 'min' => 6], ['password2', 'compare', 'compareAttribute' => 'password']]); $post = Yii::$app->request->post(); if ($model->load($post) && $dynamicModel->load($post)) { if ($model->validate() && $dynamicModel->validate()) { if (!empty($dynamicModel->password)) { $model->setPassword($dynamicModel->password); } $model->save(false); if (Adm::getInstance()->user->can('Adm-UpdateOwnUser', $model)) { Yii::$app->getSession()->setFlash('success', Adm::t('', 'Data successfully changed!')); return $this->refresh(); } else { Yii::$app->getSession()->setFlash('success', Adm::t('', 'Data successfully changed!')); return Adm::redirect(['update', 'id' => $model->id]); } } } return $this->render('update', ['model' => $model, 'dynamicModel' => $dynamicModel]); }