Skip to content

Commit

Permalink
Fix handling of invalid values for the HwFinder and WindowsWmic finder (
Browse files Browse the repository at this point in the history
  • Loading branch information
theofidry authored Dec 4, 2022
1 parent f01ffc5 commit 2c088b8
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
8 changes: 7 additions & 1 deletion src/HwFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
namespace Fidry\CpuCounter;

use function fgets;
use function filter_var;
use function is_int;
use function is_resource;
use function pclose;
use function popen;
use function trim;
use const FILTER_VALIDATE_INT;

/**
* Find the number of CPU cores for Linux, BSD and OSX.
Expand Down Expand Up @@ -51,6 +55,8 @@ public function find(): ?int
*/
public static function countCpuCores(string $process): ?int
{
return (int) $process;
$cpuCount = filter_var(trim($process), FILTER_VALIDATE_INT);

return is_int($cpuCount) && $cpuCount > 0 ? $cpuCount : null;
}
}
8 changes: 7 additions & 1 deletion src/WindowsWmicFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
namespace Fidry\CpuCounter;

use function fgets;
use function filter_var;
use function is_int;
use function is_resource;
use function pclose;
use function popen;
use function trim;
use const FILTER_VALIDATE_INT;

/**
* Find the number of CPU cores for Windows.
Expand Down Expand Up @@ -51,6 +55,8 @@ public function find(): ?int
*/
public static function countCpuCores(string $process): ?int
{
return (int) $process;
$cpuCount = filter_var(trim($process), FILTER_VALIDATE_INT);

return is_int($cpuCount) && $cpuCount > 0 ? $cpuCount : null;
}
}
15 changes: 15 additions & 0 deletions tests/HwFinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ public function test_it_can_count_the_number_of_cpu_cores(

public static function processProvider(): iterable
{
yield 'empty' => [
<<<'EOF'

EOF,
null,
];

// MyMachine™
yield 'example from an OSX machine' => [
<<<'EOF'
Expand All @@ -45,5 +52,13 @@ public static function processProvider(): iterable
EOF,
3,
];

yield 'no processor' => [
<<<'EOF'
0

EOF,
null,
];
}
}
15 changes: 15 additions & 0 deletions tests/WindowsWmicTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,27 @@ public function test_it_can_count_the_number_of_cpu_cores(

public static function wmicProvider(): iterable
{
yield 'empty' => [
<<<'EOF'

EOF,
null,
];

yield 'example from a Windows machine' => [
<<<'EOF'
3

EOF,
3,
];

yield 'no processor' => [
<<<'EOF'
0

EOF,
null,
];
}
}

0 comments on commit 2c088b8

Please sign in to comment.