Skip to content

Instantly share code, notes, and snippets.

@wtw24
Created August 3, 2018 09:31
Show Gist options
  • Save wtw24/d40ef98c35fc1ea11fdfa142d02a13f5 to your computer and use it in GitHub Desktop.
Save wtw24/d40ef98c35fc1ea11fdfa142d02a13f5 to your computer and use it in GitHub Desktop.
RowIterator
<?php
class RowIterator
{
const STOP = 'stop_iteration';
private $db;
private $sqlQuery;
private $lastProcessCount;
private $processingFunction;
public function __construct($sqlQuery, $processingFunction, $db = null)
{
$this->sqlQuery = $sqlQuery;
$this->db = (!is_null($db)) ? $db : Db::getInstance();
}
public static function go($sqlQuery, $processingFunction, &$countRef = null, $db = null)
{
$instance = new self($sqlQuery, $processingFunction, $db);
$result = $instance->iterate();
$countRef = $instance->getLastProcessCount();
return $result;
}
public function iterate(callable $processingFunction = null)
{
$result = [];
if (!$processingFunction) {
$processingFunction = $this->processingFunction;
}
$dbResult = $this->db->query($this->sqlQuery);
$this->lastProcessCount = 0;
while ($row = $dbResult->fetch_assoc()) {
// array_walk($row, 'My_Function');
try {
$processingResult = call_user_func($processingFunction, $row);
if ($processingResult == self::STOP) {
break;
}
} catch (Exception $exception) {
// RowIteratorLog::error([$row, $exception]);
}
$this->lastProcessCount++;
}
}
public function getLastProcessCount()
{
return $this->lastProcessCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment