📜 ⬆️ ⬇️

PHPDump - Debugging in the Google Chrome console and interacting with CMS MODX

Immediately to the point


There is a proprietary product that successfully helps me in debugging and called it PhpDump .


At one time, CMS MODX prompted me to write my debugger. Of course there are var_dump, phpConsole, xDebug in PHP. But here I am with my PhpDump .


I will say that the solution is not perfect, but very practical.


How much you like, you decide.


Here are some screenshots of what it looks like.




The article will tell how to install and use it in CMS MODX Revo


Requirements


Apache + PHP 7, CMS MODX Revo 2.7
Git + composer


Download and install



Create a directory for PhpDump separately from your projects. Since you may want to use it on a local server in different projects. To do this, it is not necessary to install it everywhere.


In the directory, create a file composer.json with the following data:


 { "require":{ "Alpa/PhpDump":"1.*" }, "repositories": [ { "type": "git", "url": "https://github.com/ALexeyP0708/PhpDump.git" }, { "type": "git", "url": "https://github.com/ALexeyP0708/EntityDetails" } ] } 

In the terminal, enter $ composer install


When installing via composer, the project will be located in the [directory install]/vendor/PhpDump



Or unzip the archive.


you can download it here GitHub


Install PhpDumpConsole


In Google Chrome, go to the Extensions section, turn on the developer mode (in the upper right corner), then Загрузить распакованное расширение .


Specify the directory [directory PhpDump]/ChromeExtension/PhpDumpConsole_v1.1 .


A red icon will appear in the panel in the form of a gear wheel in a circle. If by pressing the gear does not turn blue, then either the server does not support PhpDump or the client has not passed authorization.


Health check


read the file [dirictory Php Dump]/tests/test_debugManager.php


If installed via a composer, then you need to specify the correct route to the autoloader file.


To do this, replace the line


  include_once __DIR__.'/../vendor/autoload.php'; 

on


  //include_once __DIR__.'/../vendor/autoload.php'; include_once __DIR__.'/../../../autoload.php'; 

The directory where PhpDump is installed should have web access and free routing to scripts.


Suppose you installed PhpDump in /sites/www/mysite/TestPhpDump and web access to the site http://mysite/ then to run the test script
http://mysite/TestPhpDump/tests/test_debugManager.php


The page with the generated errors will be launched. Launch the Google Chrome console and click the gear in the application bar. The page will reload, the gear will turn blue. All information is now displayed in the console.


How to run on your project


At the beginning of the page that runs the script for your project, you must specify:


  include_once '[directory phpdump]/vendor/autoload.php';//ваш путь до phpdump абсолютный или относительный. new PhpDump\InitDump(); 

You need to understand that PhpDump runs in the script where the given lines are declared.
You also need to take into account the fact that PHPdumpConsole displays a dump not only for the main page, but also for ajax requests and for front-end scripts generated by the server dynamically.


If your project accesses erratically to different scenarios (for example, the page was loaded via Index.php, and the ajax request was made via other.php or the browser loads the dynamic js script from script.js.php), then unexpected situations may occur.


In such a case, it is necessary that all routing go through one script startup file. For example, via /index.php. Or apply additional solutions, as was done with MODX (Described below).


Run on a test site with CMS MODX


To run PhpDump on CMS MODX there are several solutions.


The first Solution - according to the instructions above, write the code in the file index.php of your site:


  include_once '[directory phpdump]/vendor/autoload.php'; new PhpDump\InitDump(); 

In this case, PhpDump will work in debugging and error trapping mode.


But all that will appear in the MODX logs, as well as errors that are suppressed by the system,
will not be displayed in phpdumpconsole


The second option: Official - without making customization. This is an extension of the ErrorHandler class and setting the corresponding variables in the MODX parameters.


This solution has a flaw. If you make incorrect data in the settings, the site crashes. And the situation can be corrected only through the Database.


Therefore, the description of this option is omitted.


In this version, you can see all generated PHP errors. But you will not see the generated logs, which contain a significant part of the errors MODX.


The third option, which I personally stopped at, is to install the full routing of calls to scripts via the 'dev_route.php' file;
With .htaccess, all non-static downloads are directed to the dev_route.php file.


ATTENTION: Behavior is not investigated until the end. Perhaps some applications may offer different logic of requests to the site, the routing of which is not described in dev_route.php.


ATTENTION: .htaccess is not written to the end. Not all static resources are defined in it. Therefore, will be processed in dev_route.php
Make backup .htaccess file old.
Create a new .htaccess in the root directory of the site and enter the code:


 # file .htaccess #---------------------------------------- # Деактивируем запросы к не существующим файлам каталогов статического ресурса. - Иначе сайт их будет обрабатывать как полноценный запрос. RewriteCond %{REQUEST_URI} /manager/min/assets/.* RewriteCond %{REQUEST_FILENAME} !-f [OR] RewriteCond %{REQUEST_URI} /manager/assets/.* RewriteCond %{REQUEST_FILENAME} !-f [OR] RewriteCond %{REQUEST_URI} /assets/.* RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ - [R=404,L] #--------------------------------------- #--------------------------------------- # здесь перечисляем каталоги статических ресурсов RewriteCond %{REQUEST_URI} /manager/min/assets/.* RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_URI} /manager/assets/.* RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_URI} /assets/.* RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteRule ^(.*)$ $1 [L] #--------------------------------------- #--------------------------------------- # здесь перечисляем расширение статических ресурсов c правом свободного доступа. RewriteCond %{REQUEST_FILENAME} .*\.js$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.html$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.css$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.gif$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.jpg$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.jpeg$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.png$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.svg$ [OR] RewriteCond %{REQUEST_FILENAME} .*\.woff$ RewriteRule ^(.*)$ $1 [L] #--------------------------------------- #--------------------------------------- # Перенаправляем запросы бекенда. RewriteCond %{REQUEST_URI} /manager(?:|/.*) RewriteRule ^(.*)$ dev_route.php [L] RewriteCond %{REQUEST_URI} /connectors(?:|/.*) RewriteRule ^(.*)$ dev_route.php [L] #--------------------------------------- #--------------------------------------- # Перенаправляем все остальные запросы. RewriteCond %{REQUEST_URI} .* RewriteRule ^(.*)$ dev_route.php?q=$1 [L,QSA] #--------------------------------------- 

Create the dev_route.php file in the root of the site directory and dev_route.php code into it:


 <?php include_once '[yor path php dump]/vendor/autoload.php';// Обязательно указываем путь к файлу автозагрузки классов new \Alpa\PhpDump\InitDump(); $redirect_url=$_SERVER['REDIRECT_URL']; $manager_path='manager'; $manager_dir='manager'; $connectors_path='connectors'; $connectors_dir='connectors'; if(preg_match("~^/{$manager_path}(|/[\s\S]*)$~",$redirect_url,$match)){ if(trim($match[1])=='' || trim($match[1])=='/' || !is_file(__DIR__.'/'.$manager_dir.$match[1])){ $match[1]='/index.php'; } include_once __DIR__.'/'.$manager_dir.$match[1]; } else if(preg_match("~^/{$connectors_path}(|/[\s\S]*)$~",$redirect_url,$match)){ if(trim($match[1])=='' || trim($match[1])=='/' || !is_file(__DIR__.'/'.$connectors_dir.$match[1])){ $match[1]='/index.php'; } include_once __DIR__.'/'.$connectors_dir.$match[1]; } else if(empty($redirect_url) || $redirect_url=='/' || $redirect_url=='/index.php'){ include_once __DIR__.'/index.php'; } else { //header( 'Location: /index.php' ); exit; include_once __DIR__.'/index.php'; } //include_once __DIR__.$redirect_url; 

Then in the core\xpdo\xpdo.class.php (for MODX revo 2.7) arrange the log method as follows:


  public function log($level, $msg, $target= '', $def= '', $file= '', $line= '') { \deb::print($msg."=>[$target][$def][$file][$line]",'LOG'); $this->_log($level, $msg, $target, $def, $file, $line); } 

And that's all. You have to earn everything properly.
We test in admin panel. if the admin is loading well, then everything is done as it should.


How to use:


 // выведет переменную любого типа. Рекурсивно предоставит все свойства объекта и массива \deb::print($var,'point1'); // Предоставит рекурсивно детальную информацию по объекту. \deb::dump($object,'point2'); // результат var_dump \deb::vdump($object,'point3'); //результат var_export \deb::vexport($object,'point4'); // информация о классе \deb::infoClass($name_class, 'point5'); // вывод ошибок Предназначен как правило для внутренних целей. при генерации ошибки системой. \deb::error($errno = false, $errstr, $errfile = false, $errline = false, $errcontext = false); //В лучшем случае вызывать ошибку стоит через trigger_error(); 

Security Settings


PhpDump is currently not designed for professional work, so security conditions are minimal.


If you decided to attach PhpDump to the current site on the Internet, then in the [directory phpdump] /src/include_file_in_index.php file, change the following settings for authorization:


 $settings=[ 'hashkeys'=>[ 'HashKey'=>[ // любой ключ в виде строки (латиница).Будет являться публичным ключём 'key'=>'HashKey', // дублируем строку ключа 'greeting_server'=>'greeting_server', // ключ в виде строки для авторизации на стороне сервера 'greeting_client'=>'greeting_client' // ключ для авторизации на стороне клиента. ] ] ]; 

On the client side, in the 'Java Scripts Context' drop-down list, select PhpDumpConsole and enter the code in the console.


 dm.setHashKey({ hashkey:'HashKey', greeting_server:'greeting_server', greeting_client:'greeting_client' }); //где параметры hashkey , greeting_server, greeting_client устанавливаете такие же как и на сервере. dm.bindHashKeyDomain({hashkey:'HashKey',domain:'global'}); // или domain:'your_domain' //если domain='global' будет применяться по умолчанию для всех сайтов к которым не установлена авторизация по другому ключу. 

Other buns


Through the console, you can control the on / off bektrays, filter output.
All this can be found in the instructions on the GitHub page.
PhpDump can be used not only for MODX, but also in other projects. The main thing is to know how to fasten.


PS: If you are fans of MODX, then in the near future a new bun is waiting for you: The method of forming snipet "Divide and Conquer". Snippets of logic and snippets of templates will be able to self-organize and group with each other, with the help of a combination of 2-3 snippets you can expand the behavior.


There is flexibility in writing snippets. Programmers will not need to describe the full cycle of writing a snippet, but only a separate part, describing its API for further interaction with other snippets.


Thanks to all.



Source: https://habr.com/ru/post/438088/