From 41d41c91a8c5e7734f6ec450b602c60b40c5f1f7 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Fri, 29 Jun 2018 13:58:11 -0700 Subject: [PATCH] (dev/core#217) CRM_Core_DAO - Add a helper which returns results in generator format --- CRM/Core/DAO.php | 23 +++++++++++++++++++++++ tests/phpunit/CRM/Core/DAOTest.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/CRM/Core/DAO.php b/CRM/Core/DAO.php index b4d07e75ad..3416e61a70 100644 --- a/CRM/Core/DAO.php +++ b/CRM/Core/DAO.php @@ -1114,6 +1114,29 @@ FROM civicrm_domain return $result; } + /** + * Return the results as PHP generator. + * + * @param string $type + * Whether the generator yields 'dao' objects or 'array's. + */ + public function fetchGenerator($type = 'dao') { + while ($this->fetch()) { + switch ($type) { + case 'dao': + yield $this; + break; + + case 'array': + yield $this->toArray(); + break; + + default: + throw new \RuntimeException("Invalid record type ($type)"); + } + } + } + /** * Returns a singular value. * diff --git a/tests/phpunit/CRM/Core/DAOTest.php b/tests/phpunit/CRM/Core/DAOTest.php index 9cf423c73a..2d362709f7 100644 --- a/tests/phpunit/CRM/Core/DAOTest.php +++ b/tests/phpunit/CRM/Core/DAOTest.php @@ -422,6 +422,34 @@ class CRM_Core_DAOTest extends CiviUnitTestCase { return $constants; } + public function testFetchGeneratorDao() { + $this->individualCreate([], 0); + $this->individualCreate([], 1); + $this->individualCreate([], 2); + $count = 0; + $g = CRM_Core_DAO::executeQuery('SELECT contact_type FROM civicrm_contact WHERE contact_type = "Individual" LIMIT 3') + ->fetchGenerator(); + foreach ($g as $row) { + $this->assertEquals('Individual', $row->contact_type); + $count++; + } + $this->assertEquals(3, $count); + } + + public function testFetchGeneratorArray() { + $this->individualCreate([], 0); + $this->individualCreate([], 1); + $this->individualCreate([], 2); + $count = 0; + $g = CRM_Core_DAO::executeQuery('SELECT contact_type FROM civicrm_contact WHERE contact_type = "Individual" LIMIT 3') + ->fetchGenerator('array'); + foreach ($g as $row) { + $this->assertEquals('Individual', $row['contact_type']); + $count++; + } + $this->assertEquals(3, $count); + } + /** * @dataProvider serializationMethods */ -- 2.25.1