Skip to content

Commit 50fa77e

Browse files
jrfnlschlessera
andcommitted
Runner: show actionable information when PHPCS runs out of memory
As discussed in 3621, this PR adds a new function to show a "friendly" error message if/when PHPCS runs out of memory. This functionality can't be tested via the unit/integration test suite as the PHP shutdown can't be mocked. To test the functionality, I used a test run of PHPCS over its own code base with the following command: ```bash phpcs -d memory_limit 32M ``` Fixes 3621 Co-authored-by: Alain Schlesser <[email protected]>
1 parent f3a8342 commit 50fa77e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/Runner.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ class Runner
5353
*/
5454
public function runPHPCS()
5555
{
56+
$this->register_out_of_memory_shutdown_message('phpcs');
57+
5658
try {
5759
Util\Timing::startTiming();
5860
Runner::checkRequirements();
@@ -153,6 +155,8 @@ public function runPHPCS()
153155
*/
154156
public function runPHPCBF()
155157
{
158+
$this->register_out_of_memory_shutdown_message('phpcbf');
159+
156160
if (defined('PHP_CODESNIFFER_CBF') === false) {
157161
define('PHP_CODESNIFFER_CBF', true);
158162
}
@@ -886,4 +890,42 @@ public function printProgress(File $file, $numFiles, $numProcessed)
886890
}//end printProgress()
887891

888892

893+
/**
894+
* Registers a PHP shutdown function to provide a more informative out of memory error.
895+
*
896+
* @param string $command The command which was used to initiate the PHPCS run.
897+
*
898+
* @return void
899+
*/
900+
private function register_out_of_memory_shutdown_message($command)
901+
{
902+
// Allocate all needed memory beforehand as much as possible.
903+
$errorMsg = PHP_EOL.'The PHP_CodeSniffer "%1$s" command ran out of memory.'.PHP_EOL;
904+
$errorMsg .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime'.PHP_EOL;
905+
$errorMsg .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).'.PHP_EOL;
906+
$errorMsg = sprintf($errorMsg, $command);
907+
$memoryError = 'Allowed memory size of';
908+
$errorArray = [
909+
'type' => 42,
910+
'message' => 'Some random dummy string to take up memory and take up some more memory and some more',
911+
'file' => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files',
912+
'line' => 31427,
913+
];
914+
915+
register_shutdown_function(
916+
static function () use (
917+
$errorMsg,
918+
$memoryError,
919+
$errorArray
920+
) {
921+
$errorArray = error_get_last();
922+
if (is_array($errorArray) === true && strpos($errorArray['message'], $memoryError) !== false) {
923+
echo $errorMsg;
924+
}
925+
}
926+
);
927+
928+
}//end register_out_of_memory_shutdown_message()
929+
930+
889931
}//end class

0 commit comments

Comments
 (0)