From a5143e22f99124744e00c4b0a378a1e26d9b15ba Mon Sep 17 00:00:00 2001 From: webeweb Date: Tue, 17 May 2022 12:06:57 +0200 Subject: [PATCH] Update OSHelper: - add getCpu() --- src/core/Helper/OSHelper.php | 30 ++++++++++++++++++++++++++++++ tests/core/Helper/OSHelperTest.php | 19 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/core/Helper/OSHelper.php b/src/core/Helper/OSHelper.php index 9e605728c..7c08e2854 100644 --- a/src/core/Helper/OSHelper.php +++ b/src/core/Helper/OSHelper.php @@ -11,6 +11,7 @@ namespace WBW\Library\Core\Helper; +use WBW\Library\Core\Model\Cpu; use WBW\Library\Core\Model\Memory; /** @@ -21,6 +22,35 @@ */ class OSHelper { + /** + * Get the CPU. + * + * @return Cpu|null Returns the CPU. + */ + public static function getCpu(): ?Cpu { + + if (true === static::isWindows()) { + return null; + } + + $grep = "%Cpu(s):"; + exec("top -b -n 1 |grep '$grep'", $output); + + preg_match_all("/[0-9.]+/", $output[0], $values); + + $cpu = new Cpu(); + $cpu->setUs(floatval(trim($values[0][0]))); + $cpu->setSy(floatval(trim($values[0][1]))); + $cpu->setNi(floatval(trim($values[0][2]))); + $cpu->setId(floatval(trim($values[0][3]))); + $cpu->setWa(floatval(trim($values[0][4]))); + $cpu->setHi(floatval(trim($values[0][5]))); + $cpu->setSi(floatval(trim($values[0][6]))); + $cpu->setSt(floatval(trim($values[0][7]))); + + return $cpu; + } + /** * Get the memory. * diff --git a/tests/core/Helper/OSHelperTest.php b/tests/core/Helper/OSHelperTest.php index 8535759fa..a6e9c2116 100644 --- a/tests/core/Helper/OSHelperTest.php +++ b/tests/core/Helper/OSHelperTest.php @@ -22,6 +22,25 @@ */ class OSHelperTest extends AbstractTestCase { + /** + * Tests getCpu() + * + * @return void + */ + public function testGetCpu(): void { + + $obj = OSHelper::getCpu(); + + $this->assertGreaterThanOrEqual(0, $obj->getUs()); + $this->assertGreaterThanOrEqual(0, $obj->getSy()); + $this->assertGreaterThanOrEqual(0, $obj->getNi()); + $this->assertGreaterThanOrEqual(0, $obj->getId()); + $this->assertGreaterThanOrEqual(0, $obj->getWa()); + $this->assertGreaterThanOrEqual(0, $obj->getHi()); + $this->assertGreaterThanOrEqual(0, $obj->getSi()); + $this->assertGreaterThanOrEqual(0, $obj->getST()); + } + /** * Tests getMemory() *