From 2c088b8821d2e1da8fdb93a559c3664d71781d41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20FIDRY?= <5175937+theofidry@users.noreply.github.com> Date: Sun, 4 Dec 2022 18:20:38 +0100 Subject: [PATCH] Fix handling of invalid values for the HwFinder and WindowsWmic finder (#22) --- src/HwFinder.php | 8 +++++++- src/WindowsWmicFinder.php | 8 +++++++- tests/HwFinderTest.php | 15 +++++++++++++++ tests/WindowsWmicTest.php | 15 +++++++++++++++ 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/src/HwFinder.php b/src/HwFinder.php index 052657d..80992f5 100644 --- a/src/HwFinder.php +++ b/src/HwFinder.php @@ -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. @@ -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; } } diff --git a/src/WindowsWmicFinder.php b/src/WindowsWmicFinder.php index 0cf9f22..418f982 100644 --- a/src/WindowsWmicFinder.php +++ b/src/WindowsWmicFinder.php @@ -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. @@ -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; } } diff --git a/tests/HwFinderTest.php b/tests/HwFinderTest.php index 4e3ac71..0bc6e9e 100644 --- a/tests/HwFinderTest.php +++ b/tests/HwFinderTest.php @@ -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' @@ -45,5 +52,13 @@ public static function processProvider(): iterable EOF, 3, ]; + + yield 'no processor' => [ + <<<'EOF' + 0 + + EOF, + null, + ]; } } diff --git a/tests/WindowsWmicTest.php b/tests/WindowsWmicTest.php index c6120ab..a96b8a9 100644 --- a/tests/WindowsWmicTest.php +++ b/tests/WindowsWmicTest.php @@ -37,6 +37,13 @@ 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 @@ -44,5 +51,13 @@ public static function wmicProvider(): iterable EOF, 3, ]; + + yield 'no processor' => [ + <<<'EOF' + 0 + + EOF, + null, + ]; } }