/**
  * Displays and/or update Score models for a competition.
  * @return mixed
  */
 public function actionCompetition($id)
 {
     $competition = $this->findCompetition($id);
     if (isset($_POST['ScorecardForCompetition'])) {
         $models = ScorecardForCompetition::find()->andWhere(['id' => array_keys($_POST['ScorecardForCompetition'])])->indexBy('id')->all();
         if (!ScorecardForCompetition::loadMultiple($models, Yii::$app->request->post()) || !ScorecardForCompetition::validateMultiple($models)) {
             $errors = [];
             foreach ($models as $model) {
                 $errors += $model->errors;
             }
             if (count($errors) > 0) {
                 Yii::$app->session->setFlash('danger', Yii::t('igolf', 'Error(s): {0}', [VarDumper::dumpAsString($errors, 4, true)]));
             }
         } else {
             foreach ($models as $model) {
                 $model->save();
             }
             Yii::$app->session->setFlash('success', Yii::t('igolf', 'Scores updated.'));
         }
     } else {
         //@todo do not loop on getScorecards twice...
         $scorecards = [];
         foreach ($competition->getRegistrations()->andWhere(['registration.status' => array_merge([Registration::STATUS_CONFIRMED], Registration::getPostCompetitionStatuses())])->each() as $registration) {
             $scorecards[] = $registration->getScorecard();
             // this will create a scorecard if none exists
         }
     }
     return $this->render('competition', ['competition' => $competition, 'dataProvider' => new ActiveDataProvider(['query' => $competition->getScorecards()])]);
 }
Example #2
0
 public static function get($id)
 {
     $query = is_numeric($id) ? ['clientid' => $id] : ['email' => $id];
     $response = self::getWhmcs()->call('getclientsdetails', $query, false);
     \Yii::trace(VarDumper::dumpAsString($response), __METHOD__);
     return \Yii::createObject(self::className(), [$response]);
 }
Example #3
0
 public static function info($message, $category = 'application')
 {
     if (!is_string($message)) {
         $message = VarDumper::dumpAsString($message);
     }
     Yii::info($message, $category);
 }
Example #4
0
 /**
  * @param $exception \Exception
  */
 private function sendErrorMessageToDevelopers($exception)
 {
     $errors = $this->convertExceptionToArray($exception);
     $userIdentity = Yii::$app->getUser()->getIdentity();
     if (!is_null($userIdentity)) {
         $sender = [$userIdentity->getEmail() => $userIdentity->getFullname()];
     } else {
         $sender = ['noreply@' . Yii::$app->getRequest()->getServerName() => 'Web User'];
     }
     $status = S::get($errors, 'status');
     $status = is_null($status) ? S::get($errors, 'code') : $status;
     $subject = '#' . $status . ' ' . S::get($errors, 'name');
     $content = '<h3>' . Yii::$app->name . ' alkalmazásban hiba történt!</h3>';
     $absoluteUrl = Yii::$app->getRequest()->absoluteUrl;
     $content .= '<p><b>URL:</b> ' . $absoluteUrl . '</p>';
     $referrer = Yii::$app->getRequest()->getReferrer();
     $content .= '<p><b>Előző/Hivatkozó oldal:</b> ' . ($referrer !== null ? $referrer : 'direkt link') . '</p>';
     $content .= '<p><b>Fájl:</b> <code>' . $exception->getFile() . '</code></p>';
     $content .= '<p><b>Sor:</b> <code>' . $exception->getLine() . '</code></p>';
     $content .= '<p><b>Hibaüzenet</b> <code>' . $exception->getMessage() . '</code></p>';
     $content .= '<p><b>Részetesen:</b> ' . \yii\helpers\VarDumper::dumpAsString($errors, 10, true) . '</p>';
     $content .= '<p><b>GET paraméterek</b> ' . VarDumper::dumpAsString(Yii::$app->request->get(), 10, true) . '</p>';
     $content .= '<p><b>POST paraméterek</b> ' . VarDumper::dumpAsString(Yii::$app->request->post(), 10, true) . '</p>';
     foreach ($this->emails as $recipient) {
         Mailer::sendMail($recipient, $subject, $content, $sender);
     }
 }
Example #5
0
 /**
  * @inheritdoc
  */
 public function log($level, $message, array $context = [])
 {
     if (count($context)) {
         $message .= PHP_EOL . VarDumper::dumpAsString($context);
     }
     Yii::getLogger()->log($message, $this->levelMap[$level], $this->category);
 }
Example #6
0
 /**
  * @param bool $runValidation
  * @param array|null $attributeNames
  * @return true
  */
 public function tryInsert($runValidation = true, $attributeNames = null)
 {
     if (false === $this->insert($runValidation, $attributeNames)) {
         throw new \LogicException("Saving error: " . VarDumper::dumpAsString($this->getErrors()));
     }
     return true;
 }
Example #7
0
 /**
  * Adds Administrator account.
  * @return string result message.
  */
 protected function _addAdmin()
 {
     try {
         $podium = PodiumModule::getInstance();
         if ($podium->userComponent == PodiumModule::USER_INHERIT) {
             if (!empty($podium->adminId)) {
                 $this->authManager->assign($this->authManager->getRole('podiumAdmin'), $podium->adminId);
                 return $this->outputSuccess(Yii::t('podium/flash', Messages::ADMINISTRATOR_PRIVILEGES_SET, ['id' => $podium->adminId]));
             } else {
                 return $this->outputWarning(Yii::t('podium/flash', Messages::NO_ADMINISTRATOR_PRIVILEGES_SET));
             }
         } else {
             $admin = new User();
             $admin->setScenario('installation');
             $admin->username = self::DEFAULT_USERNAME;
             $admin->email = self::DEFAULT_USER_EMAIL;
             $admin->status = User::STATUS_ACTIVE;
             $admin->role = User::ROLE_ADMIN;
             $admin->generateAuthKey();
             $admin->setPassword(self::DEFAULT_USERNAME);
             if ($admin->save()) {
                 $this->authManager->assign($this->authManager->getRole('podiumAdmin'), $admin->getId());
                 return $this->outputSuccess(Yii::t('podium/flash', Messages::ADMINISTRATOR_ACCOUNT_CREATED) . ' ' . Html::tag('strong', Yii::t('podium/flash', 'Login') . ':') . ' ' . Html::tag('kbd', self::DEFAULT_USERNAME) . ' ' . Html::tag('strong', Yii::t('podium/flash', 'Password') . ':') . ' ' . Html::tag('kbd', self::DEFAULT_USERNAME));
             } else {
                 $this->setError(true);
                 return $this->outputDanger(Yii::t('podium/flash', Messages::ACCOUNT_CREATING_ERROR) . ': ' . Html::tag('pre', VarDumper::dumpAsString($admin->getErrors())));
             }
         }
     } catch (Exception $e) {
         Yii::error([$e->getName(), $e->getMessage()], __METHOD__);
         $this->setError(true);
         return $this->outputDanger(Yii::t('podium/flash', Messages::ACCOUNT_CREATING_ERROR) . ': ' . Html::tag('pre', $e->getMessage()));
     }
 }
 /**
  * Делает рассылку писем из списка рассылки
  */
 public function actionSend()
 {
     $time = microtime(true);
     $list = SubscribeMailItem::query()->limit(10)->orderBy(['date_insert' => SORT_DESC])->all();
     if (count($list) > 0) {
         //            \Yii::info('Всего писем для рассылки: ' . count($list), 'gs\\app\\commands\\SubscribeController::actionSend');
         //            \Yii::info('Список писем: ' . VarDumper::dumpAsString(ArrayHelper::getColumn($list, 'mail')), 'gs\\app\\commands\\SubscribeController::actionSend');
         foreach ($list as $mailItem) {
             $mail = \Yii::$app->mailer->compose()->setFrom(\Yii::$app->params['mailer']['from'])->setTo($mailItem['mail'])->setSubject($mailItem['subject'])->setHtmlBody($mailItem['html']);
             if (isset($mailItem['text'])) {
                 if ($mailItem['text'] != '') {
                     $mail->setTextBody($mailItem['text']);
                 }
             }
             $result = $mail->send();
             if ($result == false) {
                 \Yii::info('Не удалось доствить: ' . VarDumper::dumpAsString($mailItem), 'gs\\app\\commands\\SubscribeController::actionSend');
             }
         }
         //            \Yii::info('Список писем для удаления: ' . VarDumper::dumpAsString(ArrayHelper::getColumn($list, 'id')), 'gs\\app\\commands\\SubscribeController::actionSend');
         SubscribeMailItem::deleteByCondition(['in', 'id', ArrayHelper::getColumn($list, 'id')]);
         //            \Yii::info('Осталось после рассылки: ' . SubscribeMailItem::query()->count(), 'gs\\app\\commands\\SubscribeController::actionSend');
         $time = microtime(true) - $time;
         //            \Yii::info('Затраченное время на расылку: ' . $time, 'gs\\app\\commands\\SubscribeController::actionSend');
     }
     \Yii::$app->end();
 }
 /**
  * @param ActionData $actionData
  *
  * @return void
  */
 public function run(&$actionData)
 {
     $monsterContentConfigs = [];
     foreach ($this->entities as $definition) {
         if (!isset($definition['entity'], $definition['attributes'])) {
             continue;
         }
         $entity = $definition['entity'];
         $definition['attributes'] = (array) $definition['attributes'];
         /** @var yii\base\Model $model */
         $models = ArrayHelper::getValue($actionData->entities, $entity, []);
         $model = is_object($models) ? $models : reset($models);
         if ($model === null) {
             Yii::info("Entities list: " . yii\helpers\VarDumper::dumpAsString($actionData->entities));
             Yii::info((array) ArrayHelper::getValue($actionData->entities, $entity, []));
             Yii::info("Searching for " . $entity);
             throw new \RuntimeException("Model is empty");
         }
         foreach ($definition['attributes'] as $index => $attribute) {
             $materials = $model->{$attribute};
             if (is_array($materials) || is_object($materials)) {
                 $monsterContentConfigs[] = ['materials' => $materials, 'uniqueContentId' => $model::className() . ":{$index}:" . $model->id];
             } else {
                 Yii::warning("Model attribute {$attribute} of entity {$entity} is not array or object");
             }
         }
     }
     $content = '';
     foreach ($monsterContentConfigs as $index => $config) {
         $content .= "<!-- MonsterContent::{$index} -->\n" . MonsterContent::widget($config) . "\n\n";
     }
     $actionData->content = $content;
 }
Example #10
0
 public function call($method, $params = array(), $tag = null)
 {
     $url = sprintf('%s/%s', $this->baseUrl, $this->callUri);
     $postFields = array('username' => $this->username, 'password' => md5($this->password), 'action' => $method, 'responsetype' => 'json');
     if (!empty($this->accesskey)) {
         $postFields['accesskey'] = $this->accesskey;
     }
     if (!empty($params)) {
         $postFields = array_merge($params, $postFields);
     }
     \Yii::trace($url, __METHOD__);
     \Yii::trace(VarDumper::dumpAsString($postFields), __METHOD__);
     $key = null;
     if (\Yii::$app->has('cache') && $tag !== false) {
         \Yii::$app->cache->keyPrefix = 'whmcs_';
         $key = md5(implode(':', [$url, serialize($postFields), $tag]));
         if ($response = \Yii::$app->cache->get($key)) {
             return $response;
         }
     }
     $response = null;
     if (!($response = $this->curl->setOption(CURLOPT_POSTFIELDS, $postFields)->post($url))) {
         throw new InvalidCallException();
     }
     $response = Json::decode($response, false);
     if ($response->result === 'success' && $key) {
         \Yii::$app->cache->set($key, $response, 3600, new TagDependency(['tags' => [$method, $tag]]));
     }
     if ($response->result !== 'success') {
         throw new InvalidCallException($response->message);
     }
     unset($response->result);
     return $response;
 }
 /**
  * Импортирует курсы сразу для всех индексов
  */
 public function actionCandels()
 {
     $rows = Stock::query()->all();
     foreach ($rows as $row) {
         $stock_id = $row['id'];
         $this->log('Попытка получить данные для: ' . $row['name']);
         $importer = ['params' => ['market' => $row['finam_market'], 'em' => $row['finam_em'], 'code' => $row['finam_code']]];
         $class = new \app\service\DadaImporter\Finam($importer);
         $date = new \DateTime();
         $date->sub(new \DateInterval('P7D'));
         $data = $class->importCandels($date->format('Y-m-d'));
         // стратегия: Если данные есть то, они не трогаются
         $dateArray = ArrayHelper::getColumn($data, 'date');
         sort($dateArray);
         $rows2 = StockKurs::query(['between', 'date', $dateArray[0], $dateArray[count($dateArray) - 1]])->andWhere(['stock_id' => $stock_id])->all();
         $dateArrayRows = ArrayHelper::getColumn($rows2, 'date');
         $new = [];
         foreach ($data as $row) {
             if (!in_array($row['date'], $dateArrayRows)) {
                 $new[] = [$stock_id, $row['date'], $row['open'], $row['high'], $row['low'], $row['close'], $row['volume'], $row['close']];
             }
         }
         if (count($new) > 0) {
             \Yii::info('Импортированы данные: ' . VarDumper::dumpAsString($new), 'cap\\importer\\index');
             $this->log('Импортированы данные: ' . VarDumper::dumpAsString($new));
             StockKurs::batchInsert(['stock_id', 'date', 'open', 'high', 'low', 'close', 'volume', 'kurs'], $new);
         } else {
             $this->log('Нечего импортировать');
         }
     }
 }
 public function release($dbConfig = false)
 {
     //		ob_flush();
     //		ob_clean();
     \Yii::trace('application release called.dbConfig=' . VarDumper::dumpAsString($dbConfig), __METHOD__);
     if ($dbConfig) {
         /**
          * 关闭非持久化的数据库连接
          */
         $keys = array_keys($dbConfig);
         if ($keys) {
             foreach ($keys as $item) {
                 $dbObject = \Yii::$app->get($item);
                 if ($dbObject instanceof \yii\db\Connection) {
                     if (!isset($dbObject->attributes[\PDO::ATTR_PERSISTENT])) {
                         if ($dbObject->getIsActive()) {
                             \Yii::trace('db ' . VarDumper::dumpAsString($dbObject) . 'close.', __METHOD__);
                             $dbObject->close();
                         }
                     }
                 }
             }
         }
     }
 }
Example #13
0
 /**
  * Saves file to a random folder
  * @param \stdClass $fileData, example:
  * object(stdClass)[82]
  *   public 'name' => string 'SampleVideo_1080x720_20mb (1).mp4' (length=33)
  *   public 'size' => int 21069678
  *   public 'type' => string 'video/mp4' (length=9)
  *   public 'extension' => string 'mp4' (length=3)
  *
  * @return int File record id
  * @author Alex Makhorin
  */
 public function saveFileToStorage($fileData)
 {
     $tmpFilePath = $this->tmpDirectory . $fileData->name;
     $randomDir = $this->generateRandomDirectory($fileData->name);
     $randomName = $this->generateRandomName();
     $newPath = $this->storageDirectory . $randomDir . '/' . $randomName . '.' . $fileData->extension;
     $this->createFolders($newPath);
     rename($tmpFilePath, $newPath);
     $url = $this->storageUrl . $randomDir . '/' . $randomName . '.' . $fileData->extension;
     if (strpos($fileData->type, 'video/') === 0) {
         $type = FileType::TYPE_VIDEO;
     } elseif (strpos($fileData->type, 'image/') === 0) {
         $type = FileType::TYPE_IMAGE;
     } else {
         is_file($newPath) && unlink($newPath);
         throw new HttpException(400, 'No data to handle');
     }
     $file = new File();
     $file->file_type = $type;
     $file->mime_type = $fileData->type;
     $file->url = $url;
     $isSaved = $file->save();
     if (!$isSaved) {
         throw new HttpException(500, 'DB error occured: ' . \yii\helpers\VarDumper::dumpAsString($file->getErrors()));
     }
     return $file->primaryKey;
 }
 /**
  * 绑定角色与权限的对应关系
  * @param $roleId   角色ID
  * @param $pids 权限ID列表
  * @param $loginUser \liuxy\admin\models\AdminUser
  */
 public static function bind($roleId, $pids, $loginUser)
 {
     self::deteteAll(['role_id' => $roleId]);
     if (!empty($pids)) {
         $pids = explode(',', $pids);
         $pids = array_unique($pids);
         foreach ($pids as $pid) {
             if (!empty($pid)) {
                 $item = new RolePermission();
                 $item->isNewRecord = true;
                 $item->role_id = $roleId;
                 $item->permission_id = $pid;
                 $item->insert_by = $loginUser->username;
                 $item->insert();
                 if ($item->hasErrors()) {
                     Yii::error(VarDumper::dumpAsString($item->getErrors()), __METHOD__);
                 }
                 unset($item);
             }
         }
         /**
          * 清理角色下所对应用户的权限
          */
         foreach (AdminUserRole::find()->where(['role_id' => $roleId])->all() as $userRole) {
             AdminUser::clearPermission($userRole['user_id']);
         }
     }
 }
 public function testApiKey()
 {
     Yii::$app->params['google.api.key'] = 'TEST_API_KEY';
     GooglePlaceSearch::widget(['id' => 'test', 'name' => 'test-widget-name', 'country' => 'au', 'map' => ['selector' => '#map']]);
     $view = Yii::$app->getView();
     $expected = '//maps.googleapis.com/maps/api/js?libraries=places&key=TEST_API_KEY';
     $this->assertContains($expected, VarDumper::dumpAsString($view->assetBundles['webtoolsnz\\widgets\\GooglePlaceSearchAsset']->js));
 }
 /**
  * actionIndex
  *
  * @access public
  * @return void
  */
 public function actionIndex()
 {
     Yii::$app->response->format = Response::FORMAT_JSON;
     if (empty(Yii::$app->request->bodyParams['csp-report'])) {
         return ['status' => 'error'];
     }
     $this->module->composeMessage("csp-report = \n" . VarDumper::dumpAsString(Yii::$app->request->bodyParams['csp-report']) . "\n\$_SERVER = \n" . VarDumper::dumpAsString($_SERVER))->send($this->module->mailer);
     return ['status' => 'ok'];
 }
 public static function cron($isEcho = true)
 {
     $ids = (new Query())->select('parent_id')->from(static::TABLE)->where(['<', 'date_finish', gmdate('YmdHis')])->column();
     if (count($ids) > 0) {
         \Yii::info(\yii\helpers\VarDumper::dumpAsString($ids), 'gs\\app\\services\\RegistrationDispatcher::cron');
         \app\models\User::deleteByCondition(['in', 'id', $ids]);
     }
     parent::cron($isEcho);
 }
Example #18
0
/**
 * Dumps a variable in terms of a string.
 * This method achieves the similar functionality as var_dump and print_r
 * but is more robust when handling complex objects such as Yii controllers.
 * @param mixed $var variable to be dumped
 * @param integer $depth maximum depth that the dumper should go into the variable. Defaults to 10.
 * @param boolean $highlight whether the result should be syntax-highlighted
 * @param bool $return whether the result should be returned (true) or print (false)
 * @return string|null
 */
function dump($var, $depth = 10, $highlight = true, $return = false)
{
    $dump = \yii\helpers\VarDumper::dumpAsString($var, $depth, $highlight);
    if ($return === true) {
        return $dump;
    } else {
        echo $dump;
    }
    return null;
}
 public function actionApi2()
 {
     try {
         $data = $this->_client->api('people/103670338149146743472', 'GET');
     } catch (\Exception $exc) {
         Yii::$app->response->data = $exc->getMessage();
         return Yii::$app->response;
     }
     Yii::$app->response->data = VarDumper::dumpAsString($data, 11, 1);
     return Yii::$app->response;
 }
Example #20
0
 private function parseYiiMessageExt(array $yiiMessage)
 {
     $fullMessage = is_string($yiiMessage[0]) ? $yiiMessage[0] : VarDumper::dumpAsString($yiiMessage[0]);
     if (mb_strlen($fullMessage) > $this->short_message_length) {
         $shortMessage = mb_substr($fullMessage, 0, $this->short_message_length);
     } else {
         $shortMessage = $fullMessage;
         $fullMessage = null;
     }
     return [$shortMessage, $fullMessage];
 }
Example #21
0
 /**
  * var_dump() wrapper with autoexit
  *
  * @param $var
  * @param bool $isExit
  * @param bool $asString
  * @param int $depth
  * @return string
  */
 public static function dump($var, $isExit = true, $asString = false, $depth = 3)
 {
     if ($asString) {
         return VarDumper::dumpAsString($var, $depth, true);
     } else {
         VarDumper::dump($var, $depth, true);
     }
     if ($isExit) {
         exit;
     }
 }
 public function actionApi2()
 {
     try {
         $data = $this->_client->api('wall.get', 'GET', ['owner_id' => '149121205']);
     } catch (\Exception $exc) {
         Yii::$app->response->data = $exc->getMessage();
         return Yii::$app->response;
     }
     Yii::$app->response->data = VarDumper::dumpAsString($data, 11, 1);
     return Yii::$app->response;
 }
 public function actionApi2()
 {
     try {
         $data = $this->_client->api('/v2.3/me');
     } catch (\Exception $exc) {
         Yii::$app->response->data = $exc->getMessage();
         return Yii::$app->response;
     }
     Yii::$app->response->data = VarDumper::dumpAsString($data, 11, 1);
     return Yii::$app->response;
 }
Example #24
0
 /**
  * @param string $shortcut
  * @param string $language
  * @return Template
  */
 public static function findByShortcut($shortcut, $language = null)
 {
     $manager = EmailManager::getInstance();
     foreach ([$language, $manager->defaultLanguage, 'en-US'] as $l) {
         $template = static::findOne(['shortcut' => $shortcut, 'language' => $l]);
         if ($template) {
             return $template;
         }
     }
     throw new \BadMethodCallException('Template not found: ' . VarDumper::dumpAsString($shortcut) . ', language ' . $l);
 }
Example #25
0
 public function parse($str)
 {
     FtpUtils::registerTranslation();
     $protocol = null;
     foreach (FtpProtocol::values() as $current) {
         $regex = '/^' . $current->getProtocol() . ':\\/\\/[^\\/]+$/';
         if (preg_match($regex, strtolower($str))) {
             $str = substr($str, strlen($current->getProtocol()) + 3);
             $protocol = $current;
             break;
         }
     }
     if ($protocol === null) {
         throw new FtpException("Could not find a valid protocol for " . $str);
     }
     // Split connect string using reverse string
     $parts = explode('@', strrev($str), 2);
     // array("<port>:<url>", "<pass>:<user>") or array("<port>:<url>")
     $res = ['class' => $protocol->driver, 'host' => 'localhost', 'port' => $protocol->port, 'user' => 'anonymous', 'pass' => ''];
     if (count($parts) >= 1) {
         $hosts = explode(":", $parts[0], 2);
         // array("<port>", "<url>") or array("<url>")
         if (count($hosts) == 1) {
             $res['host'] = strrev($hosts[0]);
         } else {
             if (count($hosts) == 2) {
                 $res['port'] = strrev($hosts[0]);
                 $res['host'] = strrev($hosts[1]);
             } else {
                 throw new FtpException("Invalid URL / port");
             }
         }
     }
     if (count($parts) == 2) {
         $hosts = explode(":", strrev($parts[1]), 2);
         // array("<user>", "<pass>") or array("<user>")
         if (count($hosts) == 1) {
             $res['user'] = $hosts[0];
         } else {
             if (count($hosts) == 2) {
                 $res['user'] = $hosts[0];
                 $res['pass'] = $hosts[1];
             }
         }
     }
     if (!isset($res['host'])) {
         throw new FtpException("No host found");
     }
     if (isset($res['port']) && !preg_match('/^[0-9]+/', $res['port'])) {
         throw new FtpException("Port is not a number");
     }
     \Yii::trace(\yii\helpers\VarDumper::dumpAsString($res), 'gftp');
     return $res;
 }
Example #26
0
 public function register($attributes)
 {
     $fields = ['vk_id' => $attributes['uid'], 'name_first' => $attributes['first_name'], 'name_last' => $attributes['last_name'], 'gender' => $attributes['sex'] == 0 ? null : ($attributes['sex'] == 1 ? 0 : 1), 'vk_link' => $attributes['screen_name'], 'datetime_reg' => gmdate('YmdHis'), 'datetime_activate' => gmdate('YmdHis'), 'is_active' => 1, 'is_confirm' => 0, 'birth_date' => $this->getBirthDate($attributes)];
     // добавляю поля для подписки
     foreach (\app\services\Subscribe::$userFieldList as $field) {
         $fields[$field] = 1;
     }
     $user = User::insert($fields);
     \Yii::info('$fields: ' . \yii\helpers\VarDumper::dumpAsString($fields), 'gs\\fb_registration');
     $user->setAvatarFromUrl($attributes['photo_200']);
     return $user;
 }
 /**
  * @param array $attributes
  * @throws Exception
  * @return \conquer\oauth2\models\AccessToken
  */
 public static function createAccessToken(array $attributes)
 {
     static::deleteAll(['<', 'expires', time()]);
     $attributes['access_token'] = \Yii::$app->security->generateRandomString(40);
     $accessToken = new static($attributes);
     if ($accessToken->save()) {
         return $accessToken;
     } else {
         \Yii::error(__CLASS__ . ' validation error:' . VarDumper::dumpAsString($accessToken->errors));
     }
     throw new Exception('Unable to create access token', Exception::INTERNAL_ERROR);
 }
Example #28
0
 /**
  * Renvoie une ligne formatée pour les logs.
  * Le paramètre $data accepte plusieurs types. Si c'est un scalaire, la valeur sera rendue telle quelle. Sinon, il sera formatté
  * en fonction de sa classe. Si aucun format n'est explicitement prévu, il sera rendu avec le VarDumper.
  *
  * @param mixed  $data
  * @param string $file
  * @param string $line
  * @param string $method
  * @param string $errNum
  * @return string
  */
 public static function _($data, $file = "", $line = "", $method = "", $errNum = "")
 {
     $out = PHP_EOL;
     if ($errNum) {
         $out .= "-- Erreur #{$errNum} -- ";
     }
     if ($file) {
         $out .= "[{$file}]";
     }
     if ($method) {
         $out .= "[{$method}]";
     }
     if ($line) {
         $out .= "({$line})";
     }
     $out .= PHP_EOL;
     if (is_scalar($data)) {
         // Un scalaire est affiché directement
         $out .= $data;
     } elseif (is_array($data)) {
         if (count($data) && array_key_exists(0, $data) && is_a($data[0], '\\yii\\db\\ActiveRecord')) {
             // Tableau de ActiveRecord : on affiche explicitement les attributs
             $tmp = array();
             foreach ($data as $it) {
                 /** @var \yii\db\ActiveRecord $it */
                 $tmp[] = $it->getAttributes();
             }
             $out .= print_r($tmp, true);
         } else {
             // Tableau normal
             $out .= print_r($data, true);
         }
     } elseif (is_a($data, '\\yii\\db\\Query')) {
         /** @var \yii\db\ActiveQuery $data */
         /** @noinspection PhpUndefinedFieldInspection */
         $out .= $data->sql;
     } elseif (is_a($data, '\\yii\\db\\Command')) {
         /** @var \yii\db\Command $data */
         /** @noinspection PhpUndefinedMethodInspection */
         $out .= $data->getText();
     } elseif (is_a($data, '\\Exception')) {
         /** @noinspection PhpUndefinedMethodInspection */
         $out .= $data->getMessage();
     } elseif (is_a($data, '\\DOMDocument')) {
         /** @noinspection PhpUndefinedMethodInspection */
         $out .= $data->saveXML();
     } else {
         // Dans le doute...
         $out = "**** Classe inconnue : " . get_class($data) . PHP_EOL;
         $out .= VarDumper::dumpAsString($data);
     }
     return $out;
 }
Example #29
0
 /**
  * Displays a single Rule model.
  * @param integer $id
  * @return mixed
  */
 public function actionView($id)
 {
     $model = $this->findModel($id);
     if ($model->load(Yii::$app->request->post()) && $model->save()) {
         return $this->redirect(['view', 'id' => $model->id]);
     } else {
         if (count($model->errors) > 0) {
             Yii::$app->session->setFlash('danger', Yii::t('igolf', 'Error(s): {0}', [VarDumper::dumpAsString($model->errors, 4, true)]));
         }
         return $this->render('view', ['model' => $model]);
     }
 }
 /**
  * 
  * @param array $params
  * @throws Exception
  * @return \conquer\oauth2\models\AuthorizationCode
  */
 public static function createAuthorizationCode(array $params)
 {
     static::deleteAll(['<', 'expires', time()]);
     $params['authorization_code'] = \Yii::$app->security->generateRandomString(40);
     $authCode = new static($params);
     if ($authCode->save()) {
         return $authCode;
     } else {
         \Yii::error(__CLASS__ . ' validation error: ' . VarDumper::dumpAsString($authCode->errors));
     }
     throw new Exception('Unable to create authorization code', Exception::SERVER_ERROR);
 }