コード例 #1
2
 /**
  * Сгенерировать карту классов для автоподгрузки.
  */
 public function actionGenerate()
 {
     $root = '@app';
     $root = Yii::getAlias($root);
     $root = FileHelper::normalizePath($root);
     $mapFile = '@app/config/classes.php';
     $mapFile = Yii::getAlias($mapFile);
     $options = ['filter' => function ($path) {
         if (is_file($path)) {
             $file = basename($path);
             if ($file[0] < 'A' || $file[0] > 'Z') {
                 return false;
             }
         }
         return;
     }, 'only' => ['*.php'], 'except' => ['/views/', '/vendor/', '/config/', '/tests/']];
     $files = FileHelper::findFiles($root, $options);
     $map = [];
     foreach ($files as $file) {
         if (strpos($file, $root) !== 0) {
             throw new \Exception("Something wrong: {$file}\n");
         }
         $path = str_replace('\\', '/', substr($file, strlen($root)));
         $map['app' . substr(str_replace('/', '\\', $path), 0, -4)] = $file;
     }
     $this->generateMapFile($mapFile, $map);
 }
コード例 #2
1
 public function init()
 {
     $this->css[] = \Yii::$app->settings->get($this->settingsKey, self::SETTINGS_SECTION) . '-' . self::MAIN_LESS_FILE;
     parent::init();
     if (!$this->sourcePath) {
         // TODO: this is workaround for empty source path when using bundled assets
         return;
     } else {
         $sourcePath = \Yii::getAlias($this->sourcePath);
         @mkdir($sourcePath);
         $models = Less::find()->all();
         $hash = sha1(Json::encode($models));
         if ($hash !== \Yii::$app->cache->get(self::CACHE_ID)) {
             $lessFiles = FileHelper::findFiles($sourcePath, ['only' => ['*.less']]);
             foreach ($lessFiles as $file) {
                 unlink($file);
             }
             foreach ($models as $model) {
                 file_put_contents("{$sourcePath}/{$model->key}.less", $model->value);
             }
             $dependency = new FileDependency();
             $dependency->fileName = __FILE__;
             \Yii::$app->cache->set(self::CACHE_ID, $hash, 0, $dependency);
             @touch($sourcePath);
         }
     }
 }
コード例 #3
0
 public function bootstrap($app)
 {
     $configs = $app->cache->get(self::CACHE_CONFIG_ID);
     if ($configs === false) {
         $configs = [];
         foreach ($this->getPaths() as $alias) {
             $path = Yii::getAlias($alias);
             $files = FileHelper::findFiles($path, ['only' => ['*/' . self::DEFINITION_FILE]]);
             foreach ($files as $file) {
                 try {
                     $config = (require $file);
                     $config['basePath'] = dirname($file);
                     $configs[] = $config;
                 } catch (Exception $e) {
                     Yii::trace("Failed loading module config.php file: {$e->getMessage()}", __METHOD__);
                 }
             }
             usort($configs, function ($configA, $configB) {
                 if (isset($configA['weight'], $configB['weight'])) {
                     return (int) $configA['weight'] > (int) $configB['weight'];
                 }
                 return 0;
             });
         }
         if (!YII_DEBUG && !empty($configs)) {
             $app->cache->set(self::CACHE_CONFIG_ID, $configs);
         }
     }
     $app->get('moduleManager')->registerModules($configs);
 }
コード例 #4
0
 public function itemList($options = [])
 {
     $session = Yii::$app->session;
     $moduleId = Yii::$app->controller->module->id;
     if (isset($options['sub-directory'])) {
         $session->set($moduleId, ['path' => '/' . ltrim($options['sub-directory'], '/')]);
     }
     //$session->remove($moduleId);
     $dir = $this->routes->uploadDir . $session->get($moduleId)['path'];
     if (is_dir($dir)) {
         //echo $dir;
         $files = \yii\helpers\FileHelper::findFiles($dir, ['recursive' => false]);
         $files_r = [];
         if (!isset($options['show-directory']) || intval($options['show-directory']) === 1) {
             foreach (glob($dir . '/*', GLOB_ONLYDIR) as $filename) {
                 $files_r[] = $filename;
             }
         }
         foreach ($files as $value) {
             $files_r[] = str_replace('\\', '/', $value);
         }
     } else {
         $message = 'Path ' . $session->get($moduleId)['path'] . ' not found!.';
         $session->remove($moduleId);
         throw new \yii\web\HttpException(500, $message);
     }
     return $files_r;
 }
コード例 #5
0
 public function actionIndex()
 {
     $th = \Yii::$app->thumbnail;
     $rollMenu = (new RollMenu())->items;
     // here comes gallery processing
     $galleryGroup = \Yii::$app->request->get('group', 'all');
     $files = [];
     foreach (glob('img/gallery/*', GLOB_ONLYDIR) as $file) {
         $galleryGroups[] = basename($file);
     }
     if (in_array($galleryGroup, $galleryGroups)) {
         $files = FileHelper::findFiles("img/gallery/{$galleryGroup}");
     } else {
         if ($galleryGroup == 'latest') {
             $files = FileHelper::findFiles("img/gallery");
             $files = array_map("filemtime", $files);
             arsort($files);
         } else {
             $files = FileHelper::findFiles("img/gallery");
         }
     }
     $galleryGroups = array_merge($galleryGroups, ['all', 'latest']);
     $galleryItems = [];
     foreach ($files as $f) {
         $galleryItems[] = ['url' => $f, 'src' => $th->thumbnailFileUrl($f, 200, 200, $th->inset), 'options' => array('title' => \Yii::t('app/images', FilenameHelper::FilenameToTitle($f)))];
     }
     $galleryWidget = ['menu' => $galleryGroups, 'items' => $galleryItems];
     $latestNews = null;
     if (\Yii::$app->request->isAjax) {
         return $this->renderPartial('/templates/image-gallery', ['galleryWidget' => $galleryWidget]);
     }
     return $this->render('index', ['rollMenu' => $rollMenu, 'latestNews' => $latestNews, 'galleryWidget' => $galleryWidget]);
 }
コード例 #6
0
 public static function repairTable($pathDb, $pathDbBak, $mode = 0660, $excludeTables = [])
 {
     $files = FileHelper::findFiles($pathDb, ['only' => ['*.ibd']]);
     $tables = self::getTableNames($files);
     $tables = self::filterTables($tables, $excludeTables);
     \Yii::$app->db->createCommand('set foreign_key_checks=0;')->query();
     self::msg('%b[info]%n Total tables: ' . ($totalTables = count($tables)));
     $i = 0;
     foreach ($tables as $table => $tableFile) {
         self::msg('%b' . ++$i . '[' . $totalTables . '] %y' . strtoupper($table) . '%n');
         try {
             \Yii::$app->db->createCommand('ALTER TABLE ' . $table . ' DISCARD TABLESPACE;')->query();
             self::msg("\tdiscard tablespace");
             $tablePathBak = $pathDbBak . '/' . $table . '.ibd';
             copy($tablePathBak, $tableFile);
             self::msg("\tcopy IBD file");
             chmod($tableFile, $mode);
             self::msg("\tchmod = " . base_convert($mode, 10, 8));
             \Yii::$app->db->createCommand('ALTER TABLE ' . $table . ' IMPORT TABLESPACE;')->query();
             self::msg("\timport tablespace");
             $tableInDb = \Yii::$app->db->createCommand('SHOW CREATE TABLE ' . $table . ';')->queryScalar();
             self::msg("\ttest: " . ($tableInDb === $table ? '%GSUCCESS' : '%RFAIL') . '%n');
         } catch (Exception $e) {
             throw $e;
         }
     }
     \Yii::$app->db->createCommand('set foreign_key_checks=1;')->query();
     self::msg('%b[info]%n Complete!');
 }
コード例 #7
0
ファイル: MessageController.php プロジェクト: freddykr/humhub
 /**
  * Extracts messages for a given module from source code.
  * 
  * @param string $moduleId
  */
 public function actionExtractModule($moduleId)
 {
     $module = Yii::$app->moduleManager->getModule($moduleId);
     $configFile = Yii::getAlias('@humhub/config/i18n.php');
     $config = array_merge(['translator' => 'Yii::t', 'overwrite' => false, 'removeUnused' => false, 'sort' => true, 'format' => 'php', 'ignoreCategories' => []], require $configFile);
     $config['sourcePath'] = $module->getBasePath();
     if (!is_dir($config['sourcePath'] . '/messages')) {
         @mkdir($config['sourcePath'] . '/messages');
     }
     $files = FileHelper::findFiles(realpath($config['sourcePath']), $config);
     $messages = [];
     foreach ($files as $file) {
         $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator'], $config['ignoreCategories']));
     }
     // Remove unrelated translation categories
     foreach ($messages as $category => $msgs) {
         $categoryModule = $this->getModuleByCategory($category);
         if ($categoryModule == null || $categoryModule->id != $module->id) {
             unset($messages[$category]);
         }
     }
     foreach ($config['languages'] as $language) {
         $dir = $config['sourcePath'] . DIRECTORY_SEPARATOR . 'messages' . DIRECTORY_SEPARATOR . $language;
         if (!is_dir($dir)) {
             @mkdir($dir);
         }
         $this->saveMessagesToPHP($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort'], false);
     }
 }
コード例 #8
0
 /**
  * @param string $sourcePath
  * @throws Exception
  */
 public function actionImport($sourcePath = null)
 {
     if (!$sourcePath) {
         $sourcePath = $this->prompt('Enter a source path');
     }
     $sourcePath = realpath(Yii::getAlias($sourcePath));
     if (!is_dir($sourcePath)) {
         throw new Exception('The source path ' . $sourcePath . ' is not a valid directory.');
     }
     $translationsFiles = FileHelper::findFiles($sourcePath, ['only' => ['*.php']]);
     foreach ($translationsFiles as $translationsFile) {
         $relativePath = trim(str_replace([$sourcePath, '.php'], '', $translationsFile), '/,\\');
         $relativePath = FileHelper::normalizePath($relativePath, '/');
         $relativePath = explode('/', $relativePath, 2);
         if (count($relativePath) > 1) {
             $language = $this->prompt('Enter language.', ['default' => $relativePath[0]]);
             $category = $this->prompt('Enter category.', ['default' => $relativePath[1]]);
             $translations = (require_once $translationsFile);
             if (is_array($translations)) {
                 foreach ($translations as $sourceMessage => $translation) {
                     if (!empty($translation)) {
                         $sourceMessage = $this->getSourceMessage($category, $sourceMessage);
                         $this->setTranslation($sourceMessage, $language, $translation);
                     }
                 }
             }
         }
     }
     echo PHP_EOL . 'Done.' . PHP_EOL;
 }
コード例 #9
0
 /**
  * @inheritdoc
  */
 public function run()
 {
     $models = StorageItem::find()->all();
     $results = [];
     if (Yii::$app->controller->module->webAccessUrl === false) {
         foreach ($models as $model) {
             $filePath = Yii::$app->controller->module->getFilePath($model->file_path);
             $url = Url::to(['view', 'id' => $model->id]);
             $fileName = pathinfo($filePath, PATHINFO_FILENAME);
             $results[] = $this->createEntry($filePath, $url, $fileName);
         }
     } else {
         $onlyExtensions = array_map(function ($ext) {
             return '*.' . $ext;
         }, Yii::$app->controller->module->imageAllowedExtensions);
         $filesPath = FileHelper::findFiles(Yii::$app->controller->module->getStorageDir(), ['recursive' => true, 'only' => $onlyExtensions]);
         if (is_array($filesPath) && count($filesPath)) {
             foreach ($filesPath as $filePath) {
                 $url = Yii::$app->controller->module->getUrl(pathinfo($filePath, PATHINFO_BASENAME));
                 $fileName = pathinfo($filePath, PATHINFO_FILENAME);
                 $results[] = $this->createEntry($filePath, $url, $fileName);
             }
         }
     }
     return $results;
 }
コード例 #10
0
ファイル: FixtureManager.php プロジェクト: bariew/yii2-tools
 /**
  * Gets data from cache or database
  * Truncates tables
  * @return \self
  * @throws \yii\db\Exception
  */
 public static function init()
 {
     if ($data = \Yii::$app->cache->get(static::$cacheKey)) {
         //return static::$data = unserialize($data);
     }
     $dir = \Yii::getAlias(static::$fixturePath);
     MigrationHelper::unsetForeignKeyCheck();
     $files = FileHelper::findFiles($dir, ['only' => ['*.php']]);
     asort($files);
     foreach ($files as $file) {
         $table = preg_replace('/\\d+\\_(.*)/', '$1', basename($file, '.php'));
         \Yii::$app->db->createCommand()->truncateTable($table)->execute();
         if (!($data = (require $file))) {
             continue;
         }
         $modelClass = @$data['modelClass'];
         unset($data['modelClass']);
         foreach ($data as $key => $values) {
             \Yii::$app->db->createCommand()->insert($table, $values)->execute();
             if ($modelClass) {
                 /** @var \yii\db\ActiveRecord $model */
                 $model = new $modelClass($values);
                 static::$data[$table][$key] = $model->hasAttribute('id') ? $model::find()->orderBy(['id' => SORT_DESC])->one() : new $model();
             } else {
                 static::$data[$table][$key] = $values;
             }
         }
     }
     static::update();
     MigrationHelper::setForeignKeyCheck();
     return new static();
 }
コード例 #11
0
 /**
  * @param string $name
  * @return boolean
  */
 public function delete($name = '')
 {
     foreach (FileHelper::findFiles($this->getFileName($name)) as $file) {
         unlink($file);
     }
     return rmdir($this->getFileName($name));
 }
コード例 #12
0
ファイル: ImageListModel.php プロジェクト: apurey/cmf
 /**
  * @return string
  */
 public function toJson()
 {
     $toJson = [];
     foreach (FileHelper::findFiles($this->getPath(), ['only' => ['*.jpg', '*.jpe', '*.jpeg', '*.png', '*.gif', '*.bmp']]) as $this->_file) {
         $toJson = ArrayHelper::merge($toJson, [['thumb' => $this->getUrl(), 'image' => $this->getUrl()]]);
     }
     return Json::encode($toJson);
 }
コード例 #13
0
ファイル: FileListModel.php プロジェクト: apurey/cmf
 /**
  * @return string
  */
 public function toJson()
 {
     $toJson = [];
     foreach (FileHelper::findFiles($this->getPath()) as $this->_file) {
         $toJson = ArrayHelper::merge($toJson, [['title' => $this->normalizeFilename(), 'name' => FileHelper::getMimeType($this->_file), 'link' => $this->getUrl(), 'size' => $this->getSize()]]);
     }
     return Json::encode($toJson);
 }
コード例 #14
0
ファイル: Harvester.php プロジェクト: voodoo-mobile/yii2-api
 /**
  * @param Module $module
  *
  * @return array
  */
 public function getControllers($module)
 {
     $files = FileHelper::findFiles($module->controllerPath, ['only' => ['*Controller.php']]);
     return ArrayHelper::getColumn($files, function ($file) use($module) {
         $class = pathinfo($file, PATHINFO_FILENAME);
         $route = Inflector::camel2id($class = substr($class, 0, strlen($class) - strlen('Controller')));
         return new ControllerModel(['route' => $module->uniqueId . '/' . $route, 'label' => Inflector::camel2words($class)]);
     });
 }
コード例 #15
0
ファイル: GuideController.php プロジェクト: dawei101/plants
 /**
  * @inheritdoc
  */
 protected function findFiles($path, $except = [])
 {
     if (empty($except)) {
         $except = ['README.md'];
     }
     $path = FileHelper::normalizePath($path);
     $options = ['only' => ['*.md'], 'except' => $except];
     return FileHelper::findFiles($path, $options);
 }
コード例 #16
0
ファイル: ToolsController.php プロジェクト: psesd/cascade-lib
 /**
  * Fix the code formatting throughout Cascade and its related libraries.
  */
 public function actionFixProject()
 {
     $dirs = [Yii::getAlias('@cascade'), Yii::getAlias('@canis'), Yii::getAlias('@cascade/modules/core'), Yii::getAlias('@psesd/cascade'), Yii::getAlias('@canis/deferred'), Yii::getAlias('@canis/notification')];
     $customStart = microtime(true);
     Console::stdout("Running custom fixes..." . PHP_EOL);
     foreach ($dirs as $dir) {
         $dirStart = microtime(true);
         $changed = 0;
         Console::stdout("\t" . $dir . "...");
         $files = FileHelper::findFiles($dir, ['only' => ['*.php'], 'recursive' => true]);
         Console::stdout("found " . count($files) . " files...");
         foreach ($files as $file) {
             if ($this->fixFile($file)) {
                 $changed++;
             }
         }
         Console::stdout("changed {$changed} files in " . round(microtime(true) - $dirStart, 1) . "s!" . PHP_EOL);
     }
     Console::stdout("done in " . round(microtime(true) - $customStart, 1) . "s!" . PHP_EOL . PHP_EOL);
     $phpcsStart = microtime(true);
     Console::stdout("Running style fixes..." . PHP_EOL);
     foreach ($dirs as $dir) {
         $dirStart = microtime(true);
         $changed = 0;
         Console::stdout("\t" . $dir . "...");
         $configFiles = [];
         $configFiles[] = $dir . DIRECTORY_SEPARATOR . '.php_cs';
         $configFiles[] = dirname($dir) . DIRECTORY_SEPARATOR . '.php_cs';
         $configFiles[] = dirname(dirname($dir)) . DIRECTORY_SEPARATOR . '.php_cs';
         $foundConfig = false;
         foreach ($configFiles as $configFile) {
             if (file_exists($configFile)) {
                 $foundConfig = $configFile;
                 break;
             }
         }
         if (!$foundConfig) {
             Console::stdout("skipped!" . PHP_EOL);
             continue;
         }
         $phpcsBinary = Yii::getAlias('@vendor/bin/php-cs-fixer');
         if (!file_exists($phpcsBinary)) {
             Console::stdout("no php-cs-fixer binary!" . PHP_EOL);
             continue;
         }
         $command = [];
         $command[] = PHP_BINARY;
         $command[] = $phpcsBinary;
         $command[] = '--no-interaction';
         $command[] = '--config-file=' . $foundConfig;
         // $command[] = '--quiet';
         $command[] = 'fix';
         exec(implode(' ', $command), $output, $exitCode);
         Console::stdout("done in " . round(microtime(true) - $dirStart, 1) . "s!" . PHP_EOL);
     }
     Console::stdout("done in " . round(microtime(true) - $phpcsStart, 1) . "s!" . PHP_EOL . PHP_EOL);
 }
コード例 #17
0
ファイル: ProviderTrait.php プロジェクト: unyii2/yii2-giiant
 /**
  * @return array Class names of the providers declared directly under crud/providers folder
  */
 public static function getCoreProviders()
 {
     $files = FileHelper::findFiles(__DIR__ . DIRECTORY_SEPARATOR . 'providers/core', ['only' => ['*.php'], 'recursive' => false]);
     foreach ($files as $file) {
         require_once $file;
     }
     return array_filter(get_declared_classes(), function ($a) {
         return stripos($a, __NAMESPACE__ . '\\providers') !== false;
     });
 }
コード例 #18
0
 /**
  * Adds one or more directories with controllers to context.
  *
  * @param string[] $dirs
  */
 public function addDirs($dirs)
 {
     $dirs = is_array($dirs) ? $dirs : [$dirs];
     foreach ($dirs as $dir) {
         $files = FileHelper::findFiles(Yii::getAlias($dir), ['only' => ['*Controller.php']]);
         foreach ($files as $file) {
             $this->addFile($file);
         }
     }
 }
コード例 #19
0
 public function actionIndex()
 {
     foreach (FileHelper::findFiles($this->module->getControllerPath()) as $file) {
         $id = lcfirst(substr(basename($file), 0, -14));
         $name = Inflector::camel2words($id);
         $route = ['/' . $this->module->id . '/' . Inflector::camel2id($name)];
         $controllers[$name] = $route;
     }
     return $this->render('index', ['controllers' => $controllers]);
 }
コード例 #20
0
ファイル: Profile.php プロジェクト: andasoft/yii2-core
 public function covers()
 {
     $cover_dir = Yii::getAlias('@webroot/uploads/user/') . $this->user_id . '/cover';
     $files = \yii\helpers\FileHelper::findFiles($cover_dir, ['recursive' => false, 'only' => ['*.jpg', '*.png']]);
     $file_url = [];
     foreach ($files as $key => $file) {
         $file_url[] = str_replace(Yii::getAlias('@webroot/'), '', $file);
     }
     return $file_url;
 }
コード例 #21
0
ファイル: Avatar.php プロジェクト: bubasuma/yii2-simplechat
 public function avatar()
 {
     $path = __DIR__ . '/../../../../assets/img/avatars';
     if (null === $this->_container) {
         $this->_container = array_map(function ($file) {
             return basename($file);
         }, FileHelper::findFiles($path));
     }
     return $this->generator->randomElement($this->_container);
 }
コード例 #22
0
 public function actionDeleteTemp($filename)
 {
     $userTempDir = $this->getModule()->getUserDirPath();
     $filePath = $userTempDir . DIRECTORY_SEPARATOR . $filename;
     unlink($filePath);
     if (!sizeof(FileHelper::findFiles($userTempDir))) {
         rmdir($userTempDir);
     }
     Yii::$app->response->format = Response::FORMAT_JSON;
     return [];
 }
コード例 #23
0
 public static function getBlockList()
 {
     $dir = Yii::getAlias(self::BLOCKS_DIR);
     $files = FileHelper::findFiles($dir, ['only' => ['*.php']]);
     $a = [];
     foreach ($files as $f) {
         $blockName = str_replace('.php', '', pathinfo($f, PATHINFO_BASENAME));
         $a[] = ['id' => $blockName];
     }
     return $a;
 }
コード例 #24
0
 /**
  * @hass-todo
  */
 public function actionIndex()
 {
     $namespaces = \HassClassLoader::getHassCoreFile();
     $result = [];
     foreach ($namespaces as $namespace => $dir) {
         $controllerDir = $dir . DIRECTORY_SEPARATOR . "controllers";
         if (!is_dir($controllerDir)) {
             continue;
         }
         $files = FileHelper::findFiles($controllerDir);
         $moduleId = trim(substr($namespace, strrpos(rtrim($namespace, "\\"), "\\")), "\\");
         $result[$moduleId]["module"] = $moduleId;
         $result[$moduleId]["permissions"] = [];
         foreach ($files as $file) {
             $childDir = rtrim(pathinfo(substr($file, strpos($file, "controllers") + 12), PATHINFO_DIRNAME), ".");
             if ($childDir) {
                 $class = $namespace . "controllers\\" . str_replace("/", "\\", $childDir) . "\\" . rtrim(basename($file), ".php");
             } else {
                 $class = $namespace . "controllers\\" . rtrim(basename($file), ".php");
             }
             $controllerId = Inflector::camel2id(str_replace("Controller", "", pathinfo($file, PATHINFO_FILENAME)));
             $reflect = new \ReflectionClass($class);
             $methods = $reflect->getMethods(\ReflectionMethod::IS_PUBLIC);
             /** @var \ReflectionMethod $method */
             foreach ($methods as $method) {
                 if (!StringHelper::startsWith($method->name, "action")) {
                     continue;
                 }
                 if ($method->name == "actions") {
                     $object = \Yii::createObject(["class" => $class], [$controllerId, $moduleId]);
                     $actions = $method->invoke($object);
                     foreach ($actions as $actionId => $config) {
                         $route = $moduleId . "/" . $controllerId . "/" . $actionId;
                         if ($childDir) {
                             $route = $moduleId . "/" . $childDir . "/" . $controllerId . "/" . $actionId;
                         }
                         $result[$moduleId]["permissions"][$route] = ["type" => Item::TYPE_PERMISSION, "description" => $controllerId . "-" . Inflector::camel2words($actionId)];
                     }
                     continue;
                 }
                 $actionId = Inflector::camel2id(substr($method->name, 6));
                 $route = $moduleId . "/" . $controllerId . "/" . $actionId;
                 if ($childDir) {
                     $route = $moduleId . "/" . $childDir . "/" . $controllerId . "/" . $actionId;
                 }
                 $result[$moduleId]["permissions"][$route] = ["type" => Item::TYPE_PERMISSION, "description" => $controllerId . "-" . Inflector::camel2words(substr($method->name, 6))];
             }
         }
     }
     $result["super"] = ['module' => 'SUPER_PERMISSION', 'permissions' => array(\hass\rbac\Module::SUPER_PERMISSION => array('type' => Item::TYPE_PERMISSION, 'description' => 'SUPER_PERMISSION'))];
     $result = "<?php \n return " . var_export($result, true) . ";";
     file_put_contents(dirname(__DIR__) . "/permissions.php", $result);
     return $this->render("index");
 }
コード例 #25
0
 /**
  * Adds sphinx extension files to [[Yii::$classPath]],
  * avoiding the necessity of usage Composer autoloader.
  */
 protected static function loadClassMap()
 {
     $baseNameSpace = 'yii/sphinx';
     $basePath = realpath(__DIR__ . '/../../../../extensions/sphinx');
     $files = FileHelper::findFiles($basePath);
     foreach ($files as $file) {
         $classRelativePath = str_replace($basePath, '', $file);
         $classFullName = str_replace(['/', '.php'], ['\\', ''], $baseNameSpace . $classRelativePath);
         Yii::$classMap[$classFullName] = $file;
     }
 }
コード例 #26
0
 /**
  * Extracts messages to be translated from source code.
  *
  * This command will search through source code files and extract
  * messages that need to be translated in different languages.
  *
  * @param string $configFile the path or alias of the configuration file.
  * You may use the "yii message/config" command to generate
  * this file and then customize it for your needs.
  * @throws Exception on failure.
  */
 public function actionGoogleExtract($configFile = null)
 {
     $configFile = Yii::getAlias($configFile ?: $this->configFile);
     if (!is_file($configFile)) {
         throw new Exception("The configuration file does not exist: {$configFile}");
     }
     $config = array_merge(['translator' => 'Yii::t', 'overwrite' => false, 'removeUnused' => false, 'sort' => false, 'format' => 'php'], require_once $configFile);
     if (!isset($config['sourcePath'], $config['languages'])) {
         throw new Exception('The configuration file must specify "sourcePath" and "languages".');
     }
     if (!is_dir($config['sourcePath'])) {
         throw new Exception("The source path {$config['sourcePath']} is not a valid directory.");
     }
     if (empty($config['format']) || !in_array($config['format'], ['php', 'po', 'db'], true)) {
         throw new Exception('Format should be either "php", "po" or "db".');
     }
     if (in_array($config['format'], ['php', 'po'], true)) {
         if (!isset($config['messagePath'])) {
             throw new Exception('The configuration file must specify "messagePath".');
         } elseif (!is_dir($config['messagePath'])) {
             throw new Exception("The message path {$config['messagePath']} is not a valid directory.");
         }
     }
     if (empty($config['languages'])) {
         throw new Exception('Languages cannot be empty.');
     }
     $files = FileHelper::findFiles(realpath($config['sourcePath']), $config);
     $messages = [];
     foreach ($files as $file) {
         $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator']));
     }
     if (in_array($config['format'], ['php', 'po'], true)) {
         foreach ($config['languages'] as $language) {
             $dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language;
             if (!is_dir($dir)) {
                 @mkdir($dir);
             }
             if ($config['format'] === 'po') {
                 $catalog = isset($config['catalog']) ? $config['catalog'] : 'messages';
                 $this->saveMessagesToPO($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort'], $catalog);
             } else {
                 $this->saveMessagesToPHPEnhanced($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort'], $language);
             }
         }
     } elseif ($config['format'] === 'db') {
         $db = \Yii::$app->get(isset($config['db']) ? $config['db'] : 'db');
         if (!$db instanceof \yii\db\Connection) {
             throw new Exception('The "db" option must refer to a valid database application component.');
         }
         $sourceMessageTable = isset($config['sourceMessageTable']) ? $config['sourceMessageTable'] : '{{%source_message}}';
         $messageTable = isset($config['messageTable']) ? $config['messageTable'] : '{{%message}}';
         $this->saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $config['removeUnused'], $config['languages']);
     }
 }
コード例 #27
0
 protected function findWidgets()
 {
     $widgets = [];
     $path = Yii::getAlias('@worstinme/zoo/widgets/models/');
     $widgetModels = \yii\helpers\FileHelper::findFiles($path);
     foreach ($widgetModels as $key => $model) {
         $model = str_replace($path, '', rtrim($model, ".php"));
         $widgets[$model] = "worstinme\\zoo\\widgets\\models\\" . $model;
     }
     return $widgets;
 }
コード例 #28
0
ファイル: ClassmapController.php プロジェクト: aivavic/yii2
    /**
     * Creates a class map for the core Yii classes.
     * @param string $root    the root path of Yii framework. Defaults to YII2_PATH.
     * @param string $mapFile the file to contain the class map. Defaults to YII2_PATH . '/classes.php'.
     */
    public function actionCreate($root = null, $mapFile = null)
    {
        if ($root === null) {
            $root = YII2_PATH;
        }
        $root = FileHelper::normalizePath($root);
        if ($mapFile === null) {
            $mapFile = YII2_PATH . '/classes.php';
        }
        $options = ['filter' => function ($path) {
            if (is_file($path)) {
                $file = basename($path);
                if ($file[0] < 'A' || $file[0] > 'Z') {
                    return false;
                }
            }
            return null;
        }, 'only' => ['*.php'], 'except' => ['/Yii.php', '/BaseYii.php', '/console/']];
        $files = FileHelper::findFiles($root, $options);
        $map = [];
        foreach ($files as $file) {
            if (strpos($file, $root) !== 0) {
                throw new Exception("Something wrong: {$file}\n");
            }
            $path = str_replace('\\', '/', substr($file, strlen($root)));
            $map[$path] = "  'yii" . substr(str_replace('/', '\\', $path), 0, -4) . "' => YII2_PATH . '{$path}',";
        }
        ksort($map);
        $map = implode("\n", $map);
        $output = <<<EOD
<?php
/**
 * Yii core class map.
 *
 * This file is automatically generated by the "build classmap" command under the "build" folder.
 * Do not modify it directly.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

return [
{$map}
];

EOD;
        if (is_file($mapFile) && file_get_contents($mapFile) === $output) {
            echo "Nothing changed.\n";
        } else {
            file_put_contents($mapFile, $output);
            echo "Class map saved in {$mapFile}\n";
        }
    }
コード例 #29
0
 /**
  * Deletes all of thumbnails of the image
  *
  * @return bool
  */
 public function clear()
 {
     list($path, $basename) = $this->pathComponents();
     if (file_exists($path)) {
         $files = FileHelper::findFiles($path, ['only' => [$basename . '-*']]);
         foreach ($files as $file) {
             unlink($file);
         }
     }
     return true;
 }
コード例 #30
0
 public function run1($table, $id)
 {
     $filesPath = FileHelper::findFiles(Yii::$app->controller->module->getSaveDir(), ['recursive' => true, 'only' => $onlyExtensions]);
     if (is_array($filesPath) && count($filesPath)) {
         $result = [];
         foreach ($filesPath as $filePath) {
             $url = Yii::$app->controller->module->getUrl(pathinfo($filePath, PATHINFO_BASENAME));
             $result[] = ['thumb' => $url, 'image' => $url, 'title' => pathinfo($filePath, PATHINFO_FILENAME)];
         }
         return $result;
     }
 }