public function upload($attribute) { $class = \yii\helpers\StringHelper::basename(get_class($this->owner)) . 'Cutter'; if ($uploadImage = UploadedFile::getInstance($this->owner, $attribute)) { if (!$this->owner->isNewRecord) { $this->delete($attribute); } $cropping = $_POST[$class][$attribute . '-cropping']; $croppingFileName = md5($uploadImage->name . $this->quality . Json::encode($cropping)); $croppingFileExt = strrchr($uploadImage->name, '.'); $croppingFileDir = substr($croppingFileName, 0, 2); $croppingFileBasePath = Yii::getAlias($this->basePath) . $this->baseDir; if (!is_dir($croppingFileBasePath)) { mkdir($croppingFileBasePath, 0755, true); } $croppingFilePath = Yii::getAlias($this->basePath) . $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir; if (!is_dir($croppingFilePath)) { mkdir($croppingFilePath, 0755, true); } $fileSavePath = $croppingFilePath . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; $point = new Point($cropping['dataX'], $cropping['dataY']); $box = new Box($cropping['dataWidth'], $cropping['dataHeight']); $palette = new \Imagine\Image\Palette\RGB(); $color = $palette->color('fff', 0); Image::frame($uploadImage->tempName, 0, 'fff', 0)->rotate($cropping['dataRotate'], $color)->crop($point, $box)->save($fileSavePath, ['quality' => $this->quality]); $this->owner->{$attribute} = $this->baseDir . DIRECTORY_SEPARATOR . $croppingFileDir . DIRECTORY_SEPARATOR . $croppingFileName . $croppingFileExt; } elseif (isset($_POST[$class][$attribute . '-remove']) && $_POST[$class][$attribute . '-remove']) { $this->delete($attribute); } elseif (!empty($_POST[$class][$attribute])) { $this->owner->{$attribute} = $_POST[$class][$attribute]; } elseif (isset($this->owner->oldAttributes[$attribute])) { $this->owner->{$attribute} = $this->owner->oldAttributes[$attribute]; } }
public function getMetaData() { $model = $this->getMetaModel(); $title = $model->title ?: $this->title; $description = $model->description ?: StringHelper::truncate(strip_tags($this->content), 200); return [$title, $description, $model->keywords]; }
public static function bOrderAttr() { if (is_null(static::$b_order_attr)) { static::$b_order_attr = Inflector::camel2id(StringHelper::basename(static::bClass()), '_') . '_ord'; } return static::$b_order_attr; }
/** * Convert display date for saving to model * * @return string JSON encoded HTML output */ public function actionConvert() { $output = ''; Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; $post = Yii::$app->request->post(); if (isset($post['displayDate'])) { $saveFormat = ArrayHelper::getValue($post, 'saveFormat'); $dispFormat = ArrayHelper::getValue($post, 'dispFormat'); $dispTimezone = ArrayHelper::getValue($post, 'dispTimezone'); $saveTimezone = ArrayHelper::getValue($post, 'saveTimezone'); $settings = ArrayHelper::getValue($post, 'settings', []); // Russian dates ends with \r. - i dont know why if (StringHelper::endsWith($dispFormat, '.')) { $dispFormat = substr($dispFormat, 0, strlen($dispFormat) - 4); $post['displayDate'] = substr($post['displayDate'], 0, strlen($post['displayDate']) - 4); } if (ArrayHelper::getValue($post, 'type') != DateControl::FORMAT_DATETIME) { $dispTimezone = null; $saveTimezone = null; } $date = DateControl::getTimestamp($post['displayDate'], $dispFormat, $dispTimezone, $settings); if (empty($date) || !$date) { $value = ''; } elseif ($saveTimezone != null) { $value = $date->setTimezone(new DateTimeZone($saveTimezone))->format($saveFormat); } else { $value = $date->format($saveFormat); } return ['status' => 'success', 'output' => $value]; } else { return ['status' => 'error', 'output' => 'No display date found']; } }
/** * Unlinks two or more models by provided primary key or a list of primary keys. * If the relation type is a many_to_many. related row in the junction table will be deleted. * Otherwise related foreign key will be simply set to NULL. * A '204' response should be set to headers if any change has been made. * @param string $IDs should hold the list of IDs related to the models to be unlinken from the relative one. * it must be a string of the primary keys values separated by commas. * @throws BadRequestHttpException if any of the models are not linked. * @throws InvalidCallException if the models cannot be unlinked */ public function run($IDs) { $relModel = $this->getRelativeModel(); $modelClass = $this->modelClass; $pk = $modelClass::primaryKey()[0]; $getter = 'get' . $this->relationName; $ids = preg_split('/\\s*,\\s*/', $IDs, -1, PREG_SPLIT_NO_EMPTY); $to_unlink = []; foreach ($ids as $pk_value) { $linked = $relModel->{$getter}()->where([$pk => $pk_value])->exists(); if ($linked === true) { $to_unlink[] = $this->findModel($pk_value); } else { throw new BadRequestHttpException(StringHelper::basename($modelClass) . " '{$pk_value}' not linked to " . StringHelper::basename($this->relativeClass) . " '{$this->relative_id}'."); } } $relType = $relModel->getRelation($this->relationName); $delete = $relType->multiple === true && $relType->via !== null; foreach ($to_unlink as $model) { if ($this->checkAccess) { call_user_func($this->checkAccess, $this->id, $model); } $relModel->unlink($this->relationName, $model, $delete); } Yii::$app->getResponse()->setStatusCode(204); }
/** * @inheritdoc */ public static function tableName() { $name = Inflector::camel2id(StringHelper::basename(get_called_class()), '_'); $length = mb_strlen($name, \Yii::$app->charset) - 7; // - mb_strlen('_record', Yii::$app->charset); return '{{%' . trim(mb_substr($name, 0, $length, \Yii::$app->charset)) . '}}'; }
/** * @param DOMElement $element * @param mixed $data */ protected function buildXml($element, $data) { if (is_object($data)) { $child = new DOMElement(StringHelper::basename(get_class($data))); $element->appendChild($child); if ($data instanceof Arrayable) { $this->buildXml($child, $data->toArray()); } else { $array = []; foreach ($data as $name => $value) { $array[$name] = $value; } $this->buildXml($child, $array); } } elseif (is_array($data)) { foreach ($data as $name => $value) { if (is_int($name) && is_object($value)) { $this->buildXml($element, $value); } elseif (is_array($value) || is_object($value)) { $child = new DOMElement(is_int($name) ? $this->itemTag : $name); $element->appendChild($child); $this->buildXml($child, $value); } else { $child = new DOMElement(is_int($name) ? $this->itemTag : $name); $element->appendChild($child); $child->appendChild(new DOMText((string) $value)); } } } else { $element->appendChild(new DOMText((string) $data)); } }
public function testTruncateWords() { $this->assertEquals('это тестовая multibyte строка', StringHelper::truncateWords('это тестовая multibyte строка', 5)); $this->assertEquals('это тестовая multibyte...', StringHelper::truncateWords('это тестовая multibyte строка', 3)); $this->assertEquals('это тестовая multibyte!!!', StringHelper::truncateWords('это тестовая multibyte строка', 3, '!!!')); $this->assertEquals('это строка с неожиданными...', StringHelper::truncateWords('это строка с неожиданными пробелами', 4)); }
/** * @param $path * @param array $dbInfo * @param array $restoreOptions * @return string */ public function makeRestoreCommand($path, array $dbInfo, array $restoreOptions) { $arguments = []; if (StringHelper::endsWith($path, '.gz', false)) { $arguments[] = 'gunzip -c'; $arguments[] = $path; $arguments[] = '|'; } if ($this->isWindows()) { $arguments[] = 'set PGPASSWORD='******'password']; $arguments[] = '&'; } else { $arguments[] = 'PGPASSWORD='******'password']; } // default port if (empty($dbInfo['port'])) { $dbInfo['port'] = '5432'; } $arguments = array_merge($arguments, ['psql', '--host=' . $dbInfo['host'], '--port=' . $dbInfo['port'], '--username='******'username'], '--no-password']); if ($restoreOptions['preset']) { $arguments[] = trim($restoreOptions['presetData']); } $arguments[] = $dbInfo['dbName']; if (!StringHelper::endsWith($path, '.gz', false)) { $arguments[] = '<'; $arguments[] = $path; } return implode(' ', $arguments); }
private function checkForNews() { try { $response = (new Client())->createRequest()->setUrl($this->getCurrentFeed()->url)->send(); if (!$response->isOk) { throw new \Exception(); } $rss = simplexml_load_string($response->getContent()); $newItemsCount = 0; foreach ($rss->channel->item as $item) { if (!NewModel::findOne(['feed' => $this->getCurrentFeed()->id, 'url' => (string) $item->link])) { $new = new NewModel(); $new->feed = $this->getCurrentFeed()->id; $new->published_at = date_create_from_format(\DateTime::RSS, (string) $item->pubDate)->format('Y-m-d H:i:s'); $new->title = (string) $item->title; if (isset($item->description)) { $new->short_text = StringHelper::truncate(strip_tags((string) $item->description), 250); } $new->url = (string) $item->link; if ($new->save()) { $newItemsCount++; } } } if ($newItemsCount > 0) { \Yii::$app->session->addFlash('info', \Yii::t('user', 'Get news: ') . $newItemsCount); $this->clearOldNewsIfNeed(); \Yii::$app->cache->delete($this->getNewsCacheKey()); \Yii::$app->cache->delete($this->getFeedsCacheKey()); } } catch (Exception $e) { \Yii::$app->session->addFlash('danger', \Yii::t('user', 'Get news error')); } }
/** * @inheritDoc */ public function formatConversation($model) { $model = parent::formatConversation($model); $model['date'] = DateHelper::formatConversationDate($model['created_at']); $model['text'] = StringHelper::truncate($model['text'], 20); return $model; }
/** * @param \phpDocumentor\Reflection\BaseReflector $reflector * @param Context $context * @param array $config */ public function __construct($reflector = null, $context = null, $config = []) { parent::__construct($config); if ($reflector === null) { return; } // base properties $this->name = ltrim($reflector->getName(), '\\'); $this->startLine = $reflector->getNode()->getAttribute('startLine'); $this->endLine = $reflector->getNode()->getAttribute('endLine'); $docblock = $reflector->getDocBlock(); if ($docblock !== null) { $this->shortDescription = ucfirst($docblock->getShortDescription()); if (empty($this->shortDescription) && !$this instanceof PropertyDoc && $context !== null && $docblock->getTagsByName('inheritdoc') === null) { $context->errors[] = ['line' => $this->startLine, 'file' => $this->sourceFile, 'message' => "No short description for " . substr(StringHelper::basename(get_class($this)), 0, -3) . " '{$this->name}'"]; } $this->description = $docblock->getLongDescription()->getContents(); $this->phpDocContext = $docblock->getContext(); $this->tags = $docblock->getTags(); foreach ($this->tags as $i => $tag) { if ($tag instanceof SinceTag) { $this->since = $tag->getVersion(); unset($this->tags[$i]); } elseif ($tag instanceof DeprecatedTag) { $this->deprecatedSince = $tag->getVersion(); $this->deprecatedReason = $tag->getDescription(); unset($this->tags[$i]); } } } elseif ($context !== null) { $context->errors[] = ['line' => $this->startLine, 'file' => $this->sourceFile, 'message' => "No docblock for element '{$this->name}'"]; } }
/** * @inheritdoc */ public function getDiff($file = null) { $previewFile = []; $ret = []; $appendFileDiff = function () use(&$previewFile, &$ret) { if (!empty($previewFile)) { $ret[] = new Diff($previewFile); $previewFile = []; } }; $fullDiff = []; if (!is_null($file)) { $fullDiff = $this->repository->getDiff(Repository::DIFF_PATH, $file, $this->id); } else { $fullDiff = $this->repository->getDiff(Repository::DIFF_COMMIT, $this->id); } foreach ($fullDiff as $row) { if (StringHelper::startsWith($row, 'diff')) { // the new file diff, append to $ret $appendFileDiff(); } $previewFile[] = $row; } // append last file diff to full array $appendFileDiff(); return $ret; }
public static function Preview($models) { foreach ($models as $key => $model) { $models[$key]['text'] = StringHelper::truncate(strip_tags($model['text']), 400); } return $models; }
public function testBasename() { $this->assertEquals('', StringHelper::basename('')); $this->assertEquals('file', StringHelper::basename('file')); $this->assertEquals('file.test', StringHelper::basename('file.test', '.test2')); $this->assertEquals('file', StringHelper::basename('file.test', '.test')); $this->assertEquals('file', StringHelper::basename('/file')); $this->assertEquals('file.test', StringHelper::basename('/file.test', '.test2')); $this->assertEquals('file', StringHelper::basename('/file.test', '.test')); $this->assertEquals('file', StringHelper::basename('/path/to/file')); $this->assertEquals('file.test', StringHelper::basename('/path/to/file.test', '.test2')); $this->assertEquals('file', StringHelper::basename('/path/to/file.test', '.test')); $this->assertEquals('file', StringHelper::basename('\\file')); $this->assertEquals('file.test', StringHelper::basename('\\file.test', '.test2')); $this->assertEquals('file', StringHelper::basename('\\file.test', '.test')); $this->assertEquals('file', StringHelper::basename('C:\\file')); $this->assertEquals('file.test', StringHelper::basename('C:\\file.test', '.test2')); $this->assertEquals('file', StringHelper::basename('C:\\file.test', '.test')); $this->assertEquals('file', StringHelper::basename('C:\\path\\to\\file')); $this->assertEquals('file.test', StringHelper::basename('C:\\path\\to\\file.test', '.test2')); $this->assertEquals('file', StringHelper::basename('C:\\path\\to\\file.test', '.test')); // mixed paths $this->assertEquals('file.test', StringHelper::basename('/path\\to/file.test')); $this->assertEquals('file.test', StringHelper::basename('/path/to\\file.test')); $this->assertEquals('file.test', StringHelper::basename('\\path/to\\file.test')); // \ and / in suffix $this->assertEquals('file', StringHelper::basename('/path/to/filete/st', 'te/st')); $this->assertEquals('st', StringHelper::basename('/path/to/filete/st', 'te\\st')); $this->assertEquals('file', StringHelper::basename('/path/to/filete\\st', 'te\\st')); $this->assertEquals('st', StringHelper::basename('/path/to/filete\\st', 'te/st')); // http://www.php.net/manual/en/function.basename.php#72254 $this->assertEquals('foo', StringHelper::basename('/bar/foo/')); $this->assertEquals('foo', StringHelper::basename('\\bar\\foo\\')); }
public function actionIndex() { $actions = []; $rc = new \ReflectionClass($this); $publicMethods = $rc->getMethods(\ReflectionMethod::IS_PUBLIC); $availableActions = []; foreach ($publicMethods as $publicMethod) { $methodName = $publicMethod->name; if ($methodName == 'actions') { continue; } if (StringHelper::startsWith($methodName, 'action')) { $availableActions[] = $methodName; } } if (count($this->actions()) > 0) { $availableActions = $availableActions + array_keys($this->actions()); } $menus = []; foreach ($availableActions as $actionName) { $routeId = Inflector::camel2id(substr($actionName, strlen('action'))); $menus[] = Html::a($actionName, [$routeId]); } echo implode('<br/>', $menus); }
public function rules() { return [[['type_in', 'hdomain_id_in'], 'filter', 'filter' => function ($value) { $res = StringHelper::explode($value, ',', true, true); return $res; }, 'skipOnArray' => true, 'on' => ['export-hosts']], [['type_in'], 'default', 'value' => ['a', 'aaaa'], 'on' => ['export-hosts']], [['type_in'], 'each', 'rule' => ['in', 'range' => array_keys($this->getTypes())], 'on' => ['export-hosts']], [['hdomain_id_in'], 'required', 'on' => ['export-hosts']]]; }
public function init() { if (!$this->modelName) { $this->modelName = StringHelper::basename(get_class($this), 'Controller'); } if (!$this->modelClass) { $modelClass = 'app\\models\\' . $this->modelName; if (class_exists($modelClass)) { $this->modelClass = $modelClass; } else { $modelClass = 'app\\models\\readonly\\' . $this->modelName; if (class_exists($modelClass)) { $this->modelClass = $modelClass; } } } if (!$this->filterModelClass) { $filterModelClass = 'app\\models\\search\\' . $this->modelName . 'Search'; if (class_exists($filterModelClass)) { $this->filterModelClass = $filterModelClass; } else { $filterModelClass = 'app\\models\\readonly\\search\\' . $this->modelName . 'Search'; if (class_exists($filterModelClass)) { $this->filterModelClass = $filterModelClass; } } } parent::init(); }
public static function locationStringToGeometry($location) { if (preg_match('/^(\\-?\\d+(\\.\\d+)?),(\\-?\\d+(\\.\\d+)?)$/', $location, $match)) { $location = \yii\helpers\StringHelper::explode($location, ','); return self::getPostgisFormatByCoordinate($location[0], $location[1]); } return null; }
public function getThumbnailTrue() { if ($this->image) { $name = \yii\helpers\StringHelper::basename($this->image); $dir = \yii\helpers\StringHelper::dirname($this->image); return Yii::getAlias($dir . '/thumb/' . $name); } }
public function run() { $notesDataProvider = new ActiveDataProvider(['query' => $this->model->getNotes(), 'pagination' => ['pageSize' => 3]]); $newModel = new Note(); $newModel->Model_id = $this->model->id; $newModel->Model = StringHelper::basename(get_class($this->model)); echo $this->render('note', ['model' => $newModel, 'dataProvider' => $notesDataProvider, 'accessPriviledge' => $this->accessPriviledge]); }
/** * Generates a class name with camelcase style and specific suffix, if not already provided * * @param string $string The name of the class, e.g.: hello_word would * @param string $suffix The suffix to append on the class name if not eixsts, e.g.: MySuffix * @return string The class name e.g. HelloWorldMySuffix * @since 1.0.0-beta4 */ public function createClassName($string, $suffix = false) { $name = Inflector::camelize($string); if ($suffix && StringHelper::endsWith($name, $suffix, false)) { $name = substr($name, 0, -strlen($suffix)); } return $name . $suffix; }
protected function idAttr() { if (is_null($this->pivotIdAttr)) { $owner = $this->owner; $this->pivotIdAttr = Inflector::camel2id(StringHelper::basename($owner->className()), '_') . '_id'; } return $this->pivotIdAttr; }
public function up() { $this->execute('ALTER TABLE galaxysss_1.gs_unions_office ADD category VARCHAR(100) NULL;'); $path = Yii::getAlias('@app/app/assets/1.xml'); $data = file_get_contents($path); $x = new \DOMDocument(); $x->loadXML($data); $ret = []; /** @var \DOMElement $element */ foreach ($x->documentElement->childNodes as $element) { if ($element instanceof \DOMElement) { $data = $element->getAttribute('data-jmapping'); $pos = Str::pos('lat', $data); $pos1 = Str::pos('lng', $data); $lat = Str::sub($data, $pos + 5, $pos1 - $pos - 7); $pos = Str::pos('lng', $data); $pos1 = Str::pos('category', $data); $lng = Str::sub($data, $pos + 5, $pos1 - $pos - 8); $pos = Str::pos('category', $data); $category = Str::sub($data, $pos + 11); $category = Str::sub($category, 0, Str::length($category) - 2); $category = explode('|', $category); $list = $element->getElementsByTagName("p"); if ($list->length == 1) { /** @var \DOMElement $content */ $content = $list->item(0); $content = $x->saveXML($content); $content = Str::sub($content, 3); $content = Str::sub($content, 0, Str::length($content) - 4); $content = explode('<br/>', $content); $ret2 = []; foreach ($content as $item) { if (StringHelper::startsWith($item, '<b>')) { $item = Str::sub($item, 3); $item = Str::sub($item, 0, Str::length($item) - 4); } $ret2[] = trim($item); } $name = $ret2[0]; array_shift($ret2); if (StringHelper::startsWith($ret2[count($ret2) - 1], 'Открытие')) { $ret2 = array_reverse($ret2); array_shift($ret2); $ret2 = array_reverse($ret2); } if (StringHelper::startsWith($ret2[count($ret2) - 1], '"ВкусВилл')) { $ret2 = array_reverse($ret2); array_shift($ret2); $ret2 = array_reverse($ret2); } $address = $ret2[0]; array_shift($ret2); $ret[] = [392, $address, $name, $lat, $lng, join('|', $category), Html::tag('p', join('<br/>', $ret2))]; } } } $this->batchInsert('gs_unions_office', ['union_id', 'point_address', 'name', 'point_lat', 'point_lng', 'category', 'content'], $ret); }
/** * Builds a normalized cache key from a given key. * * If the given key is a string containing alphanumeric characters only and no more than 32 characters, * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]]. * * @param mixed $key the key to be normalized * @return string the generated cache key */ public function buildKey($key) { if (is_string($key)) { $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key); } else { $key = md5(json_encode($key)); } return $this->keyPrefix . $key; }
/** * @inheritdoc */ public function __construct($params = []) { $classname = \yii\helpers\StringHelper::basename(static::className()); if (!isset($params[$classname])) { $params = [$classname => $params]; } $this->_params = $params; return parent::__construct(); }
/** * @inheritdoc */ public function generate() { $files = []; $modulePath = $this->getModulePath(); $files[] = new CodeFile($modulePath . '/' . StringHelper::basename($this->moduleClass) . '.php', $this->render("module.php")); $files[] = new CodeFile($modulePath . '/controllers/frontend/DefaultController.php', $this->render("controller.php")); $files[] = new CodeFile($modulePath . '/views/frontend/default/index.php', $this->render("view.php")); return $files; }
/** * @return array * 构建登录栏数据 */ private function userInfo() { if (Yii::$app->getUser()->isGuest) { $userInfo = [['label' => '登录', 'url' => $user = Yii::$app->getUser()->loginUrl], ['label' => '注册', 'url' => Yii::$app->params['registerUrl']]]; } else { $userInfo = [['label' => StringHelper::truncate(Yii::$app->user->identity->username, 5), 'active' => false, 'url' => ['/'], 'items' => [['label' => '个人资料', 'url' => '#'], ['label' => '退出', 'url' => ['/signout']]]]]; } return $userInfo; }
public function parseExtraFields($modelName) { if (isset($this->extraFieldModels[StringHelper::basename($modelName::className())])) { $var = $this->extraFieldModels[StringHelper::basename($modelName::className())]; $fieldsArr = $this->{$var}; return array_values(ArrayHelper::map($fieldsArr, 0, 0)); } return []; }
/** * Gets the value of an environment variable. Supports boolean, empty and null. * * @param string $key * @param mixed $default * @return mixed */ function env($key, $default = null) { $value = getenv($key); if ($value === false) { return value($default); } switch (strtolower($value)) { case 'true': case '(true)': return true; case 'false': case '(false)': return false; case 'empty': case '(empty)': return ''; case 'null': case '(null)': return; } if (strlen($value) > 1 && Str::startsWith($value, '"') && Str::endsWith($value, '"')) { return substr($value, 1, -1); } return $value; }