作者:muv
项目:yii2-whmc
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;
}
作者:DevGroup-r
项目:dotplant-monste
/**
* @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;
}
作者:buuug
项目:game403
function myVarDump($param)
{
echo '<pre>';
\yii\helpers\VarDumper::dump($param);
echo '</pre>';
die;
}
作者:CAPITALO
项目:capitalo
/**
* Импортирует курсы сразу для всех индексов
*/
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('Нечего импортировать');
}
}
}
作者:kleit
项目:golfleagu
/**
* 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()])]);
}
作者:keltst
项目:yii2-podiu
/**
* 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()));
}
}
作者:Avenger
项目:yii2-podiu
/**
* Stores log messages to DB.
*/
public function export()
{
$tableName = $this->db->quoteTableName($this->logTable);
$sql = "INSERT INTO {$tableName} ([[level]], [[category]], [[log_time]], [[prefix]], [[message]], [[model]], [[blame]])\n VALUES (:level, :category, :log_time, :prefix, :message, :model, :blame)";
$command = $this->db->createCommand($sql);
foreach ($this->messages as $message) {
list($text, $level, $category, $timestamp) = $message;
$extracted = ['msg' => '', 'model' => null, 'blame' => null];
if (is_array($text) && (isset($text['msg']) || isset($text['model']) || isset($text['blame']))) {
if (isset($text['msg'])) {
if (!is_string($text['msg'])) {
$extracted['msg'] = VarDumper::export($text['msg']);
} else {
$extracted['msg'] = $text['msg'];
}
}
if (isset($text['model'])) {
$extracted['model'] = $text['model'];
}
if (isset($text['blame'])) {
$extracted['blame'] = $text['blame'];
}
} elseif (is_string($text)) {
$extracted['msg'] = $text;
} else {
$extracted['msg'] = VarDumper::export($text);
}
$command->bindValues([':level' => $level, ':category' => $category, ':log_time' => $timestamp, ':prefix' => $this->getMessagePrefix($message), ':message' => $extracted['msg'], ':model' => $extracted['model'], ':blame' => $extracted['blame']])->execute();
}
}
作者:Makeyk
项目:galaxyss
/**
* Делает рассылку писем из списка рассылки
*/
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();
}
作者:DevGroup-r
项目:yii2-extensions-manage
/**
* Writes all configuration to application configuration file
* @return bool result, true if success
*/
public function commit()
{
$data = <<<PHP
<?php
/*
* ! WARNING !
*
* This file is auto-generated.
* Please don't modify it by-hand or all your changes can be lost.
*/
{$this->append}
return
PHP;
$data .= VarDumper::export($this->configuration);
$data .= ";\n\n";
$result = file_put_contents($this->filename, $data, LOCK_EX) !== false;
if ($result) {
if (function_exists('opcache_invalidate')) {
opcache_invalidate($this->filename, true);
}
if (function_exists('apc_delete_file')) {
@apc_delete_file($this->filename);
}
}
return $result;
}
作者:highestgoodlikewate
项目:yii2-liuxy-extensio
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();
}
}
}
}
}
}
}
作者:CDIO
项目:biosaf
public function format($response)
{
$response->getHeaders()->set('Content-Type', 'text/php; charset=UTF-8');
if ($response->data !== null) {
$response->content = "<?php\nreturn " . VarDumper::export($response->data) . ";\n";
}
}
作者:ivan-chk
项目:yii2-boos
/**
* @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);
}
作者:deesof
项目:yii2-consol
/**
* @return array all directories
*/
protected function getDirectories()
{
if ($this->_paths === null) {
$paths = ArrayHelper::getValue(Yii::$app->params, $this->paramVar, []);
$paths = array_merge($paths, $this->migrationLookup);
$extra = !empty($this->extraFile) && is_file($this->extraFile = Yii::getAlias($this->extraFile)) ? require $this->extraFile : [];
$paths = array_merge($extra, $paths);
$p = [];
foreach ($paths as $path) {
$p[Yii::getAlias($path, false)] = true;
}
unset($p[false]);
$currentPath = Yii::getAlias($this->migrationPath);
if (!isset($p[$currentPath])) {
$p[$currentPath] = true;
if (!empty($this->extraFile)) {
$extra[] = $this->migrationPath;
FileHelper::createDirectory(dirname($this->extraFile));
file_put_contents($this->extraFile, "<?php\nreturn " . VarDumper::export($extra) . ";\n", LOCK_EX);
}
}
$this->_paths = array_keys($p);
foreach ($this->migrationNamespaces as $namespace) {
$path = str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace)));
$this->_paths[$namespace] = $path;
}
}
return $this->_paths;
}
作者:yarcod
项目:yii2-bas
/**
* @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;
}
作者:albertborso
项目:yii2-li
/**
* @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);
}
}
作者:piotrmu
项目:Targemati
public function actionCookie()
{
// Yii::$app->response->format = Response::FORMAT_RAW;
// $headers = Yii::$app->response->headers;
// $headers->add('Content-type', 'image/gif');
// $headers->add('Content-Length', '42');
// $headers->add('Cache-Control', 'private, no-cache, no-cache=Set-Cookie, proxy-revalidate');
// $headers->add('Expires', 'Wed, 11 Jan 2000 12:59:00 GMT');
// $headers->add('Last-Modified', 'Wed, 11 Jan 2006 12:59:00 GMT');
// $headers->add('Pragma', 'no-cache');
// echo sprintf('%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%', 71, 73, 70, 56, 57, 97, 1, 0, 1, 0, 128, 255, 0, 192, 192, 192, 0, 0, 0, 33, 249, 4, 1, 0, 0, 0, 0, 44, 0, 0, 0, 0, 1, 0, 1, 0, 0, 2, 2, 68, 1, 0, 59);
$clientCookie = new ClientCookie();
if ($clientCookie->cookie_id === null) {
$cookie = new Cookie();
$cookie->last_activity = $cookie->create_time = date('Y-m-d H:i:s');
$cookie->save();
$clientCookie->cookie_id = $cookie->id;
} else {
$cookie = Cookie::findOne(['id' => $clientCookie->cookie_id]);
if ($cookie !== null) {
$cookie->last_activity = date('Y-m-d H:i:s');
$cookie->save();
}
}
// $clientCookie->updateCategory(3, [
// 'value' => 1
// ]);
$clientCookie->save();
echo "<pre>";
VarDumper::dump($clientCookie);
echo "</pre>";
}
作者:muv
项目:yii2-whmc
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]);
}
作者:vfoko
项目:tims
/**
* 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;
}
作者:highestgoodlikewate
项目:yii2-liuxy-admi
/**
* 绑定角色与权限的对应关系
* @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']);
}
}
}
作者:ivan-chk
项目:yii2-kladovk
public static function info($message, $category = 'application')
{
if (!is_string($message)) {
$message = VarDumper::dumpAsString($message);
}
Yii::info($message, $category);
}