Created
August 20, 2013 22:08
-
-
Save mishak87/6287984 to your computer and use it in GitHub Desktop.
I was tired of writing the same batch code all over again. At some point in the future this will be part of rixxi/basics or not...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Rixxi\Utils; | |
class Batch implements \ArrayAccess | |
{ | |
/** @var int */ | |
private $limit; | |
/** @var int */ | |
private $counter = 0; | |
/** @var callable */ | |
private $callback; | |
/** @var array */ | |
private $values = []; | |
/** @var bool */ | |
private $finished = FALSE; | |
/** | |
* @param callable $callback | |
* @param int $limit | |
*/ | |
public function __construct(callable $callback, $limit = 9000) | |
{ | |
$this->callback = $callback; | |
$this->limit = $limit; | |
} | |
public function finish() | |
{ | |
if ($this->finished) { | |
throw new \Exception("Batch has already finished."); | |
} | |
call_user_func($this->callback, $this->values); | |
$this->values = []; | |
} | |
public function offsetSet($index, $value) | |
{ | |
if ($index !== NULL) { | |
$this->unsupportedAccess(); | |
} | |
$this->values[] = $value; | |
if (++$this->counter === $this->limit) { | |
call_user_func($this->callback, $this->values); | |
$this->values = []; | |
$this->counter = 0; | |
} | |
} | |
public function offsetGet($index) | |
{ | |
$this->unsupportedAccess(); | |
} | |
public function offsetExists($index) | |
{ | |
$this->unsupportedAccess(); | |
} | |
public function offsetUnset($index) | |
{ | |
$this->unsupportedAccess(); | |
} | |
private function unsupportedAccess() | |
{ | |
throw new \RuntimeException("You can only append to batch."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment