Test Failed
Push — master ( dd3b22...212393 )
by Jean-Christophe
03:19
created

AbstractBulks::execGroupTrans()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 12
ccs 0
cts 11
cp 0
rs 9.9666
cc 3
nc 5
nop 1
crap 12
1
<?php
2
3
namespace Ubiquity\orm\bulk;
4
5
use Ubiquity\orm\OrmUtils;
6
use Ubiquity\orm\DAO;
7
use Ubiquity\log\Logger;
8
use Ubiquity\controllers\Startup;
9
10
/**
11
 * Ubiquity\orm\bulk$AbstractBulks
12
 * This class is part of Ubiquity
13
 *
14
 * @author jcheron <[email protected]>
15
 * @version 1.0.0
16
 *
17
 */
18
abstract class AbstractBulks {
19
	protected $class;
20
	protected $pkName;
21
	protected $fields;
22
	protected $db;
23
	protected $instances = [ ];
24
	protected $parameters;
25
	protected $dbType;
26
	protected $insertFields;
27
28
	protected function getQuotedKeys($fields, $quote) {
29
		$ret = array ();
30
		foreach ( $fields as $field ) {
31
			$ret [] = $quote . $field . $quote;
32
		}
33
		return $ret;
34
	}
35
36
	protected function updateInstanceRest($instance) {
37
		foreach ( $this->fields as $field ) {
38
			$accessor = 'get' . \ucfirst ( $field );
39
			$instance->_rest [$field] = $instance->$accessor ();
40
		}
41
	}
42
43
	protected function execGroupTrans($sql) {
44
		while ( true ) {
45
			try {
46
				$this->db->beginTransaction ();
47
				$this->db->execute ( $sql );
48
				$this->db->commit ();
49
				return true;
50
			} catch ( \Exception $e ) {
51
				$this->db->rollBack ();
52
			}
53
		}
54
		return false;
55
	}
56
57
	public function __construct($className) {
58
		$this->class = $className;
59
		$this->pkName = OrmUtils::getFirstKey ( $className );
60
		$this->fields = OrmUtils::getSerializableFields ( $className );
61
		$this->db = DAO::getDb ( $className );
62
		$this->dbType = $this->db->getDbType ();
63
	}
64
65
	public function addInstances($instances) {
66
		foreach ( $instances as $instance ) {
67
			$this->addInstance ( $instance );
68
		}
69
	}
70
71
	public abstract function addInstance($instance);
72
73
	public abstract function createSQL();
74
75
	public function flush() {
76
		$statement = $this->db->getUpdateStatement ( $this->createSQL () );
77
		while ( true ) {
78
			try {
79
				$result = $statement->execute ( $this->parameters );
80
				if ($result !== false) {
81
					$this->instances = [ ];
82
					$this->parameters = [ ];
83
					return $result;
84
				}
85
			} catch ( \Exception $e ) {
86
				Logger::warn ( "DAOBulkUpdates", $e->getMessage (), \get_class ( $this ) );
87
				if ($e->errorInfo [0] == 40001 && $this->db->getDbType () == 'mysql' && $e->errorInfo [1] == 1213) {
88
					echo "deadlock";
89
				} else {
90
					if (Startup::$config ['debug']) {
91
						throw $e;
92
					}
93
				}
94
			}
95
		}
96
		return false;
97
	}
98
}
99
100