AutoTransactionBatchIterator   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 65
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A valid() 0 18 4
A commitIfInTransaction() 0 14 3
A next() 0 5 1
A __destruct() 0 8 2
1
<?php
2
3
namespace itertools;
4
5
use Exception;
6
use IteratorIterator;
7
use itertools\IterUtil;
8
use PDO;
9
10
11
class AutoTransactionBatchIterator extends IteratorIterator
12
{
13
	const START_TRANSACTION = -1;
14
15
	protected $batchSize;
16
	protected $pdo;
17
	protected $currentStep = self::START_TRANSACTION;
18
	protected $inTransaction = false;
19
20
	public function __construct($iterator, PDO $pdo, $batchSize = 100)
21
	{
22
		$this->batchSize = $batchSize;
23
		$this->pdo = $pdo;
24
		parent::__construct(IterUtil::asTraversable($iterator));
25
	}
26
27
	public function valid()
28
	{
29
		$valid = parent::valid();
30
		if(! $valid) {
31
			$this->commitIfInTransaction();
32
			return false;
33
		}
34
		if($this->currentStep >= $this->batchSize) {
35
			$this->currentStep = self::START_TRANSACTION;
36
			$this->commitIfInTransaction();
37
		}
38
		if(self::START_TRANSACTION == $this->currentStep) {
39
			$this->pdo->beginTransaction();
40
			$this->inTransaction = true;
41
			$this->currentStep = 0;
42
		}
43
		return true;
44
	}
45
46
	public function commitIfInTransaction()
47
	{
48
		if(! $this->inTransaction) {
49
			return;
50
		}
51
		try {
52
			$this->pdo->commit();
53
			$this->inTransaction = false;
54
		} catch(Exception $e) {
55
			$this->pdo->rollBack();
56
			$this->inTransaction = false;
57
			throw $e;
58
		}
59
	}
60
61
	public function next()
62
	{
63
		$this->currentStep += 1;
64
		parent::next();
65
	}
66
67
	public function __destruct()
68
	{
69
		if(! $this->inTransaction) {
70
			return;
71
		}
72
		// this can only be destructed in transaction if exception occured
73
		$this->pdo->rollBack();
74
	}
75
}
76
77