本文整理汇总了PHP中yii\base\DynamicModel::validateData方法的典型用法代码示例。如果您正苦于以下问题:PHP DynamicModel::validateData方法的具体用法?PHP DynamicModel::validateData怎么用?PHP DynamicModel::validateData使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类yii\base\DynamicModel
的用法示例。
在下文中一共展示了DynamicModel::validateData方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: Run
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;
}
示例2: actionCreate
/**
* 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;
}
示例3: run
/**
* @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'];
}
示例4: send
/**
* 发送短信
* @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));
}
}
示例5: actionImport
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']);
}
示例6: runGet
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);
}
示例7: testFormatting
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);
}
示例8: createAndValidateRequestForm
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;
}
示例9: dynamicFileValidate
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;
}
}
示例10: testValidateData
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'));
}
示例11: actionUpdate
/**
* 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]);
}
示例12: beforeSave
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);
}
示例13: run
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;
}
示例14: actionSettings
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]);
}
示例15: Run
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;
}