Skip to content

Commit

Permalink
Consolidate HwFinder (#23)
Browse files Browse the repository at this point in the history
- Move the `popen` function check instead of relying on the `CpuCoreCounter`'s `proc_open` check.
- Refactor `HwFinder::find()` for better readability
- Handle potential `fgets` `false` value returned
  • Loading branch information
theofidry authored Dec 4, 2022
1 parent 2c088b8 commit 2114c6e
Showing 1 changed file with 14 additions and 7 deletions.
21 changes: 14 additions & 7 deletions src/HwFinder.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use function fgets;
use function filter_var;
use function function_exists;
use function is_int;
use function is_resource;
use function pclose;
Expand All @@ -35,17 +36,23 @@ final class HwFinder implements CpuCoreFinder
*/
public function find(): ?int
{
$process = popen('sysctl -n hw.ncpu', 'rb');
if (!function_exists('popen')) {
return null;
}

if (is_resource($process)) {
// *nix (Linux, BSD and Mac)
$cores = self::countCpuCores(fgets($process));
pclose($process);
// -n to show only the variable value
$process = popen('sysctl -n hw.ncpu', 'rb');

return $cores;
if (!is_resource($process)) {
return null;
}

return null;
$processResult = fgets($process);
pclose($process);

return false === $processResult
? null
: self::countCpuCores($processResult);
}

/**
Expand Down

0 comments on commit 2114c6e

Please sign in to comment.