├── README.md ├── composer.json └── src ├── Bootstrap.php ├── OpcacheModule.php ├── commands └── OpcacheController.php ├── contracts ├── IFileFilterModel.php ├── IOpcacheFinder.php └── IOpcachePresenter.php ├── controllers └── DefaultController.php ├── messages ├── en │ ├── hint.php │ ├── interface.php │ └── status.php └── ru │ ├── hint.php │ ├── interface.php │ └── status.php ├── models ├── FileFilterModel.php └── OpcacheStatus.php ├── services ├── OpcacheFinder.php └── OpcachePresenter.php ├── utils ├── Helper.php ├── OpcacheException.php └── Translator.php ├── views └── default │ ├── _charts.php │ ├── _menu.php │ ├── blacklist.php │ ├── config.php │ ├── files.php │ └── index.php └── widgets └── PieWidget.php /README.md: -------------------------------------------------------------------------------- 1 | Yii2 OpCache module 2 | =================== 3 | Show statistic, config, reset all, invalidate files, search in cached files 4 | 5 | Installation 6 | ------------ 7 | 8 | The preferred way to install this extension is through [composer](http://getcomposer.org/download/). 9 | 10 | Either run 11 | 12 | ``` 13 | php composer.phar require --prefer-dist insolita/yii2-opcache "~1.0" 14 | ``` 15 | 16 | or add 17 | 18 | ``` 19 | "insolita/yii2-opcache": "~1.0" 20 | ``` 21 | 22 | to the require section of your `composer.json` file. 23 | 24 | 25 | Usage 26 | ----- 27 | 28 | Once the extension is installed, simply use it in your code by : 29 | ```php 30 | 'bootstrap'=>[ 31 | ... 32 | \insolita\opcache\Bootstrap::class 33 | ... 34 | ], 35 | ... 36 | 'modules'=>[ 37 | ... 38 | 'opcache'=>[ 39 | 'class'=>'insolita\opcache\OpcacheModule', 40 | 'as access'=>[ 41 | 'class' => \yii\filters\AccessControl::class, 42 | 'rules' => [ 43 | [ 44 | 'allow' => true, 45 | //Protect access 46 | 'roles' => ['developer'], 47 | ], 48 | ], 49 | ] 50 | ], 51 | ... 52 | ] 53 | 54 | ``` 55 | Go to route ```['/opcache/default/index']``` 56 | 57 | 58 | Also for console command usage - add in console configuration 59 | 60 | ```php 61 | 'bootstrap'=>[ 62 | ... 63 | \insolita\opcache\Bootstrap::class 64 | ... 65 | ], 66 | ... 67 | 'controllerMap'=>[ 68 | 'opcache'=>[ 69 | 'class'=>\insolita\opcache\commands\OpcacheController::class 70 | ] 71 | ] 72 | ``` 73 | commands opcache/status opcache/config opcache/files opcache/reset opcache/invalidate will be available 74 | 75 | Screens 76 | ------- 77 | ![Status](http://dl4.joxi.net/drive/2017/04/05/0008/3019/551883/83/a70744c562.jpg) 78 | ![Files](http://dl4.joxi.net/drive/2017/04/05/0008/3019/551883/83/070fedc0b3.jpg) 79 | ![Config](http://dl4.joxi.net/drive/2017/04/05/0008/3019/551883/83/c3769678c7.jpg) 80 | 81 | #### Understanding OpCache 82 | 83 | @see https://habrahabr.ru/company/mailru/blog/310054/ (Ru) 84 | 85 | @see http://jpauli.github.io/2015/03/05/opcache.html (En) 86 | 87 | 88 | ##### P.S. 89 | Russian settings translation based on 90 | https://sabini.ch/cms/perevod-nastroek-zend-opcache.html -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "insolita/yii2-opcache", 3 | "description": "Yii2 OpCache module - Show statistic, config, reset all, invalidate files, search in cached files", 4 | "type": "yii2-extension", 5 | "keywords": ["yii2","extension","opcache"], 6 | "license": "MIT", 7 | "authors": [ 8 | { 9 | "name": "insolita", 10 | "email": "webmaster100500@ya.ru" 11 | } 12 | ], 13 | "require": { 14 | "php":">=5.6.0", 15 | "yiisoft/yii2": "*", 16 | "yiisoft/yii2-bootstrap": "^2.0" 17 | }, 18 | "autoload": { 19 | "psr-4": { 20 | "\\insolita\\opcache\\": "src/" 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Bootstrap.php: -------------------------------------------------------------------------------- 1 | set(IOpcachePresenter::class, OpcachePresenter::class); 29 | \Yii::$container->set(IOpcacheFinder::class, OpcacheFinder::class); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/OpcacheModule.php: -------------------------------------------------------------------------------- 1 | registerTranslations(); 26 | } 27 | 28 | public function registerTranslations() 29 | { 30 | \Yii::$app->i18n->translations['opcache/*'] = [ 31 | 'class' => 'yii\i18n\PhpMessageSource', 32 | 'sourceLanguage' => 'en-US', 33 | 'basePath' => '@insolita/opcache/messages', 34 | 'fileMap' => [ 35 | 'opcache/interface' => 'interface.php', 36 | 'opcache/hint' => 'hint.php', 37 | 'opcache/status' => 'status.php', 38 | ], 39 | ]; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/commands/OpcacheController.php: -------------------------------------------------------------------------------- 1 | finder = $finder; 49 | $this->presenter = $presenter; 50 | parent::__construct($id, $module, $config); 51 | } 52 | 53 | /** 54 | * Show opcache statistic 55 | */ 56 | public function actionStatus() 57 | { 58 | $status = $this->finder->getStatus(); 59 | $this->showCaption('Common Status'); 60 | $this->showRow('opcache_enabled', $this->presenter->formatBool($status->getOpcacheEnabled())); 61 | $this->showRow('cache_full', $this->presenter->formatBool($status->getCacheFull())); 62 | $this->showRow('restart_pending', $this->presenter->formatBool($status->getRestartPending())); 63 | $this->showRow('restart_in_progress', $this->presenter->formatBool($status->getRestartInProgress())); 64 | $this->showCaption('Memory Usage'); 65 | foreach ($status->getMemoryUsage() as $key => $value) { 66 | $this->showRow($key, $this->presenter->formatMemory($value, $key)); 67 | } 68 | $this->showCaption('Interned Strings Usage'); 69 | foreach ($status->getStringsInfo() as $key => $value) { 70 | $this->showRow($key, $this->presenter->formatMemory($value, $key)); 71 | } 72 | $this->showCaption('Statistic'); 73 | foreach ($status->getStatistics() as $key => $value) { 74 | $this->showRow($key, $this->presenter->formatStatistic($value, $key)); 75 | } 76 | } 77 | 78 | /** 79 | * Show opcache config 80 | */ 81 | public function actionConfig() 82 | { 83 | $config = $this->finder->getDirectives(); 84 | foreach ($config as $key => $value) { 85 | $this->showRow($key, $value); 86 | } 87 | } 88 | 89 | /** 90 | * List of cached file; Use with pipe grep for filtering 91 | * 92 | * @example opcache/files | grep yii2 93 | */ 94 | public function actionFiles() 95 | { 96 | $files = $this->finder->getFiles(); 97 | foreach ($files as $row) { 98 | $this->stdout($row['full_path'] . PHP_EOL); 99 | } 100 | } 101 | 102 | /** 103 | * List of black-listed files and patterns 104 | */ 105 | public function actionBlack() 106 | { 107 | $files = $this->finder->getBlackList(); 108 | foreach ($files as $file) { 109 | $this->stdout($file . PHP_EOL); 110 | } 111 | } 112 | 113 | /** 114 | * Reset cache 115 | * 116 | * @return int 117 | */ 118 | public function actionReset() 119 | { 120 | if (opcache_reset()) { 121 | return 0; 122 | } else { 123 | return 1; 124 | } 125 | } 126 | 127 | /** 128 | * Invalidate file 129 | * 130 | * @param $file 131 | * 132 | * @return int 133 | */ 134 | public function actionInvalidate($file) 135 | { 136 | if (opcache_invalidate($file, true)) { 137 | return 0; 138 | } else { 139 | return 1; 140 | } 141 | } 142 | 143 | /** 144 | * Invalidate pathPart 145 | * 146 | * @param $pathPart 147 | * 148 | * @return int 149 | */ 150 | public function actionInvalidatePartial($pathPart) 151 | { 152 | $files = $this->finder->getFiles(); 153 | foreach ($files as $row) { 154 | if (mb_strpos($row['full_path'], $pathPart) !== false) { 155 | opcache_invalidate($row['full_path'], true); 156 | $this->stdout($row['full_path'] . PHP_EOL); 157 | } 158 | } 159 | return 1; 160 | } 161 | 162 | /** 163 | * @param $key 164 | * @param $value 165 | */ 166 | private function showRow($key, $value) 167 | { 168 | $this->stdout($key . ' - ' . $value . PHP_EOL); 169 | } 170 | 171 | /** 172 | * @param $value 173 | */ 174 | private function showCaption($value) 175 | { 176 | $this->stdout(str_repeat('=', 10) . ' ' . $value . ' ' . str_repeat('=', 10) . PHP_EOL); 177 | } 178 | } 179 | -------------------------------------------------------------------------------- /src/contracts/IFileFilterModel.php: -------------------------------------------------------------------------------- 1 | presenter = $presenter; 41 | $this->presenter->setUpFormat(); 42 | $this->finder = $finder; 43 | parent::__construct($id, $module, $config); 44 | } 45 | 46 | /** 47 | * @return string 48 | */ 49 | public function actionIndex() 50 | { 51 | $version = $this->finder->getVersion(); 52 | $status = $this->finder->getStatus(); 53 | $presenter = $this->presenter; 54 | return $this->render('index', compact('version', 'status', 'presenter')); 55 | } 56 | 57 | /** 58 | * @return string 59 | */ 60 | public function actionConfig() 61 | { 62 | $version = $this->finder->getVersion(); 63 | $directives = $this->finder->getDirectives(); 64 | $directives = $this->presenter->configDirectivesProvider($directives); 65 | return $this->render('config', compact('version', 'directives')); 66 | } 67 | 68 | /** 69 | * @return string 70 | */ 71 | public function actionFiles() 72 | { 73 | $version = $this->finder->getVersion(); 74 | $files = $this->finder->getFiles(); 75 | $searchModel = $this->presenter->createFileFilterModel($files); 76 | $provider = $searchModel->search(\Yii::$app->request->getQueryParams()); 77 | return $this->render('files', compact('version', 'searchModel', 'provider')); 78 | } 79 | 80 | /** 81 | * @return \yii\web\Response 82 | */ 83 | public function actionReset() 84 | { 85 | if (opcache_reset()) { 86 | \Yii::$app->session->setFlash('success', Translator::t('cache_reset_success')); 87 | } else { 88 | \Yii::$app->session->setFlash('error', Translator::t('cache_reset_fail')); 89 | } 90 | return $this->redirect(\Yii::$app->request->getReferrer()); 91 | } 92 | 93 | /** 94 | * @return string 95 | */ 96 | public function actionBlack() 97 | { 98 | $blackList = $this->finder->getBlackList(); 99 | $version = $this->finder->getVersion(); 100 | $blackFile = $this->finder->getDirectives()['opcache.blacklist_filename']; 101 | return $this->render('blacklist', compact('blackList', 'blackFile', 'version')); 102 | } 103 | 104 | /** 105 | * @param $file 106 | * 107 | * @return \yii\web\Response 108 | */ 109 | public function actionInvalidate($file) 110 | { 111 | if (opcache_invalidate($file, true)) { 112 | \Yii::$app->session->setFlash( 113 | 'success', 114 | Translator::t('file_invalidate_success') . ' - ' . Html::encode($file) 115 | ); 116 | } else { 117 | \Yii::$app->session->setFlash( 118 | 'error', 119 | Translator::t('file_invalidate_fail') . ' - ' . Html::encode($file) 120 | ); 121 | } 122 | return $this->redirect(\Yii::$app->request->getReferrer()); 123 | } 124 | 125 | /** 126 | * @return \yii\web\Response 127 | */ 128 | public function actionInvalidatePartial() 129 | { 130 | $files = $this->finder->getFiles(); 131 | $model = $this->presenter->createFileFilterModel($files); 132 | $files = $model->filterFiles(\Yii::$app->request->post(null, [])); 133 | if (!empty($files)) { 134 | foreach ($files as $file) { 135 | opcache_invalidate($file['full_path'], true); 136 | } 137 | \Yii::$app->session->setFlash('success', Translator::t('cache_reset_success')); 138 | } else { 139 | \Yii::$app->session->setFlash('error', Translator::t('cache_reset_fail')); 140 | } 141 | return $this->redirect(['files']); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/messages/en/hint.php: -------------------------------------------------------------------------------- 1 | 'Version', 4 | 'opcache.enable' => 'Determines if OPCache is enabled', 5 | 'opcache.enable_cli' => 'Determines if Zend OPCache is enabled for the CLI version of PHP', 6 | 'opcache.use_cwd' => 'When this directive is enabled, the OPcache appends the current 7 | working directory to the script key, thus eliminating possible collisions between files with the same name 8 | (basename). Disabling the directive improves performance, but may break existing applications', 9 | 'opcache.validate_timestamps' => 'When disabled, you must reset the OPcache manually or restart 10 | the webserver for changes to the filesystem to take effect', 11 | 'opcache.validate_permission' => 'Validate cached file permissions.', 12 | 'opcache.validate_root' => 'Prevent name collisions in chroot\'ed environment', 13 | 'opcache.inherited_hack' => '', 14 | 'opcache.dups_fix' => '', 15 | 'opcache.revalidate_path' => 'Enables or disables file search in include_path optimization', 16 | 'opcache.log_verbosity_level' => ' All OPcache errors go to the Web server log. By default, only 17 | fatal errors (level 0) or errors (level 1) are logged. You can also enable warnings (level 2), info messages 18 | (level 3) or debug messages (level 4)', 19 | 'opcache.memory_consumption' => 'The OPcache shared memory storage size', 20 | 'opcache.interned_strings_buffer' => 'The amount of memory for interned strings in Mbytes', 21 | 'opcache.max_accelerated_files' => 'The maximum number of keys (scripts) in the OPcache hash table. 22 | Only numbers between 200 and 100000 are allowed', 23 | 'opcache.max_wasted_percentage' => 'The maximum percentage of "wasted" memory until a restart is scheduled', 24 | 'opcache.consistency_checks' => 'Check the cache checksum each N requests. The default value of "0" 25 | means that the checks are disabled.', 26 | 'opcache.force_restart_timeout' => 'How long to wait (in seconds) for a scheduled restart to begin 27 | if the cache is not being accessed', 28 | 'opcache.revalidate_freq' => 'How often (in seconds) to check file timestamps for changes 29 | to the shared memory storage allocation. ("1" means validate once per second, but only once per request. 30 | "0" means always validate)', 31 | 'opcache.preferred_memory_model' => 'Preferred Shared Memory back-end. 32 | Leave empty and let the system decide.', 33 | 'opcache.blacklist_filename' => 'The location of the OPcache blacklist file (wildcards allowed). 34 | Each OPcache blacklist file is a text file that holds the names of files that should not be accelerated. 35 | The file format is to add each filename to a new line. The filename may be a full path or just a file prefix 36 | (i.e., /var/www/x blacklists all the files and directories in /var/www that start with \'x\'). 37 | Line starting with a ; are ignored (comments).', 38 | 'opcache.max_file_size' => 'Allows exclusion of large files from being cached. By default all files 39 | are cached.', 40 | 'opcache.error_log' => 'OPcache error_log file name. Empty string assumes "stderr"', 41 | 'opcache.protect_memory' => 'Protect the shared memory from unexpected writing during script execution. 42 | Useful for internal debugging only.', 43 | 'opcache.save_comments' => 'If disabled, all PHPDoc comments are dropped from the code to reduce the 44 | size of the optimized code.', 45 | 'opcache.load_comments'=>'', 46 | 'opcache.fast_shutdown' => 'If enabled, a fast shutdown sequence is used for the accelerated code', 47 | 'opcache.enable_file_override' => 'Allow file existence override (file_exists, etc.) performance feature.', 48 | 'opcache.optimization_level' => 'A bitmask, where each bit enables or disables the appropriate OPcache 49 | passes', 50 | 'opcache.lockfile_path' => '', 51 | 'opcache.file_cache' => 'Enables and sets the second level cache directory. 52 | It should improve performance when SHM memory is full, at server restart or 53 | SHM reset. The default "" disables file based caching.', 54 | 'opcache.file_cache_only' => 'Enables or disables opcode caching in shared memory.', 55 | 'opcache.file_cache_consistency_checks' => 'Enables or disables checksum validation when 56 | script loaded from file cache.', 57 | 'opcache.file_update_protection'=>'', 58 | 'opcache.restrict_api'=>'Allows calling OPcache API functions only from PHP scripts which path is 59 | started from specified string. The default "" means no restriction', 60 | 'opcache.mmap_base'=>'Mapping base of shared memory segments (for Windows only). All the PHP 61 | processes have to map shared memory into the same address space. This 62 | directive allows to manually fix the "Unable to reattach to base address" 63 | errors.', 64 | 'opcache.huge_code_pages'=>'Enables or disables copying of PHP code (text segment) into HUGE PAGES. 65 | This should improve performance, but requires appropriate OS configuration.', 66 | 'opcache.file_cache_fallback'=>'Implies opcache.file_cache_only=1 for a certain process that failed to 67 | reattach to the shared memory (for Windows only). Explicitly enabled file cache is required.' 68 | ]; -------------------------------------------------------------------------------- /src/messages/en/interface.php: -------------------------------------------------------------------------------- 1 | 'Option', 4 | 'value'=>'Value', 5 | 'hint'=>'Hint', 6 | 'reset'=>'Reset', 7 | 'status'=>'Status', 8 | 'config'=>'Config', 9 | 'file_list'=>'Cached Files', 10 | 'cache_reset_success'=>'Cache successfully cleaned!', 11 | 'cache_reset_fail'=>'Can`t reset cache!', 12 | 'file_invalidate_success'=>'File successfully invalidated!', 13 | 'file_invalidate_fail'=>'File not found, or not need invalidation!', 14 | 'file_compile_success'=>'File successfully compiled!', 15 | 'invalidate_file'=>'Invalidate file', 16 | 'invalidate'=>'invalidate', 17 | 'compile_file'=>'compile_file', 18 | 'filepath'=>'File path', 19 | 'black_list'=>'Black List', 20 | 'black_list_file'=>'Black List File', 21 | 'black_list_ignors'=>'Ignored Files and Patterns', 22 | 'black_list_notice'=>'Black list items not found!', 23 | 'full_path'=>'Full Path', 24 | 'hits'=>'Hits', 25 | 'memory_consumption'=>'Memory Consumption', 26 | 'last_used_timestamp'=>'Last Usage', 27 | 'file_timestamp'=>'Cache Time', 28 | 'memory_usage'=>'Memory Usage', 29 | 'hits_misses'=>'Hits/Misses', 30 | 'common_status' =>'Common Status', 31 | 'interned_strings_usage'=>'Interned Strings Usage', 32 | 'opcache_statistics'=>'OpCache Statistics', 33 | 'reset_founded_files' =>'Reset founded files' 34 | ]; -------------------------------------------------------------------------------- /src/messages/en/status.php: -------------------------------------------------------------------------------- 1 | 'Used Memory', 4 | 'free_memory'=>'Free Memory', 5 | 'wasted_memory'=>'Wasted Memory', 6 | 'current_wasted_percentage'=>'Wasted Memory Percentage', 7 | 'opcache_enabled'=>'Opcache Enabled?', 8 | 'cache_full'=>'Cache Full?', 9 | 'restart_pending'=>'Restart Pending?', 10 | 'restart_in_progress'=>'Restart in Progress ?', 11 | 'num_cached_scripts'=>'Number of Cached Files', 12 | 'num_cached_keys'=>'Number Of Cached Keys', 13 | 'max_cached_keys'=>'Max Cached Keys', 14 | 'hits'=>'Hits', 15 | 'start_time'=>'Start Time', 16 | 'last_restart_time'=>'Last Restart Time', 17 | 'oom_restarts'=>'Oom Restarts', 18 | 'hash_restarts'=>'Hash Restarts', 19 | 'manual_restarts'=>'Manual Restarts', 20 | 'misses'=>'Misses', 21 | 'blacklist_misses'=>'Black List Misses', 22 | 'blacklist_miss_ratio'=>'Black List Misses Ratio', 23 | 'opcache_hit_rate'=>'Opcache Hit Rate', 24 | 'buffer_size'=>'Buffer Size', 25 | 'number_of_trings'=>'Number Of Strings', 26 | ]; -------------------------------------------------------------------------------- /src/messages/ru/hint.php: -------------------------------------------------------------------------------- 1 | 'Версия', 4 | 'opcache.enable' => 'Включение/выключение OpCache. 5 | В выключенном состоянии код не оптимизируется и не кешируется.', 6 | 'opcache.enable_cli' => 'Включение OpCache для CLI-версии PHP. 7 | Наилучшим образом подходит для тестирование и отладки.', 8 | 'opcache.use_cwd' => 'При включении этого параметра, OpCache добавляет текущую рабочую 9 | директорию в ключ скрипта для предотвращения возникновения колизий между файлами с одинаковым именем. 10 | Выключение этой функции увеличивает производительность, но может нарушить работу приложений.', 11 | 'opcache.validate_timestamps' => 'При отключенном параметре, появляется возможность обнуления OpCache 12 | вручную или перезапуском вебсервера для того, чтобы привести в актуальное состояние данных об изменениях в файлах. 13 | Частота проверки управляется параметром opcache.revalidate_freq', 14 | 'opcache.validate_permission' => 'Проверять полномочия кешированных файло.', 15 | 'opcache.validate_root' => 'Предотвращение коллизий имен в chroot - окружении', 16 | 'opcache.inherited_hack' => 'В php-5.3 и выше этот хак более не требуется и изменение параметра ни коим образом не скажется на работе.', 17 | 'opcache.dups_fix' => 'Включайте этот параметр только при появлении ошибок вида Cannot redeclare class', 18 | 'opcache.revalidate_path' => 'Включение или отключение оптимизации поиска файлов в include_path. 19 | Если поиск файлов выключен и будет найден закешированный файл, используемый в include_path, файл не будет найден 20 | повторно. Таким образом, если файл с именем, попадающийся где-либо еще в include_path, он не будет найден. 21 | Включайте этот параметр только в случае, если это действительно принесет ожидаемый эффект ускорения. 22 | По умолчанию возможность отключена, т.е оптимизация активирована.', 23 | 'opcache.log_verbosity_level' => 'Все ошибки OpCache отправлять в лог-файл лог-файл веб-сервера. По умолчанию, журналируются только критические ошибки (level 0) или обычные ошибки (level 1). Так же можно включить выводит предупреждений (level 2), информационных сообщений (level 3) или отладочную информацию (level 4).', 24 | 'opcache.memory_consumption' => 'Размер используемой памяти для хранения прекомпилированного PHP-кода. 25 | Размер указывается в мегабайтах.', 26 | 'opcache.interned_strings_buffer' => 'Количество памяти для пула строк в мегабайтах', 27 | 'opcache.max_accelerated_files' => 'Максимальное количество ключей (скриптов) в хэш-таблице OpCache. 28 | Число должно быть простым и быть больше, чем те, что приведены в примере:{ 223, 463, 983, 1979, 3907, 7963, 16229, 29 | 32531, 65407, 130987, 262237, 524521, 1048793 }. Допустимы числа между 200 и 1000000.', 30 | 'opcache.max_wasted_percentage' => 'Максимальный процент потеряной памяти 31 | для запланированного перезапуска.', 32 | 'opcache.consistency_checks' => 'Проверять контрольную сумму кэша каждое N-ое количество запросов. По умолчанию параметр имеет значение равное нулю, что означает отключение проверки. Подсчет контрольной суммы снижает производительность, этот параметр следует включать только если требуется отладка.', 33 | 'opcache.force_restart_timeout' => 'Какое время ожидать (в секундах) перед запланированной перезагрузкой в случае недоступности кэша.', 34 | 'opcache.revalidate_freq' => 'Через какой промежуток времени (в секундах) проверять изменения 35 | временных меток для поддержания данных в памяти в актуальном состоянии. (“1” означает проверку с периодичностью 36 | раз в секунду для запроса, “0” — постоянная проверка)', 37 | 'opcache.preferred_memory_model' => 'Предпочитаемый бэкэнд общей памяти. Можно оставить пустым и позволить системе самой разобраться.', 38 | 'opcache.blacklist_filename' => 'Месторасположение списка файлов, к которым запрещен доступ для OpCache (поддерживаются маски). Каждый такой файл является текстовым файлом, в котором хранятся имена файлов, которые не требуется кешировать.Формат файла предусматривает размещение каждого имени файла в отдельной строке. Имя файла может содержать полный путь, либо префикс (к примеру /var/www/x укажет на все файлы в директориях, начинающихся на ‘x’. Строки, начинающиеся с “;” игнорируются (комментарии). Обычно, блокируют файлы следующих типов: Директории, в которых содержатся автоматически генерирующиеся файлы с кодом (к примеру кеш Smarty или ZFW фреймворков); Код, который не работает при кешировании/оптимизации;Код, который не отображается по причине ошибок в OpCache.', 39 | 'opcache.max_file_size' => 'Позволяет исключать большие файлы из кеширования. По умолчанию кешируются все файлы.', 40 | 'opcache.error_log' => 'Определение названия и местоположения лога ошибок OpCache. При пустом значении ошибки выводятся в stderr', 41 | 'opcache.protect_memory' => 'Защита общей памяти от несанкционированной записи во время выполнения скрипта. Полезно только для отладки.', 42 | 'opcache.save_comments' => 'Если выключено, все комментарии PHPDoc будут удалены из кода с целью 43 | уменьшения размера оптимизированного кода. Отключение параметра может вызвать некорректную работу некоторых 44 | приложений или фреймворков (к примеру, Doctrine, ZF2, PHPUnit)', 45 | 'opcache.load_comments'=>'Если выключено, комментарии PHPDoc не будут загружаться из общей памяти. При включении вывода, комментарии будут сохранятся, но выводиться приложениями только в случае надобности.', 46 | 'opcache.fast_shutdown' => 'Если включено, будет использоваться последовательность быстрых выключений для оптимизированного кода. Эта возможность не освобождает каждый используемый блок памяти, но позволяет работать Zend Engine Memory Manager.', 47 | 'opcache.enable_file_override' => 'При включении OpCache будет проверять наличие закешированного файла при вызовах file_exists(),is_file() и is_readable(). Это может увеличить скорость работы в приложениях, которые проверяют расширение и читабельность PHP-скриптов, но появляется риск вывода устаревших данных в случае отключения параметра opcache.validate_timestamps.', 48 | 'opcache.optimization_level' => 'Маска битности, в которой каждый бит включает или отключает в соответствующие проходы OpCache.', 49 | 'opcache.lockfile_path' => '', 50 | 'opcache.file_update_protection'=>'Через какой промежуток времени (в секундах) проверять изменения временных 51 | меток для поддержания данных в памяти в актуальном состоянии. (“1” означает проверку с периодичностью раз в 52 | секунду для запроса, “0” — постоянная проверка)', 53 | 'opcache.file_cache' => 'Enables and sets the second level cache directory. 54 | It should improve performance when SHM memory is full, at server restart or 55 | SHM reset. The default "" disables file based caching.', 56 | 'opcache.file_cache_only' => 'Включение кеширования в разделяемой памяти', 57 | 'opcache.file_cache_consistency_checks' => 'Включение проверки контрольной суммы файлов загружаемых из кеша', 58 | 'opcache.restrict_api'=>'Разрешение вызова API-функций OpCache из PHP-скриптов, путь к которым начинается тем, что указано в строке. По умолчанию пустое значение означает разрешение на всё.', 59 | 'opcache.mmap_base'=>'Маппирование основных сегментов памяти (только для Windows). Все процессы PHP маппируются в общей памяти в некотором адресном пространстве. Этот параметр позволяет вручную исправить ошибки вида "Unable to reattach to base address"', 60 | 'opcache.huge_code_pages'=>'Enables or disables copying of PHP code (text segment) into HUGE PAGES. 61 | This should improve performance, but requires appropriate OS configuration.', 62 | 'opcache.file_cache_fallback'=>'Implies opcache.file_cache_only=1 for a certain process that failed to 63 | reattach to the shared memory (for Windows only). Explicitly enabled file cache is required.' 64 | ]; -------------------------------------------------------------------------------- /src/messages/ru/interface.php: -------------------------------------------------------------------------------- 1 | 'Параметр', 4 | 'value'=>'Значение', 5 | 'hint'=>'Описание', 6 | 'reset'=>'Сброс', 7 | 'status'=>'Статус', 8 | 'config'=>'Конфигурация', 9 | 'file_list'=>'Файлы в кеше', 10 | 'cache_reset_success'=>'Кеш очищен!', 11 | 'cache_reset_fail'=>'Ошибка очистки кеша!', 12 | 'file_invalidate_success'=>'Кеш файла сброшен!', 13 | 'file_invalidate_fail'=>'Файл не найден или не нуждается в сбросе', 14 | 'file_compile_success'=>'Файл добавлен в кеш!', 15 | 'invalidate_file'=>'Сбросить кеш файла', 16 | 'invalidate'=>'Сброс', 17 | 'compile_file'=>'Добавить файл в кеш', 18 | 'filepath'=>'Полный путь к файлу', 19 | 'black_list'=>'Чёрный список', 20 | 'black_list_file'=>'Файл чёрного списка', 21 | 'black_list_ignors'=>'Игнорируемые файлы и маски путей', 22 | 'black_list_notice'=>'Файлов в чёрном списке не найдено', 23 | 'full_path'=>'Путь', 24 | 'hits'=>'Использований', 25 | 'memory_consumption'=>'Память', 26 | 'last_used_timestamp'=>'Использовалось', 27 | 'file_timestamp'=>'Изменен', 28 | 'memory_usage'=>'Использование памяти', 29 | 'hits_misses'=>'Попаданий/Промахов', 30 | 'common_status' =>'Общий статус', 31 | 'interned_strings_usage'=>'Внутреннее использование строк', 32 | 'opcache_statistics'=>'Статистика OpCache', 33 | 'reset_founded_files' =>'Сбросить найденные файлы' 34 | ]; -------------------------------------------------------------------------------- /src/messages/ru/status.php: -------------------------------------------------------------------------------- 1 | 'Использовано', 4 | 'free_memory'=>'Свободно', 5 | 'wasted_memory'=>'Потеряная память', 6 | 'current_wasted_percentage'=>'Процент потеряной памяти', 7 | 'opcache_enabled'=>'Opcache Включен?', 8 | 'cache_full'=>'Кеш заполнен?', 9 | 'restart_pending'=>'Ожидается перезагрузка?', 10 | 'restart_in_progress'=>'Выполняется перезагрузка ?', 11 | 'num_cached_scripts'=>'Кол-во закешированных файлов', 12 | 'num_cached_keys'=>'Кол-во закешированных ключей', 13 | 'max_cached_keys'=>'Максимум закешированных ключей', 14 | 'hits'=>'Использований', 15 | 'start_time'=>'Дата запуска', 16 | 'last_restart_time'=>'Дата последнего перезапуска', 17 | 'oom_restarts'=>'Перезапусков по лимиту памяти', 18 | 'hash_restarts'=>'Перезапусков по лимиту кол-ва файлов', 19 | 'manual_restarts'=>'Перезапусков вручную', 20 | 'misses'=>'Промахов', 21 | 'blacklist_misses'=>'Промахов Чёрного списка', 22 | 'blacklist_miss_ratio'=>'% Промахов Чёрного списка', 23 | 'opcache_hit_rate'=>'% Хитов', 24 | 'buffer_size'=>'Размер буфера', 25 | 'number_of_strings'=>'Кол-во строк' 26 | ]; -------------------------------------------------------------------------------- /src/models/FileFilterModel.php: -------------------------------------------------------------------------------- 1 | files = $files; 39 | parent::__construct($config); 40 | } 41 | 42 | /** 43 | * @return array 44 | */ 45 | public function rules() 46 | { 47 | return [ 48 | [['full_path'], 'trim'], 49 | [['full_path'], 'string', 'max' => 100], 50 | ]; 51 | } 52 | 53 | /** 54 | * @return array 55 | */ 56 | public function attributeLabels() 57 | { 58 | return [ 59 | 'full_path' => Translator::t('full_path'), 60 | ]; 61 | } 62 | 63 | /** 64 | * @param $params 65 | * 66 | * @return \yii\data\ArrayDataProvider 67 | */ 68 | public function search(array $params = []) 69 | { 70 | $provider = new ArrayDataProvider( 71 | [ 72 | 'allModels' => $this->files, 73 | 'key' => 'full_path', 74 | 'pagination' => ['pageSize' => 100], 75 | 'sort' => [ 76 | 'attributes' => [ 77 | 'full_path' => [], 78 | 'timestamp' => [], 79 | 'hits' => [], 80 | 'memory_consumption' => [], 81 | 'last_used_timestamp' => [], 82 | ], 83 | 'defaultOrder' => ['full_path' => SORT_ASC], 84 | ], 85 | ] 86 | ); 87 | if ($this->load($params) && $this->validate() && !empty($this->full_path)) { 88 | $provider = new ArrayDataProvider( 89 | [ 90 | 'allModels' => array_filter($this->files, [$this, 'pathFilter']), 91 | 'key' => 'full_path', 92 | 'pagination' => ['pageSize' => 100], 93 | 'sort' => [ 94 | 'attributes' => [ 95 | 'full_path' => [], 96 | 'timestamp' => [], 97 | 'hits' => [], 98 | 'memory_consumption' => [], 99 | 'last_used_timestamp' => [], 100 | ], 101 | 'defaultOrder' => ['full_path' => SORT_ASC], 102 | ], 103 | ] 104 | ); 105 | } 106 | return $provider; 107 | } 108 | 109 | /** 110 | * @param $params 111 | * 112 | * @return array 113 | */ 114 | public function filterFiles(array $params = []) 115 | { 116 | if ($this->load($params) && $this->validate() && !empty($this->full_path)) { 117 | return array_filter($this->files, [$this, 'pathFilter']); 118 | } else { 119 | return []; 120 | } 121 | } 122 | 123 | /** 124 | * @param $item 125 | * 126 | * @return bool 127 | */ 128 | protected function pathFilter($item) 129 | { 130 | if (mb_strpos($item['full_path'], $this->full_path) !== false) { 131 | return true; 132 | } else { 133 | return false; 134 | } 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/models/OpcacheStatus.php: -------------------------------------------------------------------------------- 1 | memoryUsage = Helper::remove($config, 'memory_usage'); 60 | $this->statistics = Helper::remove($config, 'opcache_statistics'); 61 | $this->stringsInfo = Helper::remove($config, 'interned_strings_usage'); 62 | foreach ($config as $name => $value) { 63 | $name = Helper::variablize($name); 64 | if (isset($this->{$name})) { 65 | $this->{$name} = $value; 66 | } 67 | } 68 | } 69 | 70 | /** 71 | * @return bool 72 | */ 73 | public function getOpcacheEnabled() 74 | { 75 | return $this->opcacheEnabled; 76 | } 77 | 78 | /** 79 | * @return bool 80 | */ 81 | public function getCacheFull() 82 | { 83 | return $this->cacheFull; 84 | } 85 | 86 | /** 87 | * @return bool 88 | */ 89 | public function getRestartPending() 90 | { 91 | return $this->restartPending; 92 | } 93 | 94 | /** 95 | * @return bool 96 | */ 97 | public function getRestartInProgress() 98 | { 99 | return $this->restartInProgress; 100 | } 101 | 102 | /** 103 | * @return array 104 | */ 105 | public function getMemoryUsage() 106 | { 107 | return $this->memoryUsage; 108 | } 109 | 110 | /** 111 | * @return array 112 | */ 113 | public function getStatistics() 114 | { 115 | return $this->statistics; 116 | } 117 | 118 | /** 119 | * @return array 120 | */ 121 | public function getStringsInfo() 122 | { 123 | return $this->stringsInfo; 124 | } 125 | 126 | } 127 | -------------------------------------------------------------------------------- /src/services/OpcacheFinder.php: -------------------------------------------------------------------------------- 1 | directives = Helper::remove($config, 'directives', []); 55 | $this->blackList = Helper::remove($config, 'blacklist', []); 56 | $this->version = Helper::getValue($config, 'version.opcache_product_name', '') 57 | . Helper::getValue($config, 'version.version', 'Unknown'); 58 | $status = opcache_get_status(true); 59 | $this->files = Helper::remove($status, 'scripts', []); 60 | $this->status = new OpcacheStatus($status); 61 | unset($config, $status); 62 | } catch (\Throwable $e) { 63 | throw new OpcacheException( 64 | 'Opcache functions not available; 65 | Check if extension opcache installed; Check opcache.restriction_api option' 66 | ); 67 | } 68 | } 69 | 70 | /** 71 | * @return array 72 | */ 73 | public function getDirectives() 74 | { 75 | return $this->directives; 76 | } 77 | 78 | /** 79 | * @return string 80 | */ 81 | public function getVersion() 82 | { 83 | return $this->version; 84 | } 85 | 86 | /** 87 | * @return array 88 | */ 89 | public function getBlackList() 90 | { 91 | return $this->blackList?$this->blackList:[]; 92 | } 93 | 94 | /** 95 | * @return array 96 | */ 97 | public function getFiles() 98 | { 99 | return $this->files ? array_values($this->files) : []; 100 | } 101 | 102 | /** 103 | * @return \insolita\opcache\models\OpcacheStatus 104 | */ 105 | public function getStatus() 106 | { 107 | return $this->status; 108 | } 109 | 110 | } 111 | -------------------------------------------------------------------------------- /src/services/OpcachePresenter.php: -------------------------------------------------------------------------------- 1 | formatter->booleanFormat = [ 27 | '', 28 | '', 29 | ]; 30 | \Yii::$app->formatter->sizeFormatBase = 1024; 31 | } 32 | 33 | /** 34 | * @param array $directives 35 | * 36 | * @return \yii\data\ArrayDataProvider 37 | */ 38 | public function configDirectivesProvider(array &$directives) 39 | { 40 | $data = []; 41 | foreach ($directives as $key => $value) { 42 | $data[] 43 | = [ 44 | 'option' => $key, 45 | 'hint' => $this->translateHint($key), 46 | 'value' => $this->formatValue($value, $key), 47 | ]; 48 | } 49 | return new ArrayDataProvider( 50 | [ 51 | 'allModels' => $data, 52 | 'key' => 'option', 53 | 'pagination' => ['pageSize' => 100], 54 | 'sort' => [ 55 | 'attributes' => ['option' => []], 56 | 'defaultOrder' => ['option' => SORT_ASC], 57 | ], 58 | ] 59 | ); 60 | } 61 | 62 | /** 63 | * @param array $files 64 | * 65 | * @return \insolita\opcache\contracts\IFileFilterModel|\yii\base\Model 66 | */ 67 | public function createFileFilterModel(array &$files) 68 | { 69 | return new FileFilterModel($files); 70 | } 71 | 72 | /** 73 | * @param $value 74 | * @param $key 75 | * 76 | * @return string 77 | */ 78 | public function formatStatistic($value, $key) 79 | { 80 | if (in_array($key, ['start_time', 'last_restart_time'])) { 81 | $value = $value ? \Yii::$app->formatter->asDatetime($value) : ' - '; 82 | } elseif (in_array($key, ['blacklist_miss_ratio', 'opcache_hit_rate'])) { 83 | $value = round($value, 2) . '%'; 84 | } 85 | return $value; 86 | } 87 | 88 | /** 89 | * @param $value 90 | * @param $key 91 | * 92 | * @return string 93 | */ 94 | public function formatMemory($value, $key) 95 | { 96 | if (in_array($key, ['used_memory', 'buffer_size', 'free_memory', 'wasted_memory'])) { 97 | $value = \Yii::$app->formatter->asShortSize($value); 98 | } elseif ($key == 'current_wasted_percentage') { 99 | $value = round($value, 3) . '%'; 100 | } 101 | return $value; 102 | } 103 | 104 | /** 105 | * @param $value 106 | * 107 | * @return string 108 | */ 109 | public function formatBool($value) 110 | { 111 | return \Yii::$app->formatter->asBoolean($value); 112 | } 113 | 114 | /** 115 | * @param $message 116 | * 117 | * @return string 118 | */ 119 | protected function translateHint($message) 120 | { 121 | return Translator::hint($message); 122 | } 123 | 124 | /** 125 | * @param $value 126 | * @param $key 127 | * 128 | * @return string 129 | */ 130 | protected function formatValue($value, $key = null) 131 | { 132 | 133 | if (in_array($key, ['opcache.memory_consumption'])) { 134 | return \Yii::$app->formatter->asShortSize($value); 135 | } 136 | 137 | $type = gettype($value); 138 | switch ($type) { 139 | case 'boolean': 140 | return \Yii::$app->formatter->asBoolean($value); 141 | case 'float': 142 | return \Yii::$app->formatter->asDecimal($value); 143 | default: 144 | return $value; 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /src/utils/Helper.php: -------------------------------------------------------------------------------- 1 | $key; 50 | } elseif (is_array($array)) { 51 | return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default; 52 | } else { 53 | return $default; 54 | } 55 | } 56 | 57 | /** 58 | * @param $array 59 | * @param $key 60 | * @param null $default 61 | * 62 | * @return mixed|null 63 | */ 64 | public static function remove(&$array, $key, $default = null) 65 | { 66 | if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) { 67 | $value = $array[$key]; 68 | unset($array[$key]); 69 | 70 | return $value; 71 | } 72 | 73 | return $default; 74 | } 75 | 76 | /** 77 | * Converts a word like "send_email" to "sendEmail". 78 | * 79 | * @param string $word to lowerCamelCase 80 | * 81 | * @return string 82 | */ 83 | public static function variablize($word) 84 | { 85 | $word = str_replace( 86 | ' ', 87 | '', 88 | ucwords(preg_replace('/[^A-Za-z0-9]+/', ' ', $word)) 89 | ); 90 | 91 | return strtolower($word[0]) . substr($word, 1); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/utils/OpcacheException.php: -------------------------------------------------------------------------------- 1 | 'drawMemoryChart', 10 | 'options' => ['style' => 'width:600px;height:400px;','id'=>'memoryChart'], 11 | 'clientOptions' => [ 12 | 'title' => Translator::t('memory_usage')."\n" 13 | . Translator::status('current_wasted_percentage').' = ' 14 | .round($status->getMemoryUsage()['current_wasted_percentage'],2).'%', 15 | 'tooltip' => ['text' => 'percentage'], 16 | 'legend' => ['position' => 'right'], 17 | 'slices' => [ 18 | 0=>['color'=>'red'], 19 | 1=>['color'=>'green'], 20 | 2 => ['offset' => 0.3,'color'=>'yellow'], 21 | ], 22 | 'pieHole'=> 0.3, 23 | ], 24 | 'data' => [ 25 | ['label'=>'Memory','value'=>'Usage'], 26 | [ 27 | 'label' => Translator::status('used_memory') 28 | . ' - ' . Yii::$app->formatter->asShortSize( 29 | $status->getMemoryUsage()['used_memory'] 30 | ), 31 | 'value' => $status->getMemoryUsage()['used_memory'], 32 | ], 33 | [ 34 | 'label' => Translator::status('free_memory') 35 | . ' - ' . Yii::$app->formatter->asShortSize( 36 | $status->getMemoryUsage()['free_memory'] 37 | ), 38 | 'value' => $status->getMemoryUsage()['free_memory'], 39 | ], 40 | [ 41 | 'label' => Translator::status('wasted_memory') 42 | . ' - ' . Yii::$app->formatter->asShortSize( 43 | $status->getMemoryUsage()['wasted_memory'] 44 | ), 45 | 'value' => $status->getMemoryUsage()['wasted_memory'], 46 | ], 47 | ], 48 | ] 49 | ); 50 | echo insolita\opcache\widgets\PieWidget::widget( 51 | [ 52 | 'functionName' => 'drawBufferChart', 53 | 'options' => ['style' => 'width:600px;height:400px;','id'=>'bufferChart'], 54 | 'clientOptions' => [ 55 | 'title' => Translator::status('buffer_size') 56 | .' - '.Yii::$app->formatter->asShortSize($status->getStringsInfo()['buffer_size']), 57 | 'tooltip' => ['text' => 'percentage'], 58 | 'legend' => ['position' => 'right'], 59 | 'slices' => [ 60 | 0=>['color'=>'red'], 61 | 1=>['color'=>'blue'] 62 | ], 63 | 'pieHole'=> 0.4, 64 | ], 65 | 'data' => [ 66 | ['label'=>'Used','value'=>'Free'], 67 | 68 | [ 69 | 'label' => Translator::status('used_memory') 70 | . ' - ' . Yii::$app->formatter->asShortSize($status->getStringsInfo()['used_memory']), 71 | 'value' => $status->getStringsInfo()['used_memory'], 72 | ], 73 | [ 74 | 'label' => Translator::status('free_memory') 75 | . ' - ' . Yii::$app->formatter->asShortSize($status->getStringsInfo()['free_memory']), 76 | 'value' => $status->getStringsInfo()['free_memory'], 77 | ], 78 | ], 79 | ] 80 | ); 81 | echo insolita\opcache\widgets\PieWidget::widget( 82 | [ 83 | 'functionName' => 'drawHitsChart', 84 | 'options' => ['style' => 'width:600px;height:400px;','id'=>'hitsChart'], 85 | 'clientOptions' => [ 86 | 'title' => Translator::t('hits_misses'), 87 | 'tooltip' => ['text' => 'percentage'], 88 | 'legend' => ['position' => 'right'], 89 | 'slices' => [ 90 | 0=>['color'=>'green'], 91 | 1=>['color'=>'blue'], 92 | 2=>['color'=>'pink'] 93 | ], 94 | 'pieHole'=> 0.4, 95 | ], 96 | 'data' => [ 97 | ['label'=>'Hits','value'=>'Misses'], 98 | 99 | [ 100 | 'label' => Translator::status('hits') 101 | . ' - ' . $status->getStatistics()['hits'], 102 | 'value' => $status->getStatistics()['hits'], 103 | ], 104 | [ 105 | 'label' => Translator::status('misses') 106 | . ' - ' . $status->getStatistics()['misses'], 107 | 'value' => $status->getStatistics()['misses'], 108 | ], 109 | [ 110 | 'label' => Translator::status('blacklist_misses') 111 | . ' - ' . $status->getStatistics()['blacklist_misses'], 112 | 'value' => $status->getStatistics()['blacklist_misses'], 113 | ], 114 | ], 115 | ] 116 | ); 117 | -------------------------------------------------------------------------------- /src/views/default/_menu.php: -------------------------------------------------------------------------------- 1 | 'opcache_nav_menu', 6 | 'options' => ['class'=>'nav nav-tabs'], 7 | 'encodeLabels'=>false, 8 | 'items' => [ 9 | [ 10 | 'label'=>Translator::t('status'), 11 | 'url'=>['/opcache/default/index'] 12 | ], 13 | [ 14 | 'label'=>Translator::t('config'), 15 | 'url'=>['/opcache/default/config'] 16 | ], 17 | [ 18 | 'label'=>Translator::t('file_list'), 19 | 'url'=>['/opcache/default/files'] 20 | ], 21 | [ 22 | 'label'=>Translator::t('black_list'), 23 | 'url'=>['/opcache/default/black'] 24 | ], 25 | [ 26 | 'label'=>Translator::t('reset'), 27 | 'url'=>['/opcache/default/reset'] 28 | ], 29 | ] 30 | ]); -------------------------------------------------------------------------------- /src/views/default/blacklist.php: -------------------------------------------------------------------------------- 1 | 10 |
11 |
12 |
13 |
14 |
15 | render('_menu')?> 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
21 | 22 |
30 | 31 |
32 |
33 | 34 | -------------------------------------------------------------------------------- /src/views/default/config.php: -------------------------------------------------------------------------------- 1 | title = $version; 14 | 15 | ?> 16 | 17 |
18 |
19 |
20 |
21 |
22 | render('_menu')?> 23 | '', 26 | 'dataProvider' => $directives, 27 | 'layout' => '{items}', 28 | 'columns' => [ 29 | [ 30 | 'attribute' => 'option', 31 | 'format' => 'raw', 32 | 'value' => function ($model) { 33 | return Html::tag('b', $model['option']); 34 | }, 35 | 'header' => Translator::t('option'), 36 | ], 37 | [ 38 | 'attribute' => 'value', 39 | 'format' => 'raw', 40 | 'header' => Translator::t('value'), 41 | ], 42 | [ 43 | 'attribute' => 'hint', 44 | 'format' => 'raw', 45 | 'header' => Translator::t('hint'), 46 | ], 47 | ], 48 | ] 49 | )?> 50 |
51 |
52 | -------------------------------------------------------------------------------- /src/views/default/files.php: -------------------------------------------------------------------------------- 1 | title = $version; 14 | 15 | ?> 16 | 17 |
18 |
19 |
20 |
21 |
22 | render('_menu') ?> 23 | $searchModel, 26 | 'dataProvider' => $provider, 27 | 'layout' => "{summary}{pager}\n{items}\n{pager}", 28 | 'columns' => [ 29 | [ 30 | 'class' => \yii\grid\ActionColumn::class, 31 | 'buttons' => [ 32 | 'flush' => function ($url, $model) { 33 | return \yii\helpers\Html::a( 34 | Translator::t('invalidate'), 35 | ['invalidate','file'=>$model['full_path']], 36 | [ 37 | 'data-method' => 'post', 38 | 'class' => 'btn btn-default btn-sm', 39 | ] 40 | ); 41 | }, 42 | ], 43 | 'template' => '{flush}', 44 | ], 45 | [ 46 | 'attribute' => 'full_path', 47 | 'format' => 'raw', 48 | 'label' => Translator::t('full_path'), 49 | ], 50 | [ 51 | 'attribute' => 'hits', 52 | 'label' => Translator::t('hits'), 53 | ], 54 | [ 55 | 'attribute' => 'memory_consumption', 56 | 'format' => 'size', 57 | 'label' => Translator::t('memory_consumption'), 58 | ], 59 | [ 60 | 'attribute' => 'timestamp', 61 | 'format' => 'datetime', 62 | 'label' => Translator::t('file_timestamp'), 63 | ], 64 | [ 65 | 'attribute' => 'last_used_timestamp', 66 | 'format' => 'datetime', 67 | 'label' => Translator::t('last_used_timestamp'), 68 | ], 69 | 70 | ], 71 | ] 72 | ); ?> 73 |
74 | full_path) && $provider->getTotalCount()>1):?> 75 | 82 | 83 |
84 | -------------------------------------------------------------------------------- /src/views/default/index.php: -------------------------------------------------------------------------------- 1 | title = $version; 12 | ?> 13 | 14 |
15 |
16 |
17 |
18 |
19 | render('_menu') ?> 20 |
21 |
22 | 23 | 24 | 25 | 26 | 27 | 31 | 35 | 39 | 43 | 44 | 45 | 48 | 51 | 54 | 57 | 58 | 59 | 60 | 61 | 62 | getMemoryUsage() as $key => $value): ?> 63 | 67 | 68 | 69 | 70 | getMemoryUsage() as $key => $value): ?> 71 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | getStringsInfo() as $key => $value): ?> 81 | 82 | 86 | 87 | 88 | 89 | getStringsInfo() as $key => $value): ?> 90 | 91 | 94 | 95 | 96 | 97 |
28 | 29 |
opcache_enabled
30 |
32 | 33 |
cache_full
34 |
36 | 37 |
restart_pending
38 |
40 | 41 |
restart_in_progress
42 |
46 | formatter->asBoolean($status->getOpcacheEnabled()) ?> 47 | 49 | formatter->asBoolean($status->getCacheFull()) ?> 50 | 52 | formatter->asBoolean($status->getRestartPending()) ?> 53 | 55 | formatter->asBoolean($status->getRestartInProgress()) ?> 56 |
64 | 65 |
66 |
72 | formatMemory($value, $key) ?> 73 |
83 | 84 |
85 |
92 | formatMemory($value, $key) ?> 93 |
98 | 99 | 100 | getStatistics() as $key => $value): ?> 101 | 102 | 106 | 109 | 110 | 111 |
103 | 104 |
105 |
107 | formatStatistic($value, $key) ?> 108 |
112 |
113 |
114 | render('_charts', ['status' => $status]) ?> 115 |
116 |
117 |
118 |
119 | -------------------------------------------------------------------------------- /src/widgets/PieWidget.php: -------------------------------------------------------------------------------- 1 | 'The label','value'=>'The value'] 33 | **/ 34 | public $data = []; 35 | 36 | /** 37 | * @throws \yii\base\InvalidConfigException 38 | */ 39 | public function init() 40 | { 41 | if (empty($this->data)||!$this->functionName) { 42 | throw new InvalidConfigException(); 43 | } 44 | if (!isset($this->options['id'])) { 45 | $this->options['id'] = 'memoryChart'; 46 | } 47 | if (!isset($this->options['style'])) { 48 | $this->options['style'] = 'width:500px;height:400px'; 49 | } 50 | parent::init(); 51 | $this->registerHeadScript(); 52 | $this->registerScript($this->options['id'], 53 | $this->functionName, 54 | Json::encode($this->clientOptions), 55 | $this->prepareData($this->data)); 56 | } 57 | 58 | /** 59 | * @return string 60 | */ 61 | public function run() 62 | { 63 | return Html::tag('div', '', $this->options); 64 | } 65 | 66 | /** 67 | * 68 | */ 69 | private function registerHeadScript() 70 | { 71 | $this->getView()->registerJsFile( 72 | 'https://www.gstatic.com/charts/loader.js', 73 | ['position' => View::POS_HEAD], 74 | 'google_chart' 75 | ); 76 | $this->getView()->registerJs( 77 | "google.charts.load('current', {'packages':['corechart']});", 78 | View::POS_HEAD, 79 | 'google_chart_package' 80 | ); 81 | } 82 | 83 | /** 84 | * @param $data 85 | * 86 | * @return string 87 | */ 88 | private function prepareData($data) 89 | { 90 | $chartData = [ 91 | ]; 92 | foreach ($data as $row) { 93 | $chartData[] = [$row['label'], $row['value']]; 94 | } 95 | unset($data); 96 | return Json::encode($chartData); 97 | } 98 | 99 | /** 100 | * @param $selector 101 | * @param $functionName 102 | * @param $options 103 | * @param $data 104 | */ 105 | private function registerScript($selector, $functionName, $options, $data) 106 | { 107 | $js 108 | = <<getView()->registerJs($js, View::POS_HEAD); 123 | } 124 | } 125 | --------------------------------------------------------------------------------