处理配置文件路由
@return void
514591
private function parseConfigs(EventParam $e)
    {
        foreach(ServerManage::getServers() as $name => $server)
        {
            if(!$server instanceof \Imi\Server\UdpServer\Server)
            {
                continue;
            }
            $route = $server->getBean('UdpRoute');
            foreach(Helper::getMain($server->getConfig()['namespace'])->getConfig()['route'] ?? [] as $url => $routeOption)
            {
                $routeAnnotation = new UdpRoute($routeOption['route'] ?? []);
                if(isset($routeOption['callback']))
                {
                    $callable = $routeOption['callback'];
                }
                else
                {
                    $callable = new RouteCallable($routeOption['controller'], $routeOption['method']);
                }
                $route->addRuleAnnotation($routeAnnotation, $callable, [
                    'middlewares' => $routeOption['middlewares'],
                ]);
            }
        }
    }
1156491
public function validate() {
        if ($this->file->validate() === false) {
            $this->errors = $this->file->getErrors();
            return false;
        }

        return true;
    }
166704
public function findFiles()
    {
        $files = $this->getFilesystemDisk()->listContents($this->getFilesPath());
        foreach ($files as $fileData) {
            $this->addNewFileFromArray($fileData);
        }
    }
595064
protected function doExecute()
    {
        $root = $this->io->getArgument(0, WINDWALKER_ROOT . '/src');

        $dirs = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root));

        $count = 0;

        foreach ($dirs as $file) {
            /** @var $file \SplFileInfo */
            if (!$file->isFile() || $file->getExtension() != 'php') {
                continue;
            }

            $content = file_get_contents($file);

            $length = strlen($content);

            $lastChar = $content[$length - 1];

            if ($lastChar == "\n") {
                continue;
            }

            $count++;

            $this->out('Add new line to: ' . $file);

            switch ($lastChar) {
                case ' ' :
                    $content = substr($content, 0, -1);
                    break;

                case '}' :
                    $content .= "\n";
                    break;
            }

            file_put_contents($file, $content);
        }

        if ($count) {
            $this->out($count . ' files add new line.');
        } else {
            $this->out('No file found.');
        }
    }
19640
public function uploadToContentService() {
		/** @var \File $file */
		$file = $this->owner;
		$writer = $this->writer();
		if (!$writer) {
			return;
		}
		$path = $file->getFullPath();
		if (strlen($path) && is_file($path) && file_exists($path)) {

			$mtime = @filemtime($path);
            $name = trim($file->getFilename(), '/');
		if (!$mtime) {
                    $mtime = '0';
                }

			//Insert the file modified time to make file unique-ish
			if ($lastPos = strrpos($name, '/')) {
				// Add in at as last folder name
				$name = substr($name, 0, $lastPos) . '/' . $mtime . substr($name, $lastPos);
			} else {
				//No folder found create one for the mtime
				$name = $mtime . '/' . $name;
			}

			$fileKeyLength = strlen($name);
			if ($fileKeyLength > CDNFile::MAX_FILE_PATH_LENGTH) {
				$lastPos = strrpos($name, '/');
				$ext = '';
				$filename = substr($name, $lastPos + 1);
				// Try and find a file extension
				if (strrpos($name, '.') !== false) {
					// Store and trim extension for later replacement
					$ext = substr($name, strrpos($name, '.'));
					$filename = substr($filename, 0, strrpos($filename, '.'));
				}
				// add 1 here so we can add in a ~ to indictate truncation
				$truncateLength = ($fileKeyLength + strlen($ext) + 1) - CDNFile::MAX_FILE_PATH_LENGTH;
				if (strlen($filename) <= $truncateLength) {
					// Folder length exceeds CDNFile::MAX_FILE_PATH_LENGTH. MD5 file to prevent file loss log error
					SS_Log::log("CDNFile: Total file length (folders + name) exceeds " . CDNFile::MAX_FILE_PATH_LENGTH . " characters and can't be "
							. "trimmed. File key has been MD5 encoded. File key: " . md5($name) . $ext . " Filename: "
							. "$name", SS_Log::ERR);
					$name = md5($name) . $ext;
				} else {
					// Recombine folder and file name while truncating the filename and appending a ~ then extension
					$name = substr($name, 0, $lastPos) . '/' . substr($filename, 0, (0 - $truncateLength)) . '~' . $ext;
				}
			}


			$writer->write(fopen($path, 'r'), $name);

			// writer should now have an id
			$file->CDNFile = $writer->getContentId();
            $file->FileSize = @filesize($path);

            // check whether it's an image, and handle its dimensions
            if ($file instanceof CdnImage) {
                $file->storeDimensions();
            }

			$file->write();

            // confirm the remote upload is there, and delete the local file
            // Oct 2016 - UNLESS the versioned files extension is on, we have to treat it slightly different
            $this->deleteLocalIfExistsOnContentService();
		}
	}
675387
public function execute()
    {
        $this->phpci->quiet = true;
        $this->phpci->logExecOutput(false);

        foreach ($this->directories as $dir) {
            $this->lintDirectory($dir);
        }

        $this->phpci->quiet = false;
        $this->phpci->logExecOutput(true);

        $errors = 0;
        $warnings = 0;

        foreach ($this->failedPaths as $path) {
            if ($path['type'] == 'error') {
                $errors++;
            } else {
                $warnings++;
            }
        }

        $this->build->storeMeta('phptallint-warnings', $warnings);
        $this->build->storeMeta('phptallint-errors', $errors);
        $this->build->storeMeta('phptallint-data', $this->failedPaths);

        $success = true;

        if ($this->allowed_warnings != -1 && $warnings > $this->allowed_warnings) {
            $success = false;
        }

        if ($this->allowed_errors != -1 && $errors > $this->allowed_errors) {
            $success = false;
        }

        return $success;
    }
839334
private function saveFile(): void
    {
        $sourceCode = Helpers::tabsToSpaces((string) $this->DTOFile);

        $fullPath = implode('/', [
            dirname(__DIR__, 7) . '/src',
            $this->inputData['namespace'],
            $this->inputData['module'] . 'Module',
            $this->inputData['type'],
            $this->inputData['class'] . $this->inputData['type'] . '.php'
        ]);

        $dirname = dirname($fullPath);

        if (!is_dir($dirname)) {
            mkdir($dirname, 0755, true);
        }

        $handle = fopen($fullPath, 'w');
        fwrite($handle, $sourceCode);
        fclose($handle);
    }
1353187
private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
            $arr = explode(yii::getAlias("@frontend/web"), $this->filePath);
            yii::$app->alioss->uploadFile($arr[1], $this->filePath);
            yii::$app->qiniu->uploadFile($arr[1], $this->filePath);
        }
    }
631231
public function save()
    {
        $results
            = "<?php \n return " . var_export(self::getResults(), true) . ";";
        file_put_contents($this->file, $results);
    }
1207776
public function save()
    {
        if ($this->validate() && $this->file instanceof UploadedFile) {
            try {
                if (($uploader = $this->file->save()) != false) {
                    $this->file = $uploader->getUrl();
                    return true;
                } else {
                    $this->addError('file', Yii::t('yuncms', 'Audio file storage failed.'));
                }
            } catch (FileExistsException $e) {
                $this->addError('file', $e->getMessage());
            } catch (ErrorException $e) {
                $this->addError('file', $e->getMessage());
            } catch (InvalidConfigException $e) {
                $this->addError('file', $e->getMessage());
            }
        }
        return false;
    }
567414
public function fileManager()
    {
        $files = [
            base_path('config/auth.php'),
            base_path('config/services.php'),
        ];

        foreach ($files as $file) {
            $contents = file_get_contents($file);
            $contents = str_replace('App\User::class', 'App\Models\User::class', $contents);
            file_put_contents($file, $contents);
        }

        // Route setup
        $routeContents = file_get_contents(app_path('Providers/RouteServiceProvider.php'));
        $routeContents = str_replace("->group(base_path('routes/web.php'));", "->group(function() { \n\t\t\trequire base_path('routes/web.php');\n\t\t\trequire base_path('routes/cms.php'); });", $routeContents);
        file_put_contents(app_path('Providers/RouteServiceProvider.php'), $routeContents);

        $routeToDashboardContents = file_get_contents(base_path('routes/web.php'));
        $routeToDashboardContents = str_replace("Route::get('/dashboard', 'PagesController@dashboard');", "Route::get('/dashboard', function(){ return Redirect::to('cms/dashboard'); });", $routeToDashboardContents);
        file_put_contents(base_path('routes/web.php'), $routeToDashboardContents);

        // Kernel setup
        $routeContents = file_get_contents(app_path('Http/Kernel.php'));
        $routeContents = str_replace("'auth' => \App\Http\Middleware\Authenticate::class,", "'auth' => \App\Http\Middleware\Authenticate::class,\n\t\t'cms' => \App\Http\Middleware\GrafiteCms::class,\n\t\t'cms-api' => \App\Http\Middleware\GrafiteCmsApi::class,\n\t\t'cms-analytics' => \Grafite\Cms\Middleware\GrafiteCmsAnalytics::class,\n\t\t'cms-language' => \App\Http\Middleware\GrafiteCmsLanguage::class,\n\t\t'admin' => \App\Http\Middleware\Admin::class,\n\t\t'active' => \App\Http\Middleware\Active::class,", $routeContents);
        file_put_contents(app_path('Http/Kernel.php'), $routeContents);

        $fileSystem = new Filesystem();

        $files = $fileSystem->allFiles(__DIR__.'/../PublishedAssets/Setup');

        foreach ($files as $file) {
            $newFileName = str_replace(__DIR__.'/../PublishedAssets/Setup', '', $file);
            if (is_dir($file)) {
                $fileSystem->copyDirectory($file, base_path($newFileName));
            } else {
                @mkdir(base_path(str_replace(basename($newFileName), '', $newFileName)), 0755, true);
                $fileSystem->copy($file, base_path($newFileName));
            }
        }

        // AuthProviders
        $authProviderContents = file_get_contents(app_path('Providers/AuthServiceProvider.php'));
        $authProviderContents = str_replace('$this->registerPolicies();', "\$this->registerPolicies();\n\t\t\Gate::define('cms', function (\$user) {\n\t\t\treturn (\$user->roles->first()->name === 'admin');\n\t\t});\n\t\t\Gate::define('admin', function (\$user) {\n\t\t\treturn (\$user->roles->first()->name === 'admin');\n\t\t});", $authProviderContents);
        file_put_contents(app_path('Providers/AuthServiceProvider.php'), $authProviderContents);

        // Remove the teams
        $this->dropDeadFiles();

        /*
         * --------------------------------------------------------------------------
         * Drop the team routes and the active middleware
         * --------------------------------------------------------------------------
        */

        $mainRoutes = file_get_contents(base_path('routes/web.php'));
        $mainRoutes = str_replace("/*
    |--------------------------------------------------------------------------
    | Team Routes
    |--------------------------------------------------------------------------
    */

    Route::get('team/{name}', 'TeamController@showByName');
    Route::resource('teams', 'TeamController', ['except' => ['show']]);
    Route::post('teams/search', 'TeamController@search');
    Route::post('teams/{id}/invite', 'TeamController@inviteMember');
    Route::get('teams/{id}/remove/{userId}', 'TeamController@removeMember');", '', $mainRoutes);
        $mainRoutes = str_replace("['auth', 'active']", "['auth']", $mainRoutes);
        file_put_contents(base_path('routes/web.php'), $mainRoutes);

        /*
         * --------------------------------------------------------------------------
         * Drop the activate by email notification
         * --------------------------------------------------------------------------
        */

        $activateUserEmail = file_get_contents(app_path('Notifications/ActivateUserEmail.php'));
        $activateUserEmail = str_replace("'mail'", '', $activateUserEmail);
        file_put_contents(app_path('Notifications/ActivateUserEmail.php'), $activateUserEmail);

        /*
         * --------------------------------------------------------------------------
         * Clean up the user model
         * --------------------------------------------------------------------------
        */

        $userModel = file_get_contents(app_path('Models/User.php'));
        $userModel = str_replace("/**
 * Teams
 *
 * @return Relationship
 */
public function teams()
{
    return \$this->belongsToMany(Team::class);
}

/**
 * Team member
 *
 * @return boolean
 */
public function isTeamMember(\$id)
{
    \$teams = array_column(\$this->teams->toArray(), 'id');
    return array_search(\$id, \$teams) > -1;
}

/**
 * Team admin
 *
 * @return boolean
 */
public function isTeamAdmin(\$id)
{
    \$team = \$this->teams->find(\$id);
    return (int)\$team->user_id === (int)\$this->id;
}", '', $userModel);
        $userModel = str_replace("use App\Models\Team;", '', $userModel);
        file_put_contents(app_path('Models/User.php'), $userModel);

        $userService = file_get_contents(app_path('Services/UserService.php'));
        $userService = str_replace('/*
|--------------------------------------------------------------------------
| Teams
|--------------------------------------------------------------------------
*/

public function joinTeam($teamId, $userId)
{
    $team = $this->team->find($teamId);
    $user = $this->model->find($userId);

    $user->teams()->attach($team);
}

public function leaveTeam($teamId, $userId)
{
    $team = $this->team->find($teamId);
    $user = $this->model->find($userId);

    $user->teams()->detach($team);
}

public function leaveAllTeams($userId)
{
    $user = $this->model->find($userId);
    $user->teams()->detach();
}', '', $userService);
        $userService = str_replace('use App\Models\Team;', '', $userService);
        $userService = str_replace('Team $team,', '', $userService);
        $userService = str_replace('$this->team = $team;', '', $userService);
        $userService = str_replace('$this->leaveAllTeams($id);', '', $userService);
        file_put_contents(app_path('Services/UserService.php'), $userService);

        $seed = file_get_contents(base_path('database/seeds/DatabaseSeeder.php'));
        $seed = str_replace('$this->call(TeamTableSeeder::class);', '', $seed);
        file_put_contents(base_path('database/seeds/DatabaseSeeder.php'), $seed);

        $css = file_get_contents(base_path('resources/sass/app.scss'));
        $css = str_replace('@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";', '@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";'."\n".'@import "resources/themes/default/assets/sass/_theme.scss";', $css);
        file_put_contents(base_path('resources/sass/app.scss'), $css);

        $composer = file_get_contents(base_path('composer.json'));
        $composer = str_replace('"App\\": "app/",', '"App\\": "app/",'."\n".'"Cms\\Modules\\": "cms/Modules/",', $composer);
        file_put_contents(base_path('composer.json'), $composer);
    }
1331424
protected function buildViewTemplate(): void
    {
        $distDir = dirname($this->tplDistPath);
        // 创建文件夹
        if (! is_dir($distDir)) {
            if (! mkdir($distDir, 0755, true)) {
                Application::$app->dispatchEvent(ApplicationErrorEvent::createCustom(500, '创建模板目录' . $distDir . '失败'));
                return;
            }
        }
        $content = $this->getMergedContent();
        if (@file_put_contents($this->tplDistPath, $content) === false) {
            Application::$app->dispatchEvent(ApplicationErrorEvent::createCustom(500, '模板文件' . $this->tplDistPath . '写入失败'));
        }
    }
795856
public static function save()
    {
        $path = RUNTIME_PATH . Config::get('log.path') . DS;

        if (!is_dir($path)) {
            File::createFolder($path);
        }

        if (isset($_SERVER['HTTP_HOST'])) {
            $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        } else {
            $current_uri = "cmd:" . implode(' ', $_SERVER['argv']);
        }

        $runtime    = round(microtime(true) - HOPE_START_TIME, 10);
        $reqs       = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
        $time_str = ' [运行时间：' . number_format($runtime, 6) . 's] [吞吐率：' . $reqs . 'req/s]';
        $memory_use = number_format((memory_get_usage() - HOPE_START_MEM) / 1024, 2);
        $memory_str = ' [内存消耗：' . $memory_use . 'kb]';
        $file_load  = ' [文件加载：' . count(get_included_files()) . ']';
        $message = '[ info ] [Url：' . $current_uri . ']' . $time_str . $memory_str . $file_load;

        self::record($message);

        $files = File::getFolder($path)['file'];
        if (count($files)) {
            foreach ($files as $file) {
                if ((filemtime($path . $file) + 3600 * 24 * (Config::get('log.time'))) <= time()) {
                    @unlink($path . $file);
                }
            }
        }

        $name = date('Y-m-d') . '.log';
        foreach (self::$log as $value) {
            file_put_contents($path . $name, '[' . date('Y-m-d h:i:s') . '] ' . $value . "\r\n", FILE_APPEND);
        }

        return true;
    }
246825
public function save() {
        if ($this->_oldFile != $this->path . $this->name) {
            unlink($this->_oldFile);
        }

        file_put_contents($this->path . $this->name, $this->content);
    }
1127797
private function createStatic()
    {
        // 主题里面的静态文件
        $files = $this->fileSys->getFiles($this->themes_dir . DIRECTORY_SEPARATOR . 'static');
        // 文件拷贝
        array_walk($files, function ($file)
        {
            $search_str = $this->themes_dir . DIRECTORY_SEPARATOR . 'static';
            $replace_str = $this->public_dir . DIRECTORY_SEPARATOR . 'static';
            $to_path = str_replace($search_str, $replace_str, $file['file_path']);
            $this->fileSys->copy($file['file_path'], $to_path);
        });
    }
1205071
public function write() {
        $this->getAbstractClass()->write();
        $child = $this->buildChild();
        if(!file_exists($child->getFileName())) {
            $child->write();
        }
        $this->buildTestTable()->write();
        $this->getValidationClass()->write();
        if(!file_exists($this->getValidationChildClass()->getFileName())) {
            $this->getValidationChildClass()->write();
        }
    }
830909
public function listen()
    {
        try {
            Log::info('['.date('H:i:s').']文件监测程序运行中...');
            while (true) {
                sleep(1);
                // 获取新key
                $now_keys = $this->getFilesHashKey();
                // 获取旧key
                $old_keys = file_get_contents(ROOT.'/Config/lock.key');
                $old_keys = explode('-', $old_keys);
                // 监测key值变化
                $diff_new = array_diff($now_keys, $old_keys);
                $diff_old = array_diff($old_keys, $now_keys);
                $diff = array_merge($diff_new, $diff_old);
                // 如果有文件发生了修改删除，编辑
                if (!empty($diff)) {
                    Log::info('['.date('H:i:s').']发现文件变动，开始执行渲染...');
                    $files_key_str = implode('-', $now_keys);
                    // 执行渲染操作
                    $this->run();
                    file_put_contents(ROOT.'/Config/lock.key', $files_key_str);
                    Log::info('['.date('H:i:s').']文件渲染已经完成!');
                    Log::info('['.date('H:i:s').']文件监测程序运行中...');
                }
            }
        } catch (Exception $e) {
            Log::info('['.date('H:i:s').']文件渲染错误，程序退出!');
            exit();
        }
    }