Completed
Push — 4.3 ( 28cdbc )
by David
21:20 queued 01:32
created
src/Mouf/Database/TDBM/WeakrefObjectStorage.php 1 patch
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -31,117 +31,117 @@
 block discarded – undo
31 31
  */
32 32
 class WeakrefObjectStorage
33 33
 {
34
-    /**
35
-     * An array of fetched object, accessible via table name and primary key.
36
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
37
-     *
38
-     * @var array<string, WeakMap<string, TDBMObject>>
39
-     */
40
-    private $objects = array();
34
+	/**
35
+	 * An array of fetched object, accessible via table name and primary key.
36
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
37
+	 *
38
+	 * @var array<string, WeakMap<string, TDBMObject>>
39
+	 */
40
+	private $objects = array();
41 41
 
42
-    /**
43
-     * Every 10000 set in the dataset, we perform a cleanup to ensure the WeakRef instances
44
-     * are removed if they are no more valid.
45
-     * This is to avoid having memory used by dangling WeakRef instances.
46
-     *
47
-     * @var int
48
-     */
49
-    private $garbageCollectorCount = 0;
42
+	/**
43
+	 * Every 10000 set in the dataset, we perform a cleanup to ensure the WeakRef instances
44
+	 * are removed if they are no more valid.
45
+	 * This is to avoid having memory used by dangling WeakRef instances.
46
+	 *
47
+	 * @var int
48
+	 */
49
+	private $garbageCollectorCount = 0;
50 50
 
51
-    /**
52
-     * Sets an object in the storage.
53
-     *
54
-     * @param string $tableName
55
-     * @param string $id
56
-     * @param DbRow  $dbRow
57
-     */
58
-    public function set($tableName, $id, DbRow $dbRow)
59
-    {
60
-        $this->objects[$tableName][$id] = new \WeakRef($dbRow);
61
-        ++$this->garbageCollectorCount;
62
-        if ($this->garbageCollectorCount == 10000) {
63
-            $this->garbageCollectorCount = 0;
64
-            $this->cleanupDanglingWeakRefs();
65
-        }
66
-    }
51
+	/**
52
+	 * Sets an object in the storage.
53
+	 *
54
+	 * @param string $tableName
55
+	 * @param string $id
56
+	 * @param DbRow  $dbRow
57
+	 */
58
+	public function set($tableName, $id, DbRow $dbRow)
59
+	{
60
+		$this->objects[$tableName][$id] = new \WeakRef($dbRow);
61
+		++$this->garbageCollectorCount;
62
+		if ($this->garbageCollectorCount == 10000) {
63
+			$this->garbageCollectorCount = 0;
64
+			$this->cleanupDanglingWeakRefs();
65
+		}
66
+	}
67 67
 
68
-    /**
69
-     * Checks if an object is in the storage.
70
-     *
71
-     * @param string $tableName
72
-     * @param string $id
73
-     *
74
-     * @return bool
75
-     */
76
-    public function has($tableName, $id)
77
-    {
78
-        if (isset($this->objects[$tableName][$id])) {
79
-            if ($this->objects[$tableName][$id]->valid()) {
80
-                return true;
81
-            } else {
82
-                unset($this->objects[$tableName][$id]);
83
-            }
84
-        }
68
+	/**
69
+	 * Checks if an object is in the storage.
70
+	 *
71
+	 * @param string $tableName
72
+	 * @param string $id
73
+	 *
74
+	 * @return bool
75
+	 */
76
+	public function has($tableName, $id)
77
+	{
78
+		if (isset($this->objects[$tableName][$id])) {
79
+			if ($this->objects[$tableName][$id]->valid()) {
80
+				return true;
81
+			} else {
82
+				unset($this->objects[$tableName][$id]);
83
+			}
84
+		}
85 85
 
86
-        return false;
87
-    }
86
+		return false;
87
+	}
88 88
 
89
-    /**
90
-     * Returns an object from the storage (or null if no object is set).
91
-     *
92
-     * @param string $tableName
93
-     * @param string $id
94
-     *
95
-     * @return DbRow
96
-     */
97
-    public function get($tableName, $id)
98
-    {
99
-        if (isset($this->objects[$tableName][$id])) {
100
-            if ($this->objects[$tableName][$id]->valid()) {
101
-                return $this->objects[$tableName][$id]->get();
102
-            }
103
-        } else {
104
-            return;
105
-        }
106
-    }
89
+	/**
90
+	 * Returns an object from the storage (or null if no object is set).
91
+	 *
92
+	 * @param string $tableName
93
+	 * @param string $id
94
+	 *
95
+	 * @return DbRow
96
+	 */
97
+	public function get($tableName, $id)
98
+	{
99
+		if (isset($this->objects[$tableName][$id])) {
100
+			if ($this->objects[$tableName][$id]->valid()) {
101
+				return $this->objects[$tableName][$id]->get();
102
+			}
103
+		} else {
104
+			return;
105
+		}
106
+	}
107 107
 
108
-    /**
109
-     * Removes an object from the storage.
110
-     *
111
-     * @param string $tableName
112
-     * @param string $id
113
-     */
114
-    public function remove($tableName, $id)
115
-    {
116
-        unset($this->objects[$tableName][$id]);
117
-    }
108
+	/**
109
+	 * Removes an object from the storage.
110
+	 *
111
+	 * @param string $tableName
112
+	 * @param string $id
113
+	 */
114
+	public function remove($tableName, $id)
115
+	{
116
+		unset($this->objects[$tableName][$id]);
117
+	}
118 118
 
119
-    /**
120
-     * Applies the callback to all objects.
121
-     *
122
-     * @param callable $callback
123
-     */
124
-    public function apply(callable $callback)
125
-    {
126
-        foreach ($this->objects as $tableName => $table) {
127
-            foreach ($table as $id => $obj) {
128
-                if ($obj->valid()) {
129
-                    $callback($obj->get(), $tableName, $id);
130
-                } else {
131
-                    unset($this->objects[$tableName][$id]);
132
-                }
133
-            }
134
-        }
135
-    }
119
+	/**
120
+	 * Applies the callback to all objects.
121
+	 *
122
+	 * @param callable $callback
123
+	 */
124
+	public function apply(callable $callback)
125
+	{
126
+		foreach ($this->objects as $tableName => $table) {
127
+			foreach ($table as $id => $obj) {
128
+				if ($obj->valid()) {
129
+					$callback($obj->get(), $tableName, $id);
130
+				} else {
131
+					unset($this->objects[$tableName][$id]);
132
+				}
133
+			}
134
+		}
135
+	}
136 136
 
137
-    private function cleanupDanglingWeakRefs()
138
-    {
139
-        foreach ($this->objects as $tableName => $table) {
140
-            foreach ($table as $id => $obj) {
141
-                if (!$obj->valid()) {
142
-                    unset($this->objects[$tableName][$id]);
143
-                }
144
-            }
145
-        }
146
-    }
137
+	private function cleanupDanglingWeakRefs()
138
+	{
139
+		foreach ($this->objects as $tableName => $table) {
140
+			foreach ($table as $id => $obj) {
141
+				if (!$obj->valid()) {
142
+					unset($this->objects[$tableName][$id]);
143
+				}
144
+			}
145
+		}
146
+	}
147 147
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/ObjectBeanPropertyDescriptor.php 2 patches
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
     {
66 66
         // First, are there many column or only one?
67 67
         // If one column, we name the setter after it. Otherwise, we name the setter after the table name
68
-        if (count($this->foreignKey->getLocalColumns()) > 1) {
68
+        if (count($this->foreignKey->getLocalColumns())>1) {
69 69
             $name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
70 70
             if ($this->alternativeName) {
71 71
                 $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
@@ -78,8 +78,8 @@  discard block
 block discarded – undo
78 78
             if (strpos(strtolower($column), 'id_') === 0) {
79 79
                 $column = substr($column, 3);
80 80
             }
81
-            if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
82
-                $column = substr($column, 0, strlen($column) - 3);
81
+            if (strrpos(strtolower($column), '_id') === strlen($column)-3) {
82
+                $column = substr($column, 0, strlen($column)-3);
83 83
             }
84 84
             $name = TDBMDaoGenerator::toCamelCase($column);
85 85
             if ($this->alternativeName) {
Please login to merge, or discard this patch.
Indentation   +162 added lines, -162 removed lines patch added patch discarded remove patch
@@ -12,156 +12,156 @@  discard block
 block discarded – undo
12 12
  */
13 13
 class ObjectBeanPropertyDescriptor extends AbstractBeanPropertyDescriptor
14 14
 {
15
-    /**
16
-     * @var ForeignKeyConstraint
17
-     */
18
-    private $foreignKey;
19
-
20
-    /**
21
-     * @var SchemaAnalyzer
22
-     */
23
-    private $schemaAnalyzer;
24
-
25
-    public function __construct(Table $table, ForeignKeyConstraint $foreignKey, SchemaAnalyzer $schemaAnalyzer)
26
-    {
27
-        parent::__construct($table);
28
-        $this->foreignKey = $foreignKey;
29
-        $this->schemaAnalyzer = $schemaAnalyzer;
30
-    }
31
-
32
-    /**
33
-     * Returns the foreignkey the column is part of, if any. null otherwise.
34
-     *
35
-     * @return ForeignKeyConstraint|null
36
-     */
37
-    public function getForeignKey()
38
-    {
39
-        return $this->foreignKey;
40
-    }
41
-
42
-    /**
43
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
44
-     *
45
-     * @return null|string
46
-     */
47
-    public function getClassName()
48
-    {
49
-        return TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
50
-    }
51
-
52
-    /**
53
-     * Returns the param annotation for this property (useful for constructor).
54
-     *
55
-     * @return string
56
-     */
57
-    public function getParamAnnotation()
58
-    {
59
-        $str = '     * @param %s %s';
60
-
61
-        return sprintf($str, $this->getClassName(), $this->getVariableName());
62
-    }
63
-
64
-    public function getUpperCamelCaseName()
65
-    {
66
-        // First, are there many column or only one?
67
-        // If one column, we name the setter after it. Otherwise, we name the setter after the table name
68
-        if (count($this->foreignKey->getLocalColumns()) > 1) {
69
-            $name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
70
-            if ($this->alternativeName) {
71
-                $camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
72
-
73
-                $name .= 'By'.implode('And', $camelizedColumns);
74
-            }
75
-        } else {
76
-            $column = $this->foreignKey->getLocalColumns()[0];
77
-            // Let's remove any _id or id_.
78
-            if (strpos(strtolower($column), 'id_') === 0) {
79
-                $column = substr($column, 3);
80
-            }
81
-            if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
82
-                $column = substr($column, 0, strlen($column) - 3);
83
-            }
84
-            $name = TDBMDaoGenerator::toCamelCase($column);
85
-            if ($this->alternativeName) {
86
-                $name .= 'Object';
87
-            }
88
-        }
89
-
90
-        return $name;
91
-    }
92
-
93
-    /**
94
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
95
-     *
96
-     * @return bool
97
-     */
98
-    public function isCompulsory()
99
-    {
100
-        // Are all columns nullable?
101
-        $localColumnNames = $this->foreignKey->getLocalColumns();
102
-
103
-        foreach ($localColumnNames as $name) {
104
-            $column = $this->table->getColumn($name);
105
-            if ($column->getNotnull()) {
106
-                return true;
107
-            }
108
-        }
109
-
110
-        return false;
111
-    }
112
-
113
-    /**
114
-     * Returns true if the property has a default value.
115
-     *
116
-     * @return bool
117
-     */
118
-    public function hasDefault()
119
-    {
120
-        return false;
121
-    }
122
-
123
-    /**
124
-     * Returns the code that assigns a value to its default value.
125
-     *
126
-     * @return string
127
-     *
128
-     * @throws \TDBMException
129
-     */
130
-    public function assignToDefaultCode()
131
-    {
132
-        throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
133
-    }
134
-
135
-    /**
136
-     * Returns true if the property is the primary key.
137
-     *
138
-     * @return bool
139
-     */
140
-    public function isPrimaryKey()
141
-    {
142
-        $fkColumns = $this->foreignKey->getLocalColumns();
143
-        sort($fkColumns);
144
-
145
-        $pkColumns = $this->table->getPrimaryKeyColumns();
146
-        sort($pkColumns);
147
-
148
-        return $fkColumns == $pkColumns;
149
-    }
150
-
151
-    /**
152
-     * Returns the PHP code for getters and setters.
153
-     *
154
-     * @return string
155
-     */
156
-    public function getGetterSetterCode()
157
-    {
158
-        $tableName = $this->table->getName();
159
-        $getterName = $this->getGetterName();
160
-        $setterName = $this->getSetterName();
161
-
162
-        $referencedBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
163
-
164
-        $str = '    /**
15
+	/**
16
+	 * @var ForeignKeyConstraint
17
+	 */
18
+	private $foreignKey;
19
+
20
+	/**
21
+	 * @var SchemaAnalyzer
22
+	 */
23
+	private $schemaAnalyzer;
24
+
25
+	public function __construct(Table $table, ForeignKeyConstraint $foreignKey, SchemaAnalyzer $schemaAnalyzer)
26
+	{
27
+		parent::__construct($table);
28
+		$this->foreignKey = $foreignKey;
29
+		$this->schemaAnalyzer = $schemaAnalyzer;
30
+	}
31
+
32
+	/**
33
+	 * Returns the foreignkey the column is part of, if any. null otherwise.
34
+	 *
35
+	 * @return ForeignKeyConstraint|null
36
+	 */
37
+	public function getForeignKey()
38
+	{
39
+		return $this->foreignKey;
40
+	}
41
+
42
+	/**
43
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
44
+	 *
45
+	 * @return null|string
46
+	 */
47
+	public function getClassName()
48
+	{
49
+		return TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
50
+	}
51
+
52
+	/**
53
+	 * Returns the param annotation for this property (useful for constructor).
54
+	 *
55
+	 * @return string
56
+	 */
57
+	public function getParamAnnotation()
58
+	{
59
+		$str = '     * @param %s %s';
60
+
61
+		return sprintf($str, $this->getClassName(), $this->getVariableName());
62
+	}
63
+
64
+	public function getUpperCamelCaseName()
65
+	{
66
+		// First, are there many column or only one?
67
+		// If one column, we name the setter after it. Otherwise, we name the setter after the table name
68
+		if (count($this->foreignKey->getLocalColumns()) > 1) {
69
+			$name = TDBMDaoGenerator::toSingular(TDBMDaoGenerator::toCamelCase($this->foreignKey->getForeignTableName()));
70
+			if ($this->alternativeName) {
71
+				$camelizedColumns = array_map(['Mouf\\Database\\TDBM\\Utils\\TDBMDaoGenerator', 'toCamelCase'], $this->foreignKey->getLocalColumns());
72
+
73
+				$name .= 'By'.implode('And', $camelizedColumns);
74
+			}
75
+		} else {
76
+			$column = $this->foreignKey->getLocalColumns()[0];
77
+			// Let's remove any _id or id_.
78
+			if (strpos(strtolower($column), 'id_') === 0) {
79
+				$column = substr($column, 3);
80
+			}
81
+			if (strrpos(strtolower($column), '_id') === strlen($column) - 3) {
82
+				$column = substr($column, 0, strlen($column) - 3);
83
+			}
84
+			$name = TDBMDaoGenerator::toCamelCase($column);
85
+			if ($this->alternativeName) {
86
+				$name .= 'Object';
87
+			}
88
+		}
89
+
90
+		return $name;
91
+	}
92
+
93
+	/**
94
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
95
+	 *
96
+	 * @return bool
97
+	 */
98
+	public function isCompulsory()
99
+	{
100
+		// Are all columns nullable?
101
+		$localColumnNames = $this->foreignKey->getLocalColumns();
102
+
103
+		foreach ($localColumnNames as $name) {
104
+			$column = $this->table->getColumn($name);
105
+			if ($column->getNotnull()) {
106
+				return true;
107
+			}
108
+		}
109
+
110
+		return false;
111
+	}
112
+
113
+	/**
114
+	 * Returns true if the property has a default value.
115
+	 *
116
+	 * @return bool
117
+	 */
118
+	public function hasDefault()
119
+	{
120
+		return false;
121
+	}
122
+
123
+	/**
124
+	 * Returns the code that assigns a value to its default value.
125
+	 *
126
+	 * @return string
127
+	 *
128
+	 * @throws \TDBMException
129
+	 */
130
+	public function assignToDefaultCode()
131
+	{
132
+		throw new \TDBMException('Foreign key based properties cannot be assigned a default value.');
133
+	}
134
+
135
+	/**
136
+	 * Returns true if the property is the primary key.
137
+	 *
138
+	 * @return bool
139
+	 */
140
+	public function isPrimaryKey()
141
+	{
142
+		$fkColumns = $this->foreignKey->getLocalColumns();
143
+		sort($fkColumns);
144
+
145
+		$pkColumns = $this->table->getPrimaryKeyColumns();
146
+		sort($pkColumns);
147
+
148
+		return $fkColumns == $pkColumns;
149
+	}
150
+
151
+	/**
152
+	 * Returns the PHP code for getters and setters.
153
+	 *
154
+	 * @return string
155
+	 */
156
+	public function getGetterSetterCode()
157
+	{
158
+		$tableName = $this->table->getName();
159
+		$getterName = $this->getGetterName();
160
+		$setterName = $this->getSetterName();
161
+
162
+		$referencedBeanName = TDBMDaoGenerator::getBeanNameFromTableName($this->foreignKey->getForeignTableName());
163
+
164
+		$str = '    /**
165 165
      * Returns the '.$referencedBeanName.' object bound to this object via the '.implode(' and ', $this->foreignKey->getLocalColumns()).' column.
166 166
      *
167 167
      * @return '.$referencedBeanName.'
@@ -183,20 +183,20 @@  discard block
 block discarded – undo
183 183
 
184 184
 ';
185 185
 
186
-        return $str;
187
-    }
188
-
189
-    /**
190
-     * Returns the part of code useful when doing json serialization.
191
-     *
192
-     * @return string
193
-     */
194
-    public function getJsonSerializeCode()
195
-    {
196
-        return '        if (!$stopRecursion) {
186
+		return $str;
187
+	}
188
+
189
+	/**
190
+	 * Returns the part of code useful when doing json serialization.
191
+	 *
192
+	 * @return string
193
+	 */
194
+	public function getJsonSerializeCode()
195
+	{
196
+		return '        if (!$stopRecursion) {
197 197
             $object = $this->'.$this->getGetterName().'();
198 198
             $array['.var_export($this->getLowerCamelCaseName(), true).'] = $object ? $object->jsonSerialize(true) : null;
199 199
         }
200 200
 ';
201
-    }
201
+	}
202 202
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/InnerResultArray.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 
84 84
     private function toIndex($offset)
85 85
     {
86
-        if ($offset < 0 || filter_var($offset, FILTER_VALIDATE_INT) === false) {
86
+        if ($offset<0 || filter_var($offset, FILTER_VALIDATE_INT) === false) {
87 87
             throw new TDBMInvalidOffsetException('Trying to access result set using offset "'.$offset.'". An offset must be a positive integer.');
88 88
         }
89 89
         if ($this->statement === null) {
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
     public function next()
101 101
     {
102 102
         // Let's overload the next() method to store the result.
103
-        if (isset($this->results[$this->key + 1])) {
103
+        if (isset($this->results[$this->key+1])) {
104 104
             ++$this->key;
105 105
             $this->current = $this->results[$this->key];
106 106
         } else {
Please login to merge, or discard this patch.
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -27,100 +27,100 @@
 block discarded – undo
27 27
  */
28 28
 class InnerResultArray extends InnerResultIterator
29 29
 {
30
-    /**
31
-     * The list of results already fetched.
32
-     *
33
-     * @var AbstractTDBMObject[]
34
-     */
35
-    private $results = [];
30
+	/**
31
+	 * The list of results already fetched.
32
+	 *
33
+	 * @var AbstractTDBMObject[]
34
+	 */
35
+	private $results = [];
36 36
 
37
-    /**
38
-     * Whether a offset exists.
39
-     *
40
-     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
41
-     *
42
-     * @param mixed $offset <p>
43
-     *                      An offset to check for.
44
-     *                      </p>
45
-     *
46
-     * @return bool true on success or false on failure.
47
-     *              </p>
48
-     *              <p>
49
-     *              The return value will be casted to boolean if non-boolean was returned
50
-     *
51
-     * @since 5.0.0
52
-     */
53
-    public function offsetExists($offset)
54
-    {
55
-        try {
56
-            $this->toIndex($offset);
57
-        } catch (TDBMInvalidOffsetException $e) {
58
-            return false;
59
-        }
37
+	/**
38
+	 * Whether a offset exists.
39
+	 *
40
+	 * @link http://php.net/manual/en/arrayaccess.offsetexists.php
41
+	 *
42
+	 * @param mixed $offset <p>
43
+	 *                      An offset to check for.
44
+	 *                      </p>
45
+	 *
46
+	 * @return bool true on success or false on failure.
47
+	 *              </p>
48
+	 *              <p>
49
+	 *              The return value will be casted to boolean if non-boolean was returned
50
+	 *
51
+	 * @since 5.0.0
52
+	 */
53
+	public function offsetExists($offset)
54
+	{
55
+		try {
56
+			$this->toIndex($offset);
57
+		} catch (TDBMInvalidOffsetException $e) {
58
+			return false;
59
+		}
60 60
 
61
-        return true;
62
-    }
61
+		return true;
62
+	}
63 63
 
64
-    /**
65
-     * Offset to retrieve.
66
-     *
67
-     * @link http://php.net/manual/en/arrayaccess.offsetget.php
68
-     *
69
-     * @param mixed $offset <p>
70
-     *                      The offset to retrieve.
71
-     *                      </p>
72
-     *
73
-     * @return mixed Can return all value types
74
-     *
75
-     * @since 5.0.0
76
-     */
77
-    public function offsetGet($offset)
78
-    {
79
-        $this->toIndex($offset);
64
+	/**
65
+	 * Offset to retrieve.
66
+	 *
67
+	 * @link http://php.net/manual/en/arrayaccess.offsetget.php
68
+	 *
69
+	 * @param mixed $offset <p>
70
+	 *                      The offset to retrieve.
71
+	 *                      </p>
72
+	 *
73
+	 * @return mixed Can return all value types
74
+	 *
75
+	 * @since 5.0.0
76
+	 */
77
+	public function offsetGet($offset)
78
+	{
79
+		$this->toIndex($offset);
80 80
 
81
-        return $this->results[$offset];
82
-    }
81
+		return $this->results[$offset];
82
+	}
83 83
 
84
-    private function toIndex($offset)
85
-    {
86
-        if ($offset < 0 || filter_var($offset, FILTER_VALIDATE_INT) === false) {
87
-            throw new TDBMInvalidOffsetException('Trying to access result set using offset "'.$offset.'". An offset must be a positive integer.');
88
-        }
89
-        if ($this->statement === null) {
90
-            $this->executeQuery();
91
-        }
92
-        while (!isset($this->results[$offset])) {
93
-            $this->next();
94
-            if ($this->current === null) {
95
-                throw new TDBMInvalidOffsetException('Offset "'.$offset.'" does not exist in result set.');
96
-            }
97
-        }
98
-    }
84
+	private function toIndex($offset)
85
+	{
86
+		if ($offset < 0 || filter_var($offset, FILTER_VALIDATE_INT) === false) {
87
+			throw new TDBMInvalidOffsetException('Trying to access result set using offset "'.$offset.'". An offset must be a positive integer.');
88
+		}
89
+		if ($this->statement === null) {
90
+			$this->executeQuery();
91
+		}
92
+		while (!isset($this->results[$offset])) {
93
+			$this->next();
94
+			if ($this->current === null) {
95
+				throw new TDBMInvalidOffsetException('Offset "'.$offset.'" does not exist in result set.');
96
+			}
97
+		}
98
+	}
99 99
 
100
-    public function next()
101
-    {
102
-        // Let's overload the next() method to store the result.
103
-        if (isset($this->results[$this->key + 1])) {
104
-            ++$this->key;
105
-            $this->current = $this->results[$this->key];
106
-        } else {
107
-            parent::next();
108
-            if ($this->current !== null) {
109
-                $this->results[$this->key] = $this->current;
110
-            }
111
-        }
112
-    }
100
+	public function next()
101
+	{
102
+		// Let's overload the next() method to store the result.
103
+		if (isset($this->results[$this->key + 1])) {
104
+			++$this->key;
105
+			$this->current = $this->results[$this->key];
106
+		} else {
107
+			parent::next();
108
+			if ($this->current !== null) {
109
+				$this->results[$this->key] = $this->current;
110
+			}
111
+		}
112
+	}
113 113
 
114
-    /**
115
-     * Overloads the rewind implementation.
116
-     * Do not reexecute the query.
117
-     */
118
-    public function rewind()
119
-    {
120
-        if (!$this->fetchStarted) {
121
-            $this->executeQuery();
122
-        }
123
-        $this->key = -1;
124
-        $this->next();
125
-    }
114
+	/**
115
+	 * Overloads the rewind implementation.
116
+	 * Do not reexecute the query.
117
+	 */
118
+	public function rewind()
119
+	{
120
+		if (!$this->fetchStarted) {
121
+			$this->executeQuery();
122
+		}
123
+		$this->key = -1;
124
+		$this->next();
125
+	}
126 126
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/StandardObjectStorage.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -30,78 +30,78 @@
 block discarded – undo
30 30
  */
31 31
 class StandardObjectStorage
32 32
 {
33
-    /**
34
-     * An array of fetched object, accessible via table name and primary key.
35
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
36
-     *
37
-     * @var array<string, array<string, TDBMObject>>
38
-     */
39
-    private $objects = array();
33
+	/**
34
+	 * An array of fetched object, accessible via table name and primary key.
35
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
36
+	 *
37
+	 * @var array<string, array<string, TDBMObject>>
38
+	 */
39
+	private $objects = array();
40 40
 
41
-    /**
42
-     * Sets an object in the storage.
43
-     *
44
-     * @param string     $tableName
45
-     * @param string     $id
46
-     * @param TDBMObject $dbRow
47
-     */
48
-    public function set($tableName, $id, DbRow $dbRow)
49
-    {
50
-        $this->objects[$tableName][$id] = $dbRow;
51
-    }
41
+	/**
42
+	 * Sets an object in the storage.
43
+	 *
44
+	 * @param string     $tableName
45
+	 * @param string     $id
46
+	 * @param TDBMObject $dbRow
47
+	 */
48
+	public function set($tableName, $id, DbRow $dbRow)
49
+	{
50
+		$this->objects[$tableName][$id] = $dbRow;
51
+	}
52 52
 
53
-    /**
54
-     * Checks if an object is in the storage.
55
-     *
56
-     * @param string $tableName
57
-     * @param string $id
58
-     *
59
-     * @return bool
60
-     */
61
-    public function has($tableName, $id)
62
-    {
63
-        return isset($this->objects[$tableName][$id]);
64
-    }
53
+	/**
54
+	 * Checks if an object is in the storage.
55
+	 *
56
+	 * @param string $tableName
57
+	 * @param string $id
58
+	 *
59
+	 * @return bool
60
+	 */
61
+	public function has($tableName, $id)
62
+	{
63
+		return isset($this->objects[$tableName][$id]);
64
+	}
65 65
 
66
-    /**
67
-     * Returns an object from the storage (or null if no object is set).
68
-     *
69
-     * @param string $tableName
70
-     * @param string $id
71
-     *
72
-     * @return DbRow
73
-     */
74
-    public function get($tableName, $id)
75
-    {
76
-        if (isset($this->objects[$tableName][$id])) {
77
-            return $this->objects[$tableName][$id];
78
-        } else {
79
-            return;
80
-        }
81
-    }
66
+	/**
67
+	 * Returns an object from the storage (or null if no object is set).
68
+	 *
69
+	 * @param string $tableName
70
+	 * @param string $id
71
+	 *
72
+	 * @return DbRow
73
+	 */
74
+	public function get($tableName, $id)
75
+	{
76
+		if (isset($this->objects[$tableName][$id])) {
77
+			return $this->objects[$tableName][$id];
78
+		} else {
79
+			return;
80
+		}
81
+	}
82 82
 
83
-    /**
84
-     * Removes an object from the storage.
85
-     *
86
-     * @param string $tableName
87
-     * @param string $id
88
-     */
89
-    public function remove($tableName, $id)
90
-    {
91
-        unset($this->objects[$tableName][$id]);
92
-    }
83
+	/**
84
+	 * Removes an object from the storage.
85
+	 *
86
+	 * @param string $tableName
87
+	 * @param string $id
88
+	 */
89
+	public function remove($tableName, $id)
90
+	{
91
+		unset($this->objects[$tableName][$id]);
92
+	}
93 93
 
94
-    /**
95
-     * Applies the callback to all objects.
96
-     *
97
-     * @param callable $callback
98
-     */
99
-    public function apply(callable $callback)
100
-    {
101
-        foreach ($this->objects as $tableName => $table) {
102
-            foreach ($table as $id => $obj) {
103
-                $callback($obj, $tableName, $id);
104
-            }
105
-        }
106
-    }
94
+	/**
95
+	 * Applies the callback to all objects.
96
+	 *
97
+	 * @param callable $callback
98
+	 */
99
+	public function apply(callable $callback)
100
+	{
101
+		foreach ($this->objects as $tableName => $table) {
102
+			foreach ($table as $id => $obj) {
103
+				$callback($obj, $tableName, $id);
104
+			}
105
+		}
106
+	}
107 107
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/PageIterator.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
      */
113 113
     public function getCurrentPage()
114 114
     {
115
-        return floor($this->offset / $this->limit) + 1;
115
+        return floor($this->offset/$this->limit)+1;
116 116
     }
117 117
 
118 118
     /**
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
      */
252 252
     public function jsonSerialize()
253 253
     {
254
-        return array_map(function (AbstractTDBMObject $item) {
254
+        return array_map(function(AbstractTDBMObject $item) {
255 255
             return $item->jsonSerialize();
256 256
         }, $this->toArray());
257 257
     }
Please login to merge, or discard this patch.
Indentation   +211 added lines, -211 removed lines patch added patch discarded remove patch
@@ -30,238 +30,238 @@
 block discarded – undo
30 30
  */
31 31
 class PageIterator implements Page, \ArrayAccess, \JsonSerializable
32 32
 {
33
-    /**
34
-     * @var Statement
35
-     */
36
-    protected $statement;
33
+	/**
34
+	 * @var Statement
35
+	 */
36
+	protected $statement;
37 37
 
38
-    protected $fetchStarted = false;
39
-    private $objectStorage;
40
-    private $className;
38
+	protected $fetchStarted = false;
39
+	private $objectStorage;
40
+	private $className;
41 41
 
42
-    private $parentResult;
43
-    private $tdbmService;
44
-    private $magicSql;
45
-    private $parameters;
46
-    private $limit;
47
-    private $offset;
48
-    private $columnDescriptors;
49
-    private $magicQuery;
42
+	private $parentResult;
43
+	private $tdbmService;
44
+	private $magicSql;
45
+	private $parameters;
46
+	private $limit;
47
+	private $offset;
48
+	private $columnDescriptors;
49
+	private $magicQuery;
50 50
 
51
-    /**
52
-     * The key of the current retrieved object.
53
-     *
54
-     * @var int
55
-     */
56
-    protected $key = -1;
51
+	/**
52
+	 * The key of the current retrieved object.
53
+	 *
54
+	 * @var int
55
+	 */
56
+	protected $key = -1;
57 57
 
58
-    protected $current = null;
58
+	protected $current = null;
59 59
 
60
-    private $databasePlatform;
60
+	private $databasePlatform;
61 61
 
62
-    private $innerResultIterator;
62
+	private $innerResultIterator;
63 63
 
64
-    private $mode;
64
+	private $mode;
65 65
 
66
-    /**
67
-     * @var LoggerInterface
68
-     */
69
-    private $logger;
66
+	/**
67
+	 * @var LoggerInterface
68
+	 */
69
+	private $logger;
70 70
 
71
-    public function __construct(ResultIterator $parentResult, $magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode, LoggerInterface $logger)
72
-    {
73
-        $this->parentResult = $parentResult;
74
-        $this->magicSql = $magicSql;
75
-        $this->objectStorage = $objectStorage;
76
-        $this->className = $className;
77
-        $this->tdbmService = $tdbmService;
78
-        $this->parameters = $parameters;
79
-        $this->limit = $limit;
80
-        $this->offset = $offset;
81
-        $this->columnDescriptors = $columnDescriptors;
82
-        $this->magicQuery = $magicQuery;
83
-        $this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
84
-        $this->mode = $mode;
85
-        $this->logger = $logger;
86
-    }
71
+	public function __construct(ResultIterator $parentResult, $magicSql, array $parameters, $limit, $offset, array $columnDescriptors, $objectStorage, $className, TDBMService $tdbmService, MagicQuery $magicQuery, $mode, LoggerInterface $logger)
72
+	{
73
+		$this->parentResult = $parentResult;
74
+		$this->magicSql = $magicSql;
75
+		$this->objectStorage = $objectStorage;
76
+		$this->className = $className;
77
+		$this->tdbmService = $tdbmService;
78
+		$this->parameters = $parameters;
79
+		$this->limit = $limit;
80
+		$this->offset = $offset;
81
+		$this->columnDescriptors = $columnDescriptors;
82
+		$this->magicQuery = $magicQuery;
83
+		$this->databasePlatform = $this->tdbmService->getConnection()->getDatabasePlatform();
84
+		$this->mode = $mode;
85
+		$this->logger = $logger;
86
+	}
87 87
 
88
-    /**
89
-     * Retrieve an external iterator.
90
-     *
91
-     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
92
-     *
93
-     * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or
94
-     *                             <b>Traversable</b>
95
-     *
96
-     * @since 5.0.0
97
-     */
98
-    public function getIterator()
99
-    {
100
-        if ($this->innerResultIterator === null) {
101
-            if ($this->mode === TDBMService::MODE_CURSOR) {
102
-                $this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
103
-            } else {
104
-                $this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
105
-            }
106
-        }
88
+	/**
89
+	 * Retrieve an external iterator.
90
+	 *
91
+	 * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
92
+	 *
93
+	 * @return InnerResultIterator An instance of an object implementing <b>Iterator</b> or
94
+	 *                             <b>Traversable</b>
95
+	 *
96
+	 * @since 5.0.0
97
+	 */
98
+	public function getIterator()
99
+	{
100
+		if ($this->innerResultIterator === null) {
101
+			if ($this->mode === TDBMService::MODE_CURSOR) {
102
+				$this->innerResultIterator = new InnerResultIterator($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
103
+			} else {
104
+				$this->innerResultIterator = new InnerResultArray($this->magicSql, $this->parameters, $this->limit, $this->offset, $this->columnDescriptors, $this->objectStorage, $this->className, $this->tdbmService, $this->magicQuery, $this->logger);
105
+			}
106
+		}
107 107
 
108
-        return $this->innerResultIterator;
109
-    }
108
+		return $this->innerResultIterator;
109
+	}
110 110
 
111
-    /**
112
-     * @return int
113
-     */
114
-    public function getCurrentOffset()
115
-    {
116
-        return $this->offset;
117
-    }
111
+	/**
112
+	 * @return int
113
+	 */
114
+	public function getCurrentOffset()
115
+	{
116
+		return $this->offset;
117
+	}
118 118
 
119
-    /**
120
-     * @return int
121
-     */
122
-    public function getCurrentPage()
123
-    {
124
-        return floor($this->offset / $this->limit) + 1;
125
-    }
119
+	/**
120
+	 * @return int
121
+	 */
122
+	public function getCurrentPage()
123
+	{
124
+		return floor($this->offset / $this->limit) + 1;
125
+	}
126 126
 
127
-    /**
128
-     * @return int
129
-     */
130
-    public function getCurrentLimit()
131
-    {
132
-        return $this->limit;
133
-    }
127
+	/**
128
+	 * @return int
129
+	 */
130
+	public function getCurrentLimit()
131
+	{
132
+		return $this->limit;
133
+	}
134 134
 
135
-    /**
136
-     * Return the number of results on the current page of the {@link Result}.
137
-     *
138
-     * @return int
139
-     */
140
-    public function count()
141
-    {
142
-        return $this->getIterator()->count();
143
-    }
135
+	/**
136
+	 * Return the number of results on the current page of the {@link Result}.
137
+	 *
138
+	 * @return int
139
+	 */
140
+	public function count()
141
+	{
142
+		return $this->getIterator()->count();
143
+	}
144 144
 
145
-    /**
146
-     * Return the number of ALL results in the paginatable of {@link Result}.
147
-     *
148
-     * @return int
149
-     */
150
-    public function totalCount()
151
-    {
152
-        return $this->parentResult->count();
153
-    }
145
+	/**
146
+	 * Return the number of ALL results in the paginatable of {@link Result}.
147
+	 *
148
+	 * @return int
149
+	 */
150
+	public function totalCount()
151
+	{
152
+		return $this->parentResult->count();
153
+	}
154 154
 
155
-    /**
156
-     * Casts the result set to a PHP array.
157
-     *
158
-     * @return array
159
-     */
160
-    public function toArray()
161
-    {
162
-        return iterator_to_array($this->getIterator());
163
-    }
155
+	/**
156
+	 * Casts the result set to a PHP array.
157
+	 *
158
+	 * @return array
159
+	 */
160
+	public function toArray()
161
+	{
162
+		return iterator_to_array($this->getIterator());
163
+	}
164 164
 
165
-    /**
166
-     * Returns a new iterator mapping any call using the $callable function.
167
-     *
168
-     * @param callable $callable
169
-     *
170
-     * @return MapIterator
171
-     */
172
-    public function map(callable $callable)
173
-    {
174
-        return new MapIterator($this->getIterator(), $callable);
175
-    }
165
+	/**
166
+	 * Returns a new iterator mapping any call using the $callable function.
167
+	 *
168
+	 * @param callable $callable
169
+	 *
170
+	 * @return MapIterator
171
+	 */
172
+	public function map(callable $callable)
173
+	{
174
+		return new MapIterator($this->getIterator(), $callable);
175
+	}
176 176
 
177
-    /**
178
-     * Whether a offset exists.
179
-     *
180
-     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
181
-     *
182
-     * @param mixed $offset <p>
183
-     *                      An offset to check for.
184
-     *                      </p>
185
-     *
186
-     * @return bool true on success or false on failure.
187
-     *              </p>
188
-     *              <p>
189
-     *              The return value will be casted to boolean if non-boolean was returned
190
-     *
191
-     * @since 5.0.0
192
-     */
193
-    public function offsetExists($offset)
194
-    {
195
-        return $this->getIterator()->offsetExists($offset);
196
-    }
177
+	/**
178
+	 * Whether a offset exists.
179
+	 *
180
+	 * @link http://php.net/manual/en/arrayaccess.offsetexists.php
181
+	 *
182
+	 * @param mixed $offset <p>
183
+	 *                      An offset to check for.
184
+	 *                      </p>
185
+	 *
186
+	 * @return bool true on success or false on failure.
187
+	 *              </p>
188
+	 *              <p>
189
+	 *              The return value will be casted to boolean if non-boolean was returned
190
+	 *
191
+	 * @since 5.0.0
192
+	 */
193
+	public function offsetExists($offset)
194
+	{
195
+		return $this->getIterator()->offsetExists($offset);
196
+	}
197 197
 
198
-    /**
199
-     * Offset to retrieve.
200
-     *
201
-     * @link http://php.net/manual/en/arrayaccess.offsetget.php
202
-     *
203
-     * @param mixed $offset <p>
204
-     *                      The offset to retrieve.
205
-     *                      </p>
206
-     *
207
-     * @return mixed Can return all value types
208
-     *
209
-     * @since 5.0.0
210
-     */
211
-    public function offsetGet($offset)
212
-    {
213
-        return $this->getIterator()->offsetGet($offset);
214
-    }
198
+	/**
199
+	 * Offset to retrieve.
200
+	 *
201
+	 * @link http://php.net/manual/en/arrayaccess.offsetget.php
202
+	 *
203
+	 * @param mixed $offset <p>
204
+	 *                      The offset to retrieve.
205
+	 *                      </p>
206
+	 *
207
+	 * @return mixed Can return all value types
208
+	 *
209
+	 * @since 5.0.0
210
+	 */
211
+	public function offsetGet($offset)
212
+	{
213
+		return $this->getIterator()->offsetGet($offset);
214
+	}
215 215
 
216
-    /**
217
-     * Offset to set.
218
-     *
219
-     * @link http://php.net/manual/en/arrayaccess.offsetset.php
220
-     *
221
-     * @param mixed $offset <p>
222
-     *                      The offset to assign the value to.
223
-     *                      </p>
224
-     * @param mixed $value  <p>
225
-     *                      The value to set.
226
-     *                      </p>
227
-     *
228
-     * @since 5.0.0
229
-     */
230
-    public function offsetSet($offset, $value)
231
-    {
232
-        return $this->getIterator()->offsetSet($offset, $value);
233
-    }
216
+	/**
217
+	 * Offset to set.
218
+	 *
219
+	 * @link http://php.net/manual/en/arrayaccess.offsetset.php
220
+	 *
221
+	 * @param mixed $offset <p>
222
+	 *                      The offset to assign the value to.
223
+	 *                      </p>
224
+	 * @param mixed $value  <p>
225
+	 *                      The value to set.
226
+	 *                      </p>
227
+	 *
228
+	 * @since 5.0.0
229
+	 */
230
+	public function offsetSet($offset, $value)
231
+	{
232
+		return $this->getIterator()->offsetSet($offset, $value);
233
+	}
234 234
 
235
-    /**
236
-     * Offset to unset.
237
-     *
238
-     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
239
-     *
240
-     * @param mixed $offset <p>
241
-     *                      The offset to unset.
242
-     *                      </p>
243
-     *
244
-     * @since 5.0.0
245
-     */
246
-    public function offsetUnset($offset)
247
-    {
248
-        return $this->getIterator()->offsetUnset($offset);
249
-    }
235
+	/**
236
+	 * Offset to unset.
237
+	 *
238
+	 * @link http://php.net/manual/en/arrayaccess.offsetunset.php
239
+	 *
240
+	 * @param mixed $offset <p>
241
+	 *                      The offset to unset.
242
+	 *                      </p>
243
+	 *
244
+	 * @since 5.0.0
245
+	 */
246
+	public function offsetUnset($offset)
247
+	{
248
+		return $this->getIterator()->offsetUnset($offset);
249
+	}
250 250
 
251
-    /**
252
-     * Specify data which should be serialized to JSON.
253
-     *
254
-     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
255
-     *
256
-     * @return mixed data which can be serialized by <b>json_encode</b>,
257
-     *               which is a value of any type other than a resource
258
-     *
259
-     * @since 5.4.0
260
-     */
261
-    public function jsonSerialize()
262
-    {
263
-        return array_map(function (AbstractTDBMObject $item) {
264
-            return $item->jsonSerialize();
265
-        }, $this->toArray());
266
-    }
251
+	/**
252
+	 * Specify data which should be serialized to JSON.
253
+	 *
254
+	 * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
255
+	 *
256
+	 * @return mixed data which can be serialized by <b>json_encode</b>,
257
+	 *               which is a value of any type other than a resource
258
+	 *
259
+	 * @since 5.4.0
260
+	 */
261
+	public function jsonSerialize()
262
+	{
263
+		return array_map(function (AbstractTDBMObject $item) {
264
+			return $item->jsonSerialize();
265
+		}, $this->toArray());
266
+	}
267 267
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmInstallController.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -181,6 +181,9 @@
 block discarded – undo
181 181
 
182 182
     protected $errorMsg;
183 183
 
184
+    /**
185
+     * @param string $msg
186
+     */
184 187
     private function displayErrorMsg($msg)
185 188
     {
186 189
         $this->errorMsg = $msg;
Please login to merge, or discard this patch.
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -15,168 +15,168 @@
 block discarded – undo
15 15
  */
16 16
 class TdbmInstallController extends Controller
17 17
 {
18
-    /**
19
-     * @var HtmlBlock
20
-     */
21
-    public $content;
22
-
23
-    public $selfedit;
24
-
25
-    /**
26
-     * The active MoufManager to be edited/viewed.
27
-     *
28
-     * @var MoufManager
29
-     */
30
-    public $moufManager;
31
-
32
-    /**
33
-     * The template used by the main page for mouf.
34
-     *
35
-     * @Property
36
-     * @Compulsory
37
-     *
38
-     * @var TemplateInterface
39
-     */
40
-    public $template;
41
-
42
-    /**
43
-     * Displays the first install screen.
44
-     *
45
-     * @Action
46
-     * @Logged
47
-     *
48
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
49
-     */
50
-    public function defaultAction($selfedit = 'false')
51
-    {
52
-        $this->selfedit = $selfedit;
53
-
54
-        if ($selfedit == 'true') {
55
-            $this->moufManager = MoufManager::getMoufManager();
56
-        } else {
57
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
58
-        }
59
-
60
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
61
-        $this->template->toHtml();
62
-    }
63
-
64
-    /**
65
-     * Skips the install process.
66
-     *
67
-     * @Action
68
-     * @Logged
69
-     *
70
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
71
-     */
72
-    public function skip($selfedit = 'false')
73
-    {
74
-        InstallUtils::continueInstall($selfedit == 'true');
75
-    }
76
-
77
-    protected $daoNamespace;
78
-    protected $beanNamespace;
79
-    protected $autoloadDetected;
80
-    protected $storeInUtc;
81
-    protected $useCustomComposer = false;
82
-
83
-    /**
84
-     * Displays the second install screen.
85
-     *
86
-     * @Action
87
-     * @Logged
88
-     *
89
-     * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
90
-     */
91
-    public function configure($selfedit = 'false')
92
-    {
93
-        $this->selfedit = $selfedit;
94
-
95
-        if ($selfedit == 'true') {
96
-            $this->moufManager = MoufManager::getMoufManager();
97
-        } else {
98
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
99
-        }
100
-
101
-        // Let's start by performing basic checks about the instances we assume to exist.
102
-        if (!$this->moufManager->instanceExists('dbalConnection')) {
103
-            $this->displayErrorMsg("The TDBM install process assumes your database connection instance is already created, and that the name of this instance is 'dbalConnection'. Could not find the 'dbalConnection' instance.");
104
-
105
-            return;
106
-        }
107
-
108
-        $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService');
109
-        $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService');
110
-
111
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
112
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
113
-
114
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
115
-            if ($autoloadNamespaces) {
116
-                $this->autoloadDetected = true;
117
-                $rootNamespace = $autoloadNamespaces[0];
118
-                $this->daoNamespace = $rootNamespace.'Model\\Dao';
119
-                $this->beanNamespace = $rootNamespace.'Model\\Bean';
120
-            } else {
121
-                $this->autoloadDetected = false;
122
-                $this->daoNamespace = 'YourApplication\\Model\\Dao';
123
-                $this->beanNamespace = 'YourApplication\\Model\\Bean';
124
-            }
125
-        } else {
126
-            $this->autoloadDetected = true;
127
-        }
128
-        $this->defaultPath = true;
129
-        $this->storePath = '';
130
-
131
-        $this->castDatesToDateTime = true;
132
-
133
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installStep2.php', $this);
134
-        $this->template->toHtml();
135
-    }
136
-
137
-    /**
138
-     * This action generates the TDBM instance, then the DAOs and Beans.
139
-     *
140
-     * @Action
141
-     *
142
-     * @param string $daonamespace
143
-     * @param string $beannamespace
144
-     * @param int    $storeInUtc
145
-     * @param string $selfedit
146
-     *
147
-     * @throws \Mouf\MoufException
148
-     */
149
-    public function generate($daonamespace, $beannamespace, $storeInUtc = 0, $selfedit = 'false', $defaultPath = false, $storePath = '')
150
-    {
151
-        $this->selfedit = $selfedit;
152
-
153
-        if ($selfedit == 'true') {
154
-            $this->moufManager = MoufManager::getMoufManager();
155
-        } else {
156
-            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
157
-        }
158
-
159
-        $doctrineCache = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');
160
-
161
-        if (!$this->moufManager->instanceExists('tdbmService')) {
162
-            $tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService');
163
-            $tdbmService->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection'));
164
-            $tdbmService->getConstructorArgumentProperty('cache')->setValue($doctrineCache);
165
-        }
166
-
167
-        $this->moufManager->rewriteMouf();
168
-
169
-        TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'DaoFactory', 'daoFactory', $selfedit, $storeInUtc, $defaultPath, $storePath);
170
-
171
-        InstallUtils::continueInstall($selfedit == 'true');
172
-    }
173
-
174
-    protected $errorMsg;
175
-
176
-    private function displayErrorMsg($msg)
177
-    {
178
-        $this->errorMsg = $msg;
179
-        $this->content->addFile(dirname(__FILE__).'/../../../../views/installError.php', $this);
180
-        $this->template->toHtml();
181
-    }
18
+	/**
19
+	 * @var HtmlBlock
20
+	 */
21
+	public $content;
22
+
23
+	public $selfedit;
24
+
25
+	/**
26
+	 * The active MoufManager to be edited/viewed.
27
+	 *
28
+	 * @var MoufManager
29
+	 */
30
+	public $moufManager;
31
+
32
+	/**
33
+	 * The template used by the main page for mouf.
34
+	 *
35
+	 * @Property
36
+	 * @Compulsory
37
+	 *
38
+	 * @var TemplateInterface
39
+	 */
40
+	public $template;
41
+
42
+	/**
43
+	 * Displays the first install screen.
44
+	 *
45
+	 * @Action
46
+	 * @Logged
47
+	 *
48
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
49
+	 */
50
+	public function defaultAction($selfedit = 'false')
51
+	{
52
+		$this->selfedit = $selfedit;
53
+
54
+		if ($selfedit == 'true') {
55
+			$this->moufManager = MoufManager::getMoufManager();
56
+		} else {
57
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
58
+		}
59
+
60
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installStep1.php', $this);
61
+		$this->template->toHtml();
62
+	}
63
+
64
+	/**
65
+	 * Skips the install process.
66
+	 *
67
+	 * @Action
68
+	 * @Logged
69
+	 *
70
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
71
+	 */
72
+	public function skip($selfedit = 'false')
73
+	{
74
+		InstallUtils::continueInstall($selfedit == 'true');
75
+	}
76
+
77
+	protected $daoNamespace;
78
+	protected $beanNamespace;
79
+	protected $autoloadDetected;
80
+	protected $storeInUtc;
81
+	protected $useCustomComposer = false;
82
+
83
+	/**
84
+	 * Displays the second install screen.
85
+	 *
86
+	 * @Action
87
+	 * @Logged
88
+	 *
89
+	 * @param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)
90
+	 */
91
+	public function configure($selfedit = 'false')
92
+	{
93
+		$this->selfedit = $selfedit;
94
+
95
+		if ($selfedit == 'true') {
96
+			$this->moufManager = MoufManager::getMoufManager();
97
+		} else {
98
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
99
+		}
100
+
101
+		// Let's start by performing basic checks about the instances we assume to exist.
102
+		if (!$this->moufManager->instanceExists('dbalConnection')) {
103
+			$this->displayErrorMsg("The TDBM install process assumes your database connection instance is already created, and that the name of this instance is 'dbalConnection'. Could not find the 'dbalConnection' instance.");
104
+
105
+			return;
106
+		}
107
+
108
+		$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_tdbmService');
109
+		$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_tdbmService');
110
+
111
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
112
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
113
+
114
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
115
+			if ($autoloadNamespaces) {
116
+				$this->autoloadDetected = true;
117
+				$rootNamespace = $autoloadNamespaces[0];
118
+				$this->daoNamespace = $rootNamespace.'Model\\Dao';
119
+				$this->beanNamespace = $rootNamespace.'Model\\Bean';
120
+			} else {
121
+				$this->autoloadDetected = false;
122
+				$this->daoNamespace = 'YourApplication\\Model\\Dao';
123
+				$this->beanNamespace = 'YourApplication\\Model\\Bean';
124
+			}
125
+		} else {
126
+			$this->autoloadDetected = true;
127
+		}
128
+		$this->defaultPath = true;
129
+		$this->storePath = '';
130
+
131
+		$this->castDatesToDateTime = true;
132
+
133
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installStep2.php', $this);
134
+		$this->template->toHtml();
135
+	}
136
+
137
+	/**
138
+	 * This action generates the TDBM instance, then the DAOs and Beans.
139
+	 *
140
+	 * @Action
141
+	 *
142
+	 * @param string $daonamespace
143
+	 * @param string $beannamespace
144
+	 * @param int    $storeInUtc
145
+	 * @param string $selfedit
146
+	 *
147
+	 * @throws \Mouf\MoufException
148
+	 */
149
+	public function generate($daonamespace, $beannamespace, $storeInUtc = 0, $selfedit = 'false', $defaultPath = false, $storePath = '')
150
+	{
151
+		$this->selfedit = $selfedit;
152
+
153
+		if ($selfedit == 'true') {
154
+			$this->moufManager = MoufManager::getMoufManager();
155
+		} else {
156
+			$this->moufManager = MoufManager::getMoufManagerHiddenInstance();
157
+		}
158
+
159
+		$doctrineCache = $this->moufManager->getInstanceDescriptor('defaultDoctrineCache');
160
+
161
+		if (!$this->moufManager->instanceExists('tdbmService')) {
162
+			$tdbmService = $this->moufManager->createInstance('Mouf\\Database\\TDBM\\TDBMService')->setName('tdbmService');
163
+			$tdbmService->getConstructorArgumentProperty('connection')->setValue($this->moufManager->getInstanceDescriptor('dbalConnection'));
164
+			$tdbmService->getConstructorArgumentProperty('cache')->setValue($doctrineCache);
165
+		}
166
+
167
+		$this->moufManager->rewriteMouf();
168
+
169
+		TdbmController::generateDaos($this->moufManager, 'tdbmService', $daonamespace, $beannamespace, 'DaoFactory', 'daoFactory', $selfedit, $storeInUtc, $defaultPath, $storePath);
170
+
171
+		InstallUtils::continueInstall($selfedit == 'true');
172
+	}
173
+
174
+	protected $errorMsg;
175
+
176
+	private function displayErrorMsg($msg)
177
+	{
178
+		$this->errorMsg = $msg;
179
+		$this->content->addFile(dirname(__FILE__).'/../../../../views/installError.php', $this);
180
+		$this->template->toHtml();
181
+	}
182 182
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Controllers/TdbmController.php 2 patches
Doc Comments   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
      * @Action
87 87
      *
88 88
      * @param string $name
89
-     * @param bool   $selfedit
89
+     * @param string|boolean   $selfedit
90 90
      */
91 91
     public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
92 92
     {
@@ -109,6 +109,8 @@  discard block
 block discarded – undo
109 109
      * @param string      $daofactoryinstancename
110 110
      * @param string      $selfedit
111 111
      * @param bool        $storeInUtc
112
+     * @param boolean $useCustomComposer
113
+     * @param string $composerFile
112 114
      *
113 115
      * @throws \Mouf\MoufException
114 116
      */
Please login to merge, or discard this patch.
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -18,148 +18,148 @@
 block discarded – undo
18 18
  */
19 19
 class TdbmController extends AbstractMoufInstanceController
20 20
 {
21
-    /**
22
-     * @var HtmlBlock
23
-     */
24
-    public $content;
25
-
26
-    protected $daoNamespace;
27
-    protected $beanNamespace;
28
-    protected $daoFactoryName;
29
-    protected $daoFactoryInstanceName;
30
-    protected $autoloadDetected;
31
-    protected $storeInUtc;
32
-    protected $useCustomComposer;
33
-
34
-    /**
35
-     * Admin page used to display the DAO generation form.
36
-     *
37
-     * @Action
38
-     */
39
-    public function defaultAction($name, $selfedit = 'false')
40
-    {
41
-        $this->initController($name, $selfedit);
42
-
43
-        // Fill variables
44
-        if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) {
45
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name);
46
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name);
47
-            $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name);
48
-            $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name);
49
-            $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name);
50
-            $this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer_'.$name);
51
-            $this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile_'.$name);
52
-        } else {
53
-            $this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace');
54
-            $this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace');
55
-            $this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName');
56
-            $this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName');
57
-            $this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc');
58
-            $this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer');
59
-            $this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile');
60
-        }
61
-
62
-        if ($this->daoNamespace == null && $this->beanNamespace == null) {
63
-            $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
64
-
65
-            $autoloadNamespaces = $classNameMapper->getManagedNamespaces();
66
-            if ($autoloadNamespaces) {
67
-                $this->autoloadDetected = true;
68
-                $rootNamespace = $autoloadNamespaces[0];
69
-                $this->daoNamespace = $rootNamespace.'Dao';
70
-                $this->beanNamespace = $rootNamespace.'Dao\\Bean';
71
-            } else {
72
-                $this->autoloadDetected = false;
73
-                $this->daoNamespace = 'YourApplication\\Dao';
74
-                $this->beanNamespace = 'YourApplication\\Dao\\Bean';
75
-            }
76
-        } else {
77
-            $this->autoloadDetected = true;
78
-        }
79
-
80
-        $this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
81
-        $this->template->toHtml();
82
-    }
83
-
84
-    /**
85
-     * This action generates the DAOs and Beans for the TDBM service passed in parameter.
86
-     *
87
-     * @Action
88
-     *
89
-     * @param string $name
90
-     * @param bool   $selfedit
91
-     */
92
-    public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
93
-    {
94
-        $this->initController($name, $selfedit);
95
-
96
-        self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc, $useCustomComposer, $composerFile);
97
-
98
-        // TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
99
-        header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
100
-    }
101
-
102
-    /**
103
-     * This function generates the DAOs and Beans for the TDBM service passed in parameter.
104
-     *
105
-     * @param MoufManager $moufManager
106
-     * @param string      $name
107
-     * @param string      $daonamespace
108
-     * @param string      $beannamespace
109
-     * @param string      $daofactoryclassname
110
-     * @param string      $daofactoryinstancename
111
-     * @param string      $selfedit
112
-     * @param bool        $storeInUtc
113
-     *
114
-     * @throws \Mouf\MoufException
115
-     */
116
-    public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null, $useCustomComposer = null, $composerFile = null)
117
-    {
118
-        $moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace);
119
-        $moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace);
120
-        $moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname);
121
-        $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename);
122
-        $moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc);
123
-        $moufManager->setVariable('tdbmDefaultUseCustomComposer_'.$name, $useCustomComposer);
124
-        $moufManager->setVariable('tdbmDefaultComposerFile_'.$name, $composerFile);
125
-
126
-        // In case of instance renaming, let's use the last used settings
127
-        $moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace);
128
-        $moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace);
129
-        $moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname);
130
-        $moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename);
131
-        $moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc);
132
-        $moufManager->setVariable('tdbmDefaultUseCustomComposer', $useCustomComposer);
133
-        $moufManager->setVariable('tdbmDefaultComposerFile', $composerFile);
134
-
135
-        // Remove first and last slash in namespace.
136
-        $daonamespace = trim($daonamespace, '\\');
137
-        $beannamespace = trim($beannamespace, '\\');
138
-
139
-        $tdbmService = new InstanceProxy($name);
140
-        /* @var $tdbmService TDBMService */
141
-        $tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc, ($useCustomComposer ? $composerFile : null));
142
-
143
-        $moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\Generated\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
144
-
145
-        $tableToBeanMap = [];
146
-
147
-        //$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService');
148
-
149
-        foreach ($tables as $table) {
150
-            $daoName = TDBMDaoGenerator::getDaoNameFromTableName($table);
151
-
152
-            $instanceName = TDBMDaoGenerator::toVariableName($daoName);
153
-            if (!$moufManager->instanceExists($instanceName)) {
154
-                $moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName);
155
-            }
156
-            $moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object');
157
-            $moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName);
158
-
159
-            $tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table);
160
-        }
161
-        $tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name);
162
-        $tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap);
163
-        $moufManager->rewriteMouf();
164
-    }
21
+	/**
22
+	 * @var HtmlBlock
23
+	 */
24
+	public $content;
25
+
26
+	protected $daoNamespace;
27
+	protected $beanNamespace;
28
+	protected $daoFactoryName;
29
+	protected $daoFactoryInstanceName;
30
+	protected $autoloadDetected;
31
+	protected $storeInUtc;
32
+	protected $useCustomComposer;
33
+
34
+	/**
35
+	 * Admin page used to display the DAO generation form.
36
+	 *
37
+	 * @Action
38
+	 */
39
+	public function defaultAction($name, $selfedit = 'false')
40
+	{
41
+		$this->initController($name, $selfedit);
42
+
43
+		// Fill variables
44
+		if ($this->moufManager->getVariable('tdbmDefaultSourceDirectory_'.$name) != null) {
45
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace_'.$name);
46
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace_'.$name);
47
+			$this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName_'.$name);
48
+			$this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName_'.$name);
49
+			$this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc_'.$name);
50
+			$this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer_'.$name);
51
+			$this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile_'.$name);
52
+		} else {
53
+			$this->daoNamespace = $this->moufManager->getVariable('tdbmDefaultDaoNamespace');
54
+			$this->beanNamespace = $this->moufManager->getVariable('tdbmDefaultBeanNamespace');
55
+			$this->daoFactoryName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryName');
56
+			$this->daoFactoryInstanceName = $this->moufManager->getVariable('tdbmDefaultDaoFactoryInstanceName');
57
+			$this->storeInUtc = $this->moufManager->getVariable('tdbmDefaultStoreInUtc');
58
+			$this->useCustomComposer = $this->moufManager->getVariable('tdbmDefaultUseCustomComposer');
59
+			$this->composerFile = $this->moufManager->getVariable('tdbmDefaultComposerFile');
60
+		}
61
+
62
+		if ($this->daoNamespace == null && $this->beanNamespace == null) {
63
+			$classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../../../composer.json');
64
+
65
+			$autoloadNamespaces = $classNameMapper->getManagedNamespaces();
66
+			if ($autoloadNamespaces) {
67
+				$this->autoloadDetected = true;
68
+				$rootNamespace = $autoloadNamespaces[0];
69
+				$this->daoNamespace = $rootNamespace.'Dao';
70
+				$this->beanNamespace = $rootNamespace.'Dao\\Bean';
71
+			} else {
72
+				$this->autoloadDetected = false;
73
+				$this->daoNamespace = 'YourApplication\\Dao';
74
+				$this->beanNamespace = 'YourApplication\\Dao\\Bean';
75
+			}
76
+		} else {
77
+			$this->autoloadDetected = true;
78
+		}
79
+
80
+		$this->content->addFile(__DIR__.'/../../../../views/tdbmGenerate.php', $this);
81
+		$this->template->toHtml();
82
+	}
83
+
84
+	/**
85
+	 * This action generates the DAOs and Beans for the TDBM service passed in parameter.
86
+	 *
87
+	 * @Action
88
+	 *
89
+	 * @param string $name
90
+	 * @param bool   $selfedit
91
+	 */
92
+	public function generate($name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $storeInUtc = 0, $selfedit = 'false', $useCustomComposer = false, $composerFile = '')
93
+	{
94
+		$this->initController($name, $selfedit);
95
+
96
+		self::generateDaos($this->moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit, $storeInUtc, $useCustomComposer, $composerFile);
97
+
98
+		// TODO: better: we should redirect to a screen that list the number of DAOs generated, etc...
99
+		header('Location: '.ROOT_URL.'ajaxinstance/?name='.urlencode($name).'&selfedit='.$selfedit);
100
+	}
101
+
102
+	/**
103
+	 * This function generates the DAOs and Beans for the TDBM service passed in parameter.
104
+	 *
105
+	 * @param MoufManager $moufManager
106
+	 * @param string      $name
107
+	 * @param string      $daonamespace
108
+	 * @param string      $beannamespace
109
+	 * @param string      $daofactoryclassname
110
+	 * @param string      $daofactoryinstancename
111
+	 * @param string      $selfedit
112
+	 * @param bool        $storeInUtc
113
+	 *
114
+	 * @throws \Mouf\MoufException
115
+	 */
116
+	public static function generateDaos(MoufManager $moufManager, $name, $daonamespace, $beannamespace, $daofactoryclassname, $daofactoryinstancename, $selfedit = 'false', $storeInUtc = null, $useCustomComposer = null, $composerFile = null)
117
+	{
118
+		$moufManager->setVariable('tdbmDefaultDaoNamespace_'.$name, $daonamespace);
119
+		$moufManager->setVariable('tdbmDefaultBeanNamespace_'.$name, $beannamespace);
120
+		$moufManager->setVariable('tdbmDefaultDaoFactoryName_'.$name, $daofactoryclassname);
121
+		$moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName_'.$name, $daofactoryinstancename);
122
+		$moufManager->setVariable('tdbmDefaultStoreInUtc_'.$name, $storeInUtc);
123
+		$moufManager->setVariable('tdbmDefaultUseCustomComposer_'.$name, $useCustomComposer);
124
+		$moufManager->setVariable('tdbmDefaultComposerFile_'.$name, $composerFile);
125
+
126
+		// In case of instance renaming, let's use the last used settings
127
+		$moufManager->setVariable('tdbmDefaultDaoNamespace', $daonamespace);
128
+		$moufManager->setVariable('tdbmDefaultBeanNamespace', $beannamespace);
129
+		$moufManager->setVariable('tdbmDefaultDaoFactoryName', $daofactoryclassname);
130
+		$moufManager->setVariable('tdbmDefaultDaoFactoryInstanceName', $daofactoryinstancename);
131
+		$moufManager->setVariable('tdbmDefaultStoreInUtc', $storeInUtc);
132
+		$moufManager->setVariable('tdbmDefaultUseCustomComposer', $useCustomComposer);
133
+		$moufManager->setVariable('tdbmDefaultComposerFile', $composerFile);
134
+
135
+		// Remove first and last slash in namespace.
136
+		$daonamespace = trim($daonamespace, '\\');
137
+		$beannamespace = trim($beannamespace, '\\');
138
+
139
+		$tdbmService = new InstanceProxy($name);
140
+		/* @var $tdbmService TDBMService */
141
+		$tables = $tdbmService->generateAllDaosAndBeans($daofactoryclassname, $daonamespace, $beannamespace, $storeInUtc, ($useCustomComposer ? $composerFile : null));
142
+
143
+		$moufManager->declareComponent($daofactoryinstancename, $daonamespace.'\\Generated\\'.$daofactoryclassname, false, MoufManager::DECLARE_ON_EXIST_KEEP_INCOMING_LINKS);
144
+
145
+		$tableToBeanMap = [];
146
+
147
+		//$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor('tdbmService');
148
+
149
+		foreach ($tables as $table) {
150
+			$daoName = TDBMDaoGenerator::getDaoNameFromTableName($table);
151
+
152
+			$instanceName = TDBMDaoGenerator::toVariableName($daoName);
153
+			if (!$moufManager->instanceExists($instanceName)) {
154
+				$moufManager->declareComponent($instanceName, $daonamespace.'\\'.$daoName);
155
+			}
156
+			$moufManager->setParameterViaConstructor($instanceName, 0, $name, 'object');
157
+			$moufManager->bindComponentViaSetter($daofactoryinstancename, 'set'.$daoName, $instanceName);
158
+
159
+			$tableToBeanMap[$table] = $beannamespace.'\\'.TDBMDaoGenerator::getBeanNameFromTableName($table);
160
+		}
161
+		$tdbmServiceDescriptor = $moufManager->getInstanceDescriptor($name);
162
+		$tdbmServiceDescriptor->getSetterProperty('setTableToBeanMap')->setValue($tableToBeanMap);
163
+		$moufManager->rewriteMouf();
164
+	}
165 165
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/TDBMService.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,6 @@
 block discarded – undo
25 25
 use Doctrine\DBAL\Connection;
26 26
 use Doctrine\DBAL\Schema\Column;
27 27
 use Doctrine\DBAL\Schema\ForeignKeyConstraint;
28
-use Doctrine\DBAL\Schema\Schema;
29 28
 use Doctrine\DBAL\Schema\Table;
30 29
 use Doctrine\DBAL\Types\Type;
31 30
 use Mouf\Database\MagicQuery;
Please login to merge, or discard this patch.
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -1301,7 +1301,7 @@  discard block
 block discarded – undo
1301 1301
      * @param string                       $mainTable             The name of the table queried
1302 1302
      * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1303 1303
      * @param array                        $parameters
1304
-     * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1304
+     * @param string|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1305 1305
      * @param array                        $additionalTablesFetch
1306 1306
      * @param int                          $mode
1307 1307
      * @param string                       $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
@@ -1769,7 +1769,7 @@  discard block
 block discarded – undo
1769 1769
      * @param $pivotTableName
1770 1770
      * @param AbstractTDBMObject $bean
1771 1771
      *
1772
-     * @return AbstractTDBMObject[]
1772
+     * @return ResultIterator
1773 1773
      */
1774 1774
     public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1775 1775
     {
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
         sort($tables);
1065 1065
 
1066 1066
         return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1067
-            function () use ($tables) {
1067
+            function() use ($tables) {
1068 1068
                 return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1069 1069
             });
1070 1070
     }
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
      */
1112 1112
     public function _getRelatedTablesByInheritance($table)
1113 1113
     {
1114
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1114
+        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function() use ($table) {
1115 1115
             return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1116 1116
         });
1117 1117
     }
@@ -1358,7 +1358,7 @@  discard block
 block discarded – undo
1358 1358
         $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1359 1359
         $page = $objects->take(0, 2);
1360 1360
         $count = $page->count();
1361
-        if ($count > 1) {
1361
+        if ($count>1) {
1362 1362
             throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1363 1363
         } elseif ($count === 0) {
1364 1364
             return;
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
         $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1386 1386
         $page = $objects->take(0, 2);
1387 1387
         $count = $page->count();
1388
-        if ($count > 1) {
1388
+        if ($count>1) {
1389 1389
             throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1390 1390
         } elseif ($count === 0) {
1391 1391
             return;
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
         $remoteTable = $remoteFk->getForeignTableName();
1504 1504
 
1505 1505
         $primaryKeys = $this->getPrimaryKeyValues($bean);
1506
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1506
+        $columnNames = array_map(function($name) use ($pivotTableName) {
1507 1507
             return $pivotTableName.'.'.$name;
1508 1508
         }, $localFk->getLocalColumns());
1509 1509
 
@@ -1526,7 +1526,7 @@  discard block
 block discarded – undo
1526 1526
         $table1 = $fks[0]->getForeignTableName();
1527 1527
         $table2 = $fks[1]->getForeignTableName();
1528 1528
 
1529
-        $beanTables = array_map(function (DbRow $dbRow) {
1529
+        $beanTables = array_map(function(DbRow $dbRow) {
1530 1530
             return $dbRow->_getDbTableName();
1531 1531
         }, $bean->_getDbRows());
1532 1532
 
@@ -1584,7 +1584,7 @@  discard block
 block discarded – undo
1584 1584
     {
1585 1585
         if (!isset($typesForTable[$tableName])) {
1586 1586
             $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1587
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1587
+            $typesForTable[$tableName] = array_map(function(Column $column) {
1588 1588
                 return $column->getType();
1589 1589
             }, $columns);
1590 1590
         }
Please login to merge, or discard this patch.
Indentation   +1408 added lines, -1408 removed lines patch added patch discarded remove patch
@@ -47,236 +47,236 @@  discard block
 block discarded – undo
47 47
  */
48 48
 class TDBMService
49 49
 {
50
-    const MODE_CURSOR = 1;
51
-    const MODE_ARRAY = 2;
52
-
53
-    /**
54
-     * The database connection.
55
-     *
56
-     * @var Connection
57
-     */
58
-    private $connection;
59
-
60
-    /**
61
-     * @var SchemaAnalyzer
62
-     */
63
-    private $schemaAnalyzer;
64
-
65
-    /**
66
-     * @var MagicQuery
67
-     */
68
-    private $magicQuery;
69
-
70
-    /**
71
-     * @var TDBMSchemaAnalyzer
72
-     */
73
-    private $tdbmSchemaAnalyzer;
74
-
75
-    /**
76
-     * @var string
77
-     */
78
-    private $cachePrefix;
79
-
80
-    /**
81
-     * Cache of table of primary keys.
82
-     * Primary keys are stored by tables, as an array of column.
83
-     * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
84
-     *
85
-     * @var string[]
86
-     */
87
-    private $primaryKeysColumns;
88
-
89
-    /**
90
-     * Service storing objects in memory.
91
-     * Access is done by table name and then by primary key.
92
-     * If the primary key is split on several columns, access is done by an array of columns, serialized.
93
-     *
94
-     * @var StandardObjectStorage|WeakrefObjectStorage
95
-     */
96
-    private $objectStorage;
97
-
98
-    /**
99
-     * The fetch mode of the result sets returned by `getObjects`.
100
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
101
-     *
102
-     * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
103
-     * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
104
-     * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
105
-     * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
106
-     * You can access the array by key, or using foreach, several times.
107
-     *
108
-     * @var int
109
-     */
110
-    private $mode = self::MODE_ARRAY;
111
-
112
-    /**
113
-     * Table of new objects not yet inserted in database or objects modified that must be saved.
114
-     *
115
-     * @var \SplObjectStorage of DbRow objects
116
-     */
117
-    private $toSaveObjects;
118
-
119
-    /**
120
-     * A cache service to be used.
121
-     *
122
-     * @var Cache|null
123
-     */
124
-    private $cache;
125
-
126
-    /**
127
-     * Map associating a table name to a fully qualified Bean class name.
128
-     *
129
-     * @var array
130
-     */
131
-    private $tableToBeanMap = [];
132
-
133
-    /**
134
-     * @var \ReflectionClass[]
135
-     */
136
-    private $reflectionClassCache = array();
137
-
138
-    /**
139
-     * @var LoggerInterface
140
-     */
141
-    private $rootLogger;
142
-
143
-    /**
144
-     * @var LevelFilter|NullLogger
145
-     */
146
-    private $logger;
147
-
148
-    /**
149
-     * @var OrderByAnalyzer
150
-     */
151
-    private $orderByAnalyzer;
152
-
153
-    /**
154
-     * @param Connection     $connection     The DBAL DB connection to use
155
-     * @param Cache|null     $cache          A cache service to be used
156
-     * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
157
-     *                                       Will be automatically created if not passed
158
-     */
159
-    public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
160
-    {
161
-        if (extension_loaded('weakref')) {
162
-            $this->objectStorage = new WeakrefObjectStorage();
163
-        } else {
164
-            $this->objectStorage = new StandardObjectStorage();
165
-        }
166
-        $this->connection = $connection;
167
-        if ($cache !== null) {
168
-            $this->cache = $cache;
169
-        } else {
170
-            $this->cache = new VoidCache();
171
-        }
172
-        if ($schemaAnalyzer) {
173
-            $this->schemaAnalyzer = $schemaAnalyzer;
174
-        } else {
175
-            $this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
176
-        }
177
-
178
-        $this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
179
-
180
-        $this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
181
-        $this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
182
-
183
-        $this->toSaveObjects = new \SplObjectStorage();
184
-        if ($logger === null) {
185
-            $this->logger = new NullLogger();
186
-            $this->rootLogger = new NullLogger();
187
-        } else {
188
-            $this->rootLogger = $logger;
189
-            $this->setLogLevel(LogLevel::WARNING);
190
-        }
191
-        $this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
192
-    }
193
-
194
-    /**
195
-     * Returns the object used to connect to the database.
196
-     *
197
-     * @return Connection
198
-     */
199
-    public function getConnection()
200
-    {
201
-        return $this->connection;
202
-    }
203
-
204
-    /**
205
-     * Creates a unique cache key for the current connection.
206
-     *
207
-     * @return string
208
-     */
209
-    private function getConnectionUniqueId()
210
-    {
211
-        return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
212
-    }
213
-
214
-    /**
215
-     * Sets the default fetch mode of the result sets returned by `findObjects`.
216
-     * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
217
-     *
218
-     * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
219
-     * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
220
-     * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
221
-     *
222
-     * @param int $mode
223
-     *
224
-     * @return $this
225
-     *
226
-     * @throws TDBMException
227
-     */
228
-    public function setFetchMode($mode)
229
-    {
230
-        if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
231
-            throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
232
-        }
233
-        $this->mode = $mode;
234
-
235
-        return $this;
236
-    }
237
-
238
-    /**
239
-     * Returns a TDBMObject associated from table "$table_name".
240
-     * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
241
-     * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
242
-     *
243
-     * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
244
-     * 			$user = $tdbmService->getObject('users',1);
245
-     * 			echo $user->name;
246
-     * will return the name of the user whose user_id is one.
247
-     *
248
-     * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
249
-     * For instance:
250
-     * 			$group = $tdbmService->getObject('groups',array(1,2));
251
-     *
252
-     * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
253
-     * will be the same.
254
-     *
255
-     * For instance:
256
-     * 			$user1 = $tdbmService->getObject('users',1);
257
-     * 			$user2 = $tdbmService->getObject('users',1);
258
-     * 			$user1->name = 'John Doe';
259
-     * 			echo $user2->name;
260
-     * will return 'John Doe'.
261
-     *
262
-     * You can use filters instead of passing the primary key. For instance:
263
-     * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
264
-     * This will return the user whose login is 'jdoe'.
265
-     * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
266
-     *
267
-     * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
268
-     * For instance:
269
-     *  	$user = $tdbmService->getObject('users',1,'User');
270
-     * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
271
-     * Please be sure not to override any method or any property unless you perfectly know what you are doing!
272
-     *
273
-     * @param string $table_name   The name of the table we retrieve an object from
274
-     * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
275
-     * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
276
-     * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
277
-     *
278
-     * @return TDBMObject
279
-     */
50
+	const MODE_CURSOR = 1;
51
+	const MODE_ARRAY = 2;
52
+
53
+	/**
54
+	 * The database connection.
55
+	 *
56
+	 * @var Connection
57
+	 */
58
+	private $connection;
59
+
60
+	/**
61
+	 * @var SchemaAnalyzer
62
+	 */
63
+	private $schemaAnalyzer;
64
+
65
+	/**
66
+	 * @var MagicQuery
67
+	 */
68
+	private $magicQuery;
69
+
70
+	/**
71
+	 * @var TDBMSchemaAnalyzer
72
+	 */
73
+	private $tdbmSchemaAnalyzer;
74
+
75
+	/**
76
+	 * @var string
77
+	 */
78
+	private $cachePrefix;
79
+
80
+	/**
81
+	 * Cache of table of primary keys.
82
+	 * Primary keys are stored by tables, as an array of column.
83
+	 * For instance $primary_key['my_table'][0] will return the first column of the primary key of table 'my_table'.
84
+	 *
85
+	 * @var string[]
86
+	 */
87
+	private $primaryKeysColumns;
88
+
89
+	/**
90
+	 * Service storing objects in memory.
91
+	 * Access is done by table name and then by primary key.
92
+	 * If the primary key is split on several columns, access is done by an array of columns, serialized.
93
+	 *
94
+	 * @var StandardObjectStorage|WeakrefObjectStorage
95
+	 */
96
+	private $objectStorage;
97
+
98
+	/**
99
+	 * The fetch mode of the result sets returned by `getObjects`.
100
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY or TDBMObjectArray::MODE_COMPATIBLE_ARRAY.
101
+	 *
102
+	 * In 'MODE_ARRAY' mode (default), the result is an array. Use this mode by default (unless the list returned is very big).
103
+	 * In 'MODE_CURSOR' mode, the result is a Generator which is an iterable collection that can be scanned only once (only one "foreach") on it,
104
+	 * and it cannot be accessed via key. Use this mode for large datasets processed by batch.
105
+	 * In 'MODE_COMPATIBLE_ARRAY' mode, the result is an old TDBMObjectArray (used up to TDBM 3.2).
106
+	 * You can access the array by key, or using foreach, several times.
107
+	 *
108
+	 * @var int
109
+	 */
110
+	private $mode = self::MODE_ARRAY;
111
+
112
+	/**
113
+	 * Table of new objects not yet inserted in database or objects modified that must be saved.
114
+	 *
115
+	 * @var \SplObjectStorage of DbRow objects
116
+	 */
117
+	private $toSaveObjects;
118
+
119
+	/**
120
+	 * A cache service to be used.
121
+	 *
122
+	 * @var Cache|null
123
+	 */
124
+	private $cache;
125
+
126
+	/**
127
+	 * Map associating a table name to a fully qualified Bean class name.
128
+	 *
129
+	 * @var array
130
+	 */
131
+	private $tableToBeanMap = [];
132
+
133
+	/**
134
+	 * @var \ReflectionClass[]
135
+	 */
136
+	private $reflectionClassCache = array();
137
+
138
+	/**
139
+	 * @var LoggerInterface
140
+	 */
141
+	private $rootLogger;
142
+
143
+	/**
144
+	 * @var LevelFilter|NullLogger
145
+	 */
146
+	private $logger;
147
+
148
+	/**
149
+	 * @var OrderByAnalyzer
150
+	 */
151
+	private $orderByAnalyzer;
152
+
153
+	/**
154
+	 * @param Connection     $connection     The DBAL DB connection to use
155
+	 * @param Cache|null     $cache          A cache service to be used
156
+	 * @param SchemaAnalyzer $schemaAnalyzer The schema analyzer that will be used to find shortest paths...
157
+	 *                                       Will be automatically created if not passed
158
+	 */
159
+	public function __construct(Connection $connection, Cache $cache = null, SchemaAnalyzer $schemaAnalyzer = null, LoggerInterface $logger = null)
160
+	{
161
+		if (extension_loaded('weakref')) {
162
+			$this->objectStorage = new WeakrefObjectStorage();
163
+		} else {
164
+			$this->objectStorage = new StandardObjectStorage();
165
+		}
166
+		$this->connection = $connection;
167
+		if ($cache !== null) {
168
+			$this->cache = $cache;
169
+		} else {
170
+			$this->cache = new VoidCache();
171
+		}
172
+		if ($schemaAnalyzer) {
173
+			$this->schemaAnalyzer = $schemaAnalyzer;
174
+		} else {
175
+			$this->schemaAnalyzer = new SchemaAnalyzer($this->connection->getSchemaManager(), $this->cache, $this->getConnectionUniqueId());
176
+		}
177
+
178
+		$this->magicQuery = new MagicQuery($this->connection, $this->cache, $this->schemaAnalyzer);
179
+
180
+		$this->tdbmSchemaAnalyzer = new TDBMSchemaAnalyzer($connection, $this->cache, $this->schemaAnalyzer);
181
+		$this->cachePrefix = $this->tdbmSchemaAnalyzer->getCachePrefix();
182
+
183
+		$this->toSaveObjects = new \SplObjectStorage();
184
+		if ($logger === null) {
185
+			$this->logger = new NullLogger();
186
+			$this->rootLogger = new NullLogger();
187
+		} else {
188
+			$this->rootLogger = $logger;
189
+			$this->setLogLevel(LogLevel::WARNING);
190
+		}
191
+		$this->orderByAnalyzer = new OrderByAnalyzer($this->cache, $this->cachePrefix);
192
+	}
193
+
194
+	/**
195
+	 * Returns the object used to connect to the database.
196
+	 *
197
+	 * @return Connection
198
+	 */
199
+	public function getConnection()
200
+	{
201
+		return $this->connection;
202
+	}
203
+
204
+	/**
205
+	 * Creates a unique cache key for the current connection.
206
+	 *
207
+	 * @return string
208
+	 */
209
+	private function getConnectionUniqueId()
210
+	{
211
+		return hash('md4', $this->connection->getHost().'-'.$this->connection->getPort().'-'.$this->connection->getDatabase().'-'.$this->connection->getDriver()->getName());
212
+	}
213
+
214
+	/**
215
+	 * Sets the default fetch mode of the result sets returned by `findObjects`.
216
+	 * Can be one of: TDBMObjectArray::MODE_CURSOR or TDBMObjectArray::MODE_ARRAY.
217
+	 *
218
+	 * In 'MODE_ARRAY' mode (default), the result is a ResultIterator object that behaves like an array. Use this mode by default (unless the list returned is very big).
219
+	 * In 'MODE_CURSOR' mode, the result is a ResultIterator object. If you scan it many times (by calling several time a foreach loop), the query will be run
220
+	 * several times. In cursor mode, you cannot access the result set by key. Use this mode for large datasets processed by batch.
221
+	 *
222
+	 * @param int $mode
223
+	 *
224
+	 * @return $this
225
+	 *
226
+	 * @throws TDBMException
227
+	 */
228
+	public function setFetchMode($mode)
229
+	{
230
+		if ($mode !== self::MODE_CURSOR && $mode !== self::MODE_ARRAY) {
231
+			throw new TDBMException("Unknown fetch mode: '".$this->mode."'");
232
+		}
233
+		$this->mode = $mode;
234
+
235
+		return $this;
236
+	}
237
+
238
+	/**
239
+	 * Returns a TDBMObject associated from table "$table_name".
240
+	 * If the $filters parameter is an int/string, the object returned will be the object whose primary key = $filters.
241
+	 * $filters can also be a set of TDBM_Filters (see the findObjects method for more details).
242
+	 *
243
+	 * For instance, if there is a table 'users', with a primary key on column 'user_id' and a column 'user_name', then
244
+	 * 			$user = $tdbmService->getObject('users',1);
245
+	 * 			echo $user->name;
246
+	 * will return the name of the user whose user_id is one.
247
+	 *
248
+	 * If a table has a primary key over several columns, you should pass to $id an array containing the the value of the various columns.
249
+	 * For instance:
250
+	 * 			$group = $tdbmService->getObject('groups',array(1,2));
251
+	 *
252
+	 * Note that TDBMObject performs caching for you. If you get twice the same object, the reference of the object you will get
253
+	 * will be the same.
254
+	 *
255
+	 * For instance:
256
+	 * 			$user1 = $tdbmService->getObject('users',1);
257
+	 * 			$user2 = $tdbmService->getObject('users',1);
258
+	 * 			$user1->name = 'John Doe';
259
+	 * 			echo $user2->name;
260
+	 * will return 'John Doe'.
261
+	 *
262
+	 * You can use filters instead of passing the primary key. For instance:
263
+	 * 			$user = $tdbmService->getObject('users',new EqualFilter('users', 'login', 'jdoe'));
264
+	 * This will return the user whose login is 'jdoe'.
265
+	 * Please note that if 2 users have the jdoe login in database, the method will throw a TDBM_DuplicateRowException.
266
+	 *
267
+	 * Also, you can specify the return class for the object (provided the return class extends TDBMObject).
268
+	 * For instance:
269
+	 *  	$user = $tdbmService->getObject('users',1,'User');
270
+	 * will return an object from the "User" class. The "User" class must extend the "TDBMObject" class.
271
+	 * Please be sure not to override any method or any property unless you perfectly know what you are doing!
272
+	 *
273
+	 * @param string $table_name   The name of the table we retrieve an object from
274
+	 * @param mixed  $filters      If the filter is a string/integer, it will be considered as the id of the object (the value of the primary key). Otherwise, it can be a filter bag (see the filterbag parameter of the findObjects method for more details about filter bags)
275
+	 * @param string $className    Optional: The name of the class to instanciate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
276
+	 * @param bool   $lazy_loading If set to true, and if the primary key is passed in parameter of getObject, the object will not be queried in database. It will be queried when you first try to access a column. If at that time the object cannot be found in database, an exception will be thrown
277
+	 *
278
+	 * @return TDBMObject
279
+	 */
280 280
 /*	public function getObject($table_name, $filters, $className = null, $lazy_loading = false) {
281 281
 
282 282
         if (is_array($filters) || $filters instanceof FilterInterface) {
@@ -362,199 +362,199 @@  discard block
 block discarded – undo
362 362
         return $obj;
363 363
     }*/
364 364
 
365
-    /**
366
-     * Removes the given object from database.
367
-     * This cannot be called on an object that is not attached to this TDBMService
368
-     * (will throw a TDBMInvalidOperationException).
369
-     *
370
-     * @param AbstractTDBMObject $object the object to delete
371
-     *
372
-     * @throws TDBMException
373
-     * @throws TDBMInvalidOperationException
374
-     */
375
-    public function delete(AbstractTDBMObject $object)
376
-    {
377
-        switch ($object->_getStatus()) {
378
-            case TDBMObjectStateEnum::STATE_DELETED:
379
-                // Nothing to do, object already deleted.
380
-                return;
381
-            case TDBMObjectStateEnum::STATE_DETACHED:
382
-                throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
-            case TDBMObjectStateEnum::STATE_NEW:
384
-                $this->deleteManyToManyRelationships($object);
385
-                foreach ($object->_getDbRows() as $dbRow) {
386
-                    $this->removeFromToSaveObjectList($dbRow);
387
-                }
388
-                break;
389
-            case TDBMObjectStateEnum::STATE_DIRTY:
390
-                foreach ($object->_getDbRows() as $dbRow) {
391
-                    $this->removeFromToSaveObjectList($dbRow);
392
-                }
393
-                // And continue deleting...
394
-            case TDBMObjectStateEnum::STATE_NOT_LOADED:
395
-            case TDBMObjectStateEnum::STATE_LOADED:
396
-                $this->deleteManyToManyRelationships($object);
397
-                // Let's delete db rows, in reverse order.
398
-                foreach (array_reverse($object->_getDbRows()) as $dbRow) {
399
-                    $tableName = $dbRow->_getDbTableName();
400
-                    $primaryKeys = $dbRow->_getPrimaryKeys();
401
-                    $this->connection->delete($tableName, $primaryKeys);
402
-                    $this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
403
-                }
404
-                break;
405
-            // @codeCoverageIgnoreStart
406
-            default:
407
-                throw new TDBMInvalidOperationException('Unexpected status for bean');
408
-            // @codeCoverageIgnoreEnd
409
-        }
410
-
411
-        $object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
412
-    }
413
-
414
-    /**
415
-     * Removes all many to many relationships for this object.
416
-     *
417
-     * @param AbstractTDBMObject $object
418
-     */
419
-    private function deleteManyToManyRelationships(AbstractTDBMObject $object)
420
-    {
421
-        foreach ($object->_getDbRows() as $tableName => $dbRow) {
422
-            $pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
423
-            foreach ($pivotTables as $pivotTable) {
424
-                $remoteBeans = $object->_getRelationships($pivotTable);
425
-                foreach ($remoteBeans as $remoteBean) {
426
-                    $object->_removeRelationship($pivotTable, $remoteBean);
427
-                }
428
-            }
429
-        }
430
-        $this->persistManyToManyRelationships($object);
431
-    }
432
-
433
-    /**
434
-     * This function removes the given object from the database. It will also remove all objects relied to the one given
435
-     * by parameter before all.
436
-     *
437
-     * Notice: if the object has a multiple primary key, the function will not work.
438
-     *
439
-     * @param AbstractTDBMObject $objToDelete
440
-     */
441
-    public function deleteCascade(AbstractTDBMObject $objToDelete)
442
-    {
443
-        $this->deleteAllConstraintWithThisObject($objToDelete);
444
-        $this->delete($objToDelete);
445
-    }
446
-
447
-    /**
448
-     * This function is used only in TDBMService (private function)
449
-     * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
450
-     *
451
-     * @param AbstractTDBMObject $obj
452
-     */
453
-    private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
454
-    {
455
-        $dbRows = $obj->_getDbRows();
456
-        foreach ($dbRows as $dbRow) {
457
-            $tableName = $dbRow->_getDbTableName();
458
-            $pks = array_values($dbRow->_getPrimaryKeys());
459
-            if (!empty($pks)) {
460
-                $incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
461
-
462
-                foreach ($incomingFks as $incomingFk) {
463
-                    $filter = array_combine($incomingFk->getLocalColumns(), $pks);
464
-
465
-                    $results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
466
-
467
-                    foreach ($results as $bean) {
468
-                        $this->deleteCascade($bean);
469
-                    }
470
-                }
471
-            }
472
-        }
473
-    }
474
-
475
-    /**
476
-     * This function performs a save() of all the objects that have been modified.
477
-     */
478
-    public function completeSave()
479
-    {
480
-        foreach ($this->toSaveObjects as $dbRow) {
481
-            $this->save($dbRow->getTDBMObject());
482
-        }
483
-    }
484
-
485
-    /**
486
-     * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
487
-     * and gives back a proper Filter object.
488
-     *
489
-     * @param mixed $filter_bag
490
-     * @param int   $counter
491
-     *
492
-     * @return array First item: filter string, second item: parameters
493
-     *
494
-     * @throws TDBMException
495
-     */
496
-    public function buildFilterFromFilterBag($filter_bag, $counter = 1)
497
-    {
498
-        if ($filter_bag === null) {
499
-            return ['', []];
500
-        } elseif (is_string($filter_bag)) {
501
-            return [$filter_bag, []];
502
-        } elseif (is_array($filter_bag)) {
503
-            $sqlParts = [];
504
-            $parameters = [];
505
-            foreach ($filter_bag as $column => $value) {
506
-                if (is_int($column)) {
507
-                    list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
508
-                    $sqlParts[] = $subSqlPart;
509
-                    $parameters += $subParameters;
510
-                } else {
511
-                    $paramName = 'tdbmparam'.$counter;
512
-                    if (is_array($value)) {
513
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
514
-                    } else {
515
-                        $sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
516
-                    }
517
-                    $parameters[$paramName] = $value;
518
-                    ++$counter;
519
-                }
520
-            }
521
-
522
-            return [implode(' AND ', $sqlParts), $parameters];
523
-        } elseif ($filter_bag instanceof AbstractTDBMObject) {
524
-            $sqlParts = [];
525
-            $parameters = [];
526
-            $dbRows = $filter_bag->_getDbRows();
527
-            $dbRow = reset($dbRows);
528
-            $primaryKeys = $dbRow->_getPrimaryKeys();
529
-
530
-            foreach ($primaryKeys as $column => $value) {
531
-                $paramName = 'tdbmparam'.$counter;
532
-                $sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
533
-                $parameters[$paramName] = $value;
534
-                ++$counter;
535
-            }
536
-
537
-            return [implode(' AND ', $sqlParts), $parameters];
538
-        } elseif ($filter_bag instanceof \Iterator) {
539
-            return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
540
-        } else {
541
-            throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
542
-        }
543
-    }
544
-
545
-    /**
546
-     * @param string $table
547
-     *
548
-     * @return string[]
549
-     */
550
-    public function getPrimaryKeyColumns($table)
551
-    {
552
-        if (!isset($this->primaryKeysColumns[$table])) {
553
-            $this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
554
-
555
-            // TODO TDBM4: See if we need to improve error reporting if table name does not exist.
556
-
557
-            /*$arr = array();
365
+	/**
366
+	 * Removes the given object from database.
367
+	 * This cannot be called on an object that is not attached to this TDBMService
368
+	 * (will throw a TDBMInvalidOperationException).
369
+	 *
370
+	 * @param AbstractTDBMObject $object the object to delete
371
+	 *
372
+	 * @throws TDBMException
373
+	 * @throws TDBMInvalidOperationException
374
+	 */
375
+	public function delete(AbstractTDBMObject $object)
376
+	{
377
+		switch ($object->_getStatus()) {
378
+			case TDBMObjectStateEnum::STATE_DELETED:
379
+				// Nothing to do, object already deleted.
380
+				return;
381
+			case TDBMObjectStateEnum::STATE_DETACHED:
382
+				throw new TDBMInvalidOperationException('Cannot delete a detached object');
383
+			case TDBMObjectStateEnum::STATE_NEW:
384
+				$this->deleteManyToManyRelationships($object);
385
+				foreach ($object->_getDbRows() as $dbRow) {
386
+					$this->removeFromToSaveObjectList($dbRow);
387
+				}
388
+				break;
389
+			case TDBMObjectStateEnum::STATE_DIRTY:
390
+				foreach ($object->_getDbRows() as $dbRow) {
391
+					$this->removeFromToSaveObjectList($dbRow);
392
+				}
393
+				// And continue deleting...
394
+			case TDBMObjectStateEnum::STATE_NOT_LOADED:
395
+			case TDBMObjectStateEnum::STATE_LOADED:
396
+				$this->deleteManyToManyRelationships($object);
397
+				// Let's delete db rows, in reverse order.
398
+				foreach (array_reverse($object->_getDbRows()) as $dbRow) {
399
+					$tableName = $dbRow->_getDbTableName();
400
+					$primaryKeys = $dbRow->_getPrimaryKeys();
401
+					$this->connection->delete($tableName, $primaryKeys);
402
+					$this->objectStorage->remove($dbRow->_getDbTableName(), $this->getObjectHash($primaryKeys));
403
+				}
404
+				break;
405
+			// @codeCoverageIgnoreStart
406
+			default:
407
+				throw new TDBMInvalidOperationException('Unexpected status for bean');
408
+			// @codeCoverageIgnoreEnd
409
+		}
410
+
411
+		$object->_setStatus(TDBMObjectStateEnum::STATE_DELETED);
412
+	}
413
+
414
+	/**
415
+	 * Removes all many to many relationships for this object.
416
+	 *
417
+	 * @param AbstractTDBMObject $object
418
+	 */
419
+	private function deleteManyToManyRelationships(AbstractTDBMObject $object)
420
+	{
421
+		foreach ($object->_getDbRows() as $tableName => $dbRow) {
422
+			$pivotTables = $this->tdbmSchemaAnalyzer->getPivotTableLinkedToTable($tableName);
423
+			foreach ($pivotTables as $pivotTable) {
424
+				$remoteBeans = $object->_getRelationships($pivotTable);
425
+				foreach ($remoteBeans as $remoteBean) {
426
+					$object->_removeRelationship($pivotTable, $remoteBean);
427
+				}
428
+			}
429
+		}
430
+		$this->persistManyToManyRelationships($object);
431
+	}
432
+
433
+	/**
434
+	 * This function removes the given object from the database. It will also remove all objects relied to the one given
435
+	 * by parameter before all.
436
+	 *
437
+	 * Notice: if the object has a multiple primary key, the function will not work.
438
+	 *
439
+	 * @param AbstractTDBMObject $objToDelete
440
+	 */
441
+	public function deleteCascade(AbstractTDBMObject $objToDelete)
442
+	{
443
+		$this->deleteAllConstraintWithThisObject($objToDelete);
444
+		$this->delete($objToDelete);
445
+	}
446
+
447
+	/**
448
+	 * This function is used only in TDBMService (private function)
449
+	 * It will call deleteCascade function foreach object relied with a foreign key to the object given by parameter.
450
+	 *
451
+	 * @param AbstractTDBMObject $obj
452
+	 */
453
+	private function deleteAllConstraintWithThisObject(AbstractTDBMObject $obj)
454
+	{
455
+		$dbRows = $obj->_getDbRows();
456
+		foreach ($dbRows as $dbRow) {
457
+			$tableName = $dbRow->_getDbTableName();
458
+			$pks = array_values($dbRow->_getPrimaryKeys());
459
+			if (!empty($pks)) {
460
+				$incomingFks = $this->tdbmSchemaAnalyzer->getIncomingForeignKeys($tableName);
461
+
462
+				foreach ($incomingFks as $incomingFk) {
463
+					$filter = array_combine($incomingFk->getLocalColumns(), $pks);
464
+
465
+					$results = $this->findObjects($incomingFk->getLocalTableName(), $filter);
466
+
467
+					foreach ($results as $bean) {
468
+						$this->deleteCascade($bean);
469
+					}
470
+				}
471
+			}
472
+		}
473
+	}
474
+
475
+	/**
476
+	 * This function performs a save() of all the objects that have been modified.
477
+	 */
478
+	public function completeSave()
479
+	{
480
+		foreach ($this->toSaveObjects as $dbRow) {
481
+			$this->save($dbRow->getTDBMObject());
482
+		}
483
+	}
484
+
485
+	/**
486
+	 * Takes in input a filter_bag (which can be about anything from a string to an array of TDBMObjects... see above from documentation),
487
+	 * and gives back a proper Filter object.
488
+	 *
489
+	 * @param mixed $filter_bag
490
+	 * @param int   $counter
491
+	 *
492
+	 * @return array First item: filter string, second item: parameters
493
+	 *
494
+	 * @throws TDBMException
495
+	 */
496
+	public function buildFilterFromFilterBag($filter_bag, $counter = 1)
497
+	{
498
+		if ($filter_bag === null) {
499
+			return ['', []];
500
+		} elseif (is_string($filter_bag)) {
501
+			return [$filter_bag, []];
502
+		} elseif (is_array($filter_bag)) {
503
+			$sqlParts = [];
504
+			$parameters = [];
505
+			foreach ($filter_bag as $column => $value) {
506
+				if (is_int($column)) {
507
+					list($subSqlPart, $subParameters) = $this->buildFilterFromFilterBag($value, $counter);
508
+					$sqlParts[] = $subSqlPart;
509
+					$parameters += $subParameters;
510
+				} else {
511
+					$paramName = 'tdbmparam'.$counter;
512
+					if (is_array($value)) {
513
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' IN :'.$paramName;
514
+					} else {
515
+						$sqlParts[] = $this->connection->quoteIdentifier($column).' = :'.$paramName;
516
+					}
517
+					$parameters[$paramName] = $value;
518
+					++$counter;
519
+				}
520
+			}
521
+
522
+			return [implode(' AND ', $sqlParts), $parameters];
523
+		} elseif ($filter_bag instanceof AbstractTDBMObject) {
524
+			$sqlParts = [];
525
+			$parameters = [];
526
+			$dbRows = $filter_bag->_getDbRows();
527
+			$dbRow = reset($dbRows);
528
+			$primaryKeys = $dbRow->_getPrimaryKeys();
529
+
530
+			foreach ($primaryKeys as $column => $value) {
531
+				$paramName = 'tdbmparam'.$counter;
532
+				$sqlParts[] = $this->connection->quoteIdentifier($dbRow->_getDbTableName()).'.'.$this->connection->quoteIdentifier($column).' = :'.$paramName;
533
+				$parameters[$paramName] = $value;
534
+				++$counter;
535
+			}
536
+
537
+			return [implode(' AND ', $sqlParts), $parameters];
538
+		} elseif ($filter_bag instanceof \Iterator) {
539
+			return $this->buildFilterFromFilterBag(iterator_to_array($filter_bag), $counter);
540
+		} else {
541
+			throw new TDBMException('Error in filter. An object has been passed that is neither a SQL string, nor an array, nor a bean, nor null.');
542
+		}
543
+	}
544
+
545
+	/**
546
+	 * @param string $table
547
+	 *
548
+	 * @return string[]
549
+	 */
550
+	public function getPrimaryKeyColumns($table)
551
+	{
552
+		if (!isset($this->primaryKeysColumns[$table])) {
553
+			$this->primaryKeysColumns[$table] = $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getPrimaryKeyColumns();
554
+
555
+			// TODO TDBM4: See if we need to improve error reporting if table name does not exist.
556
+
557
+			/*$arr = array();
558 558
             foreach ($this->connection->getPrimaryKey($table) as $col) {
559 559
                 $arr[] = $col->name;
560 560
             }
@@ -575,166 +575,166 @@  discard block
 block discarded – undo
575 575
                     throw new TDBMException($str);
576 576
                 }
577 577
             }*/
578
-        }
579
-
580
-        return $this->primaryKeysColumns[$table];
581
-    }
582
-
583
-    /**
584
-     * This is an internal function, you should not use it in your application.
585
-     * This is used internally by TDBM to add an object to the object cache.
586
-     *
587
-     * @param DbRow $dbRow
588
-     */
589
-    public function _addToCache(DbRow $dbRow)
590
-    {
591
-        $primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
592
-        $hash = $this->getObjectHash($primaryKey);
593
-        $this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
594
-    }
595
-
596
-    /**
597
-     * This is an internal function, you should not use it in your application.
598
-     * This is used internally by TDBM to remove the object from the list of objects that have been
599
-     * created/updated but not saved yet.
600
-     *
601
-     * @param DbRow $myObject
602
-     */
603
-    private function removeFromToSaveObjectList(DbRow $myObject)
604
-    {
605
-        unset($this->toSaveObjects[$myObject]);
606
-    }
607
-
608
-    /**
609
-     * This is an internal function, you should not use it in your application.
610
-     * This is used internally by TDBM to add an object to the list of objects that have been
611
-     * created/updated but not saved yet.
612
-     *
613
-     * @param AbstractTDBMObject $myObject
614
-     */
615
-    public function _addToToSaveObjectList(DbRow $myObject)
616
-    {
617
-        $this->toSaveObjects[$myObject] = true;
618
-    }
619
-
620
-    /**
621
-     * Generates all the daos and beans.
622
-     *
623
-     * @param string $daoFactoryClassName The classe name of the DAO factory
624
-     * @param string $daonamespace        The namespace for the DAOs, without trailing \
625
-     * @param string $beannamespace       The Namespace for the beans, without trailing \
626
-     * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
627
-     * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
628
-     *
629
-     * @return \string[] the list of tables
630
-     */
631
-    public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
632
-    {
633
-        // Purge cache before generating anything.
634
-        $this->cache->deleteAll();
635
-
636
-        $tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
-        if (null !== $composerFile) {
638
-            $tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
-        }
640
-
641
-        return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
-    }
643
-
644
-    /**
645
-     * @param array<string, string> $tableToBeanMap
646
-     */
647
-    public function setTableToBeanMap(array $tableToBeanMap)
648
-    {
649
-        $this->tableToBeanMap = $tableToBeanMap;
650
-    }
651
-
652
-    /**
653
-     * Returns the fully qualified class name of the bean associated with table $tableName.
654
-     *
655
-     *
656
-     * @param string $tableName
657
-     *
658
-     * @return string
659
-     */
660
-    public function getBeanClassName(string $tableName) : string
661
-    {
662
-        if (isset($this->tableToBeanMap[$tableName])) {
663
-            return $this->tableToBeanMap[$tableName];
664
-        } else {
665
-            throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
666
-        }
667
-    }
668
-
669
-    /**
670
-     * Saves $object by INSERTing or UPDAT(E)ing it in the database.
671
-     *
672
-     * @param AbstractTDBMObject $object
673
-     *
674
-     * @throws TDBMException
675
-     */
676
-    public function save(AbstractTDBMObject $object)
677
-    {
678
-        $status = $object->_getStatus();
679
-
680
-        if ($status === null) {
681
-            throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
682
-        }
683
-
684
-        // Let's attach this object if it is in detached state.
685
-        if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
686
-            $object->_attach($this);
687
-            $status = $object->_getStatus();
688
-        }
689
-
690
-        if ($status === TDBMObjectStateEnum::STATE_NEW) {
691
-            $dbRows = $object->_getDbRows();
692
-
693
-            $unindexedPrimaryKeys = array();
694
-
695
-            foreach ($dbRows as $dbRow) {
696
-                if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
697
-                    throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
698
-                }
699
-                $dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
700
-                $tableName = $dbRow->_getDbTableName();
701
-
702
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
703
-                $tableDescriptor = $schema->getTable($tableName);
704
-
705
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
706
-
707
-                $references = $dbRow->_getReferences();
708
-
709
-                // Let's save all references in NEW or DETACHED state (we need their primary key)
710
-                foreach ($references as $fkName => $reference) {
711
-                    if ($reference !== null) {
712
-                        $refStatus = $reference->_getStatus();
713
-                        if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
714
-                            try {
715
-                                $this->save($reference);
716
-                            } catch (TDBMCyclicReferenceException $e) {
717
-                                throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
718
-                            }
719
-                        }
720
-                    }
721
-                }
722
-
723
-                if (empty($unindexedPrimaryKeys)) {
724
-                    $primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
725
-                } else {
726
-                    // First insert, the children must have the same primary key as the parent.
727
-                    $primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
728
-                    $dbRow->_setPrimaryKeys($primaryKeys);
729
-                }
730
-
731
-                $dbRowData = $dbRow->_getDbRow();
732
-
733
-                // Let's see if the columns for primary key have been set before inserting.
734
-                // We assume that if one of the value of the PK has been set, the PK is set.
735
-                $isPkSet = !empty($primaryKeys);
736
-
737
-                /*if (!$isPkSet) {
578
+		}
579
+
580
+		return $this->primaryKeysColumns[$table];
581
+	}
582
+
583
+	/**
584
+	 * This is an internal function, you should not use it in your application.
585
+	 * This is used internally by TDBM to add an object to the object cache.
586
+	 *
587
+	 * @param DbRow $dbRow
588
+	 */
589
+	public function _addToCache(DbRow $dbRow)
590
+	{
591
+		$primaryKey = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
592
+		$hash = $this->getObjectHash($primaryKey);
593
+		$this->objectStorage->set($dbRow->_getDbTableName(), $hash, $dbRow);
594
+	}
595
+
596
+	/**
597
+	 * This is an internal function, you should not use it in your application.
598
+	 * This is used internally by TDBM to remove the object from the list of objects that have been
599
+	 * created/updated but not saved yet.
600
+	 *
601
+	 * @param DbRow $myObject
602
+	 */
603
+	private function removeFromToSaveObjectList(DbRow $myObject)
604
+	{
605
+		unset($this->toSaveObjects[$myObject]);
606
+	}
607
+
608
+	/**
609
+	 * This is an internal function, you should not use it in your application.
610
+	 * This is used internally by TDBM to add an object to the list of objects that have been
611
+	 * created/updated but not saved yet.
612
+	 *
613
+	 * @param AbstractTDBMObject $myObject
614
+	 */
615
+	public function _addToToSaveObjectList(DbRow $myObject)
616
+	{
617
+		$this->toSaveObjects[$myObject] = true;
618
+	}
619
+
620
+	/**
621
+	 * Generates all the daos and beans.
622
+	 *
623
+	 * @param string $daoFactoryClassName The classe name of the DAO factory
624
+	 * @param string $daonamespace        The namespace for the DAOs, without trailing \
625
+	 * @param string $beannamespace       The Namespace for the beans, without trailing \
626
+	 * @param bool   $storeInUtc          If the generated daos should store the date in UTC timezone instead of user's timezone
627
+	 * @param string $composerFile        If it's set, location of custom Composer file. Relative to project root
628
+	 *
629
+	 * @return \string[] the list of tables
630
+	 */
631
+	public function generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc, $composerFile = null)
632
+	{
633
+		// Purge cache before generating anything.
634
+		$this->cache->deleteAll();
635
+
636
+		$tdbmDaoGenerator = new TDBMDaoGenerator($this->schemaAnalyzer, $this->tdbmSchemaAnalyzer->getSchema(), $this->tdbmSchemaAnalyzer);
637
+		if (null !== $composerFile) {
638
+			$tdbmDaoGenerator->setComposerFile(__DIR__.'/../../../../../../../'.$composerFile);
639
+		}
640
+
641
+		return $tdbmDaoGenerator->generateAllDaosAndBeans($daoFactoryClassName, $daonamespace, $beannamespace, $storeInUtc);
642
+	}
643
+
644
+	/**
645
+	 * @param array<string, string> $tableToBeanMap
646
+	 */
647
+	public function setTableToBeanMap(array $tableToBeanMap)
648
+	{
649
+		$this->tableToBeanMap = $tableToBeanMap;
650
+	}
651
+
652
+	/**
653
+	 * Returns the fully qualified class name of the bean associated with table $tableName.
654
+	 *
655
+	 *
656
+	 * @param string $tableName
657
+	 *
658
+	 * @return string
659
+	 */
660
+	public function getBeanClassName(string $tableName) : string
661
+	{
662
+		if (isset($this->tableToBeanMap[$tableName])) {
663
+			return $this->tableToBeanMap[$tableName];
664
+		} else {
665
+			throw new TDBMInvalidArgumentException(sprintf('Could not find a map between table "%s" and any bean. Does table "%s" exists?', $tableName, $tableName));
666
+		}
667
+	}
668
+
669
+	/**
670
+	 * Saves $object by INSERTing or UPDAT(E)ing it in the database.
671
+	 *
672
+	 * @param AbstractTDBMObject $object
673
+	 *
674
+	 * @throws TDBMException
675
+	 */
676
+	public function save(AbstractTDBMObject $object)
677
+	{
678
+		$status = $object->_getStatus();
679
+
680
+		if ($status === null) {
681
+			throw new TDBMException(sprintf('Your bean for class %s has no status. It is likely that you overloaded the __construct method and forgot to call parent::__construct.', get_class($object)));
682
+		}
683
+
684
+		// Let's attach this object if it is in detached state.
685
+		if ($status === TDBMObjectStateEnum::STATE_DETACHED) {
686
+			$object->_attach($this);
687
+			$status = $object->_getStatus();
688
+		}
689
+
690
+		if ($status === TDBMObjectStateEnum::STATE_NEW) {
691
+			$dbRows = $object->_getDbRows();
692
+
693
+			$unindexedPrimaryKeys = array();
694
+
695
+			foreach ($dbRows as $dbRow) {
696
+				if ($dbRow->_getStatus() == TDBMObjectStateEnum::STATE_SAVING) {
697
+					throw TDBMCyclicReferenceException::createCyclicReference($dbRow->_getDbTableName(), $object);
698
+				}
699
+				$dbRow->_setStatus(TDBMObjectStateEnum::STATE_SAVING);
700
+				$tableName = $dbRow->_getDbTableName();
701
+
702
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
703
+				$tableDescriptor = $schema->getTable($tableName);
704
+
705
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($tableName);
706
+
707
+				$references = $dbRow->_getReferences();
708
+
709
+				// Let's save all references in NEW or DETACHED state (we need their primary key)
710
+				foreach ($references as $fkName => $reference) {
711
+					if ($reference !== null) {
712
+						$refStatus = $reference->_getStatus();
713
+						if ($refStatus === TDBMObjectStateEnum::STATE_NEW || $refStatus === TDBMObjectStateEnum::STATE_DETACHED) {
714
+							try {
715
+								$this->save($reference);
716
+							} catch (TDBMCyclicReferenceException $e) {
717
+								throw TDBMCyclicReferenceException::extendCyclicReference($e, $dbRow->_getDbTableName(), $object, $fkName);
718
+							}
719
+						}
720
+					}
721
+				}
722
+
723
+				if (empty($unindexedPrimaryKeys)) {
724
+					$primaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
725
+				} else {
726
+					// First insert, the children must have the same primary key as the parent.
727
+					$primaryKeys = $this->_getPrimaryKeysFromIndexedPrimaryKeys($tableName, $unindexedPrimaryKeys);
728
+					$dbRow->_setPrimaryKeys($primaryKeys);
729
+				}
730
+
731
+				$dbRowData = $dbRow->_getDbRow();
732
+
733
+				// Let's see if the columns for primary key have been set before inserting.
734
+				// We assume that if one of the value of the PK has been set, the PK is set.
735
+				$isPkSet = !empty($primaryKeys);
736
+
737
+				/*if (!$isPkSet) {
738 738
                     // if there is no autoincrement and no pk set, let's go in error.
739 739
                     $isAutoIncrement = true;
740 740
 
@@ -752,30 +752,30 @@  discard block
 block discarded – undo
752 752
 
753 753
                 }*/
754 754
 
755
-                $types = [];
756
-                $escapedDbRowData = [];
755
+				$types = [];
756
+				$escapedDbRowData = [];
757 757
 
758
-                foreach ($dbRowData as $columnName => $value) {
759
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
760
-                    $types[] = $columnDescriptor->getType();
761
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
762
-                }
758
+				foreach ($dbRowData as $columnName => $value) {
759
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
760
+					$types[] = $columnDescriptor->getType();
761
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
762
+				}
763 763
 
764
-                $this->connection->insert($tableName, $escapedDbRowData, $types);
764
+				$this->connection->insert($tableName, $escapedDbRowData, $types);
765 765
 
766
-                if (!$isPkSet && count($primaryKeyColumns) == 1) {
767
-                    $id = $this->connection->lastInsertId();
768
-                    $pkColumn = $primaryKeyColumns[0];
769
-                    // lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
770
-                    $id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
771
-                    $primaryKeys[$pkColumn] = $id;
772
-                }
766
+				if (!$isPkSet && count($primaryKeyColumns) == 1) {
767
+					$id = $this->connection->lastInsertId();
768
+					$pkColumn = $primaryKeyColumns[0];
769
+					// lastInsertId returns a string but the column type is usually a int. Let's convert it back to the correct type.
770
+					$id = $tableDescriptor->getColumn($pkColumn)->getType()->convertToPHPValue($id, $this->getConnection()->getDatabasePlatform());
771
+					$primaryKeys[$pkColumn] = $id;
772
+				}
773 773
 
774
-                // TODO: change this to some private magic accessor in future
775
-                $dbRow->_setPrimaryKeys($primaryKeys);
776
-                $unindexedPrimaryKeys = array_values($primaryKeys);
774
+				// TODO: change this to some private magic accessor in future
775
+				$dbRow->_setPrimaryKeys($primaryKeys);
776
+				$unindexedPrimaryKeys = array_values($primaryKeys);
777 777
 
778
-                /*
778
+				/*
779 779
                  * When attached, on "save", we check if the column updated is part of a primary key
780 780
                  * If this is part of a primary key, we call the _update_id method that updates the id in the list of known objects.
781 781
                  * This method should first verify that the id is not already used (and is not auto-incremented)
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
                  *
786 786
                  */
787 787
 
788
-                /*try {
788
+				/*try {
789 789
                     $this->db_connection->exec($sql);
790 790
                 } catch (TDBMException $e) {
791 791
                     $this->db_onerror = true;
@@ -804,405 +804,405 @@  discard block
 block discarded – undo
804 804
                     }
805 805
                 }*/
806 806
 
807
-                // Let's remove this object from the $new_objects static table.
808
-                $this->removeFromToSaveObjectList($dbRow);
809
-
810
-                // TODO: change this behaviour to something more sensible performance-wise
811
-                // Maybe a setting to trigger this globally?
812
-                //$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
813
-                //$this->db_modified_state = false;
814
-                //$dbRow = array();
815
-
816
-                // Let's add this object to the list of objects in cache.
817
-                $this->_addToCache($dbRow);
818
-            }
819
-
820
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
821
-        } elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
822
-            $dbRows = $object->_getDbRows();
823
-
824
-            foreach ($dbRows as $dbRow) {
825
-                $references = $dbRow->_getReferences();
826
-
827
-                // Let's save all references in NEW state (we need their primary key)
828
-                foreach ($references as $fkName => $reference) {
829
-                    if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
830
-                        $this->save($reference);
831
-                    }
832
-                }
833
-
834
-                // Let's first get the primary keys
835
-                $tableName = $dbRow->_getDbTableName();
836
-                $dbRowData = $dbRow->_getDbRow();
837
-
838
-                $schema = $this->tdbmSchemaAnalyzer->getSchema();
839
-                $tableDescriptor = $schema->getTable($tableName);
840
-
841
-                $primaryKeys = $dbRow->_getPrimaryKeys();
842
-
843
-                $types = [];
844
-                $escapedDbRowData = [];
845
-                $escapedPrimaryKeys = [];
846
-
847
-                foreach ($dbRowData as $columnName => $value) {
848
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
849
-                    $types[] = $columnDescriptor->getType();
850
-                    $escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
851
-                }
852
-                foreach ($primaryKeys as $columnName => $value) {
853
-                    $columnDescriptor = $tableDescriptor->getColumn($columnName);
854
-                    $types[] = $columnDescriptor->getType();
855
-                    $escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
856
-                }
857
-
858
-                $this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
859
-
860
-                // Let's check if the primary key has been updated...
861
-                $needsUpdatePk = false;
862
-                foreach ($primaryKeys as $column => $value) {
863
-                    if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
864
-                        $needsUpdatePk = true;
865
-                        break;
866
-                    }
867
-                }
868
-                if ($needsUpdatePk) {
869
-                    $this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
870
-                    $newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
871
-                    $dbRow->_setPrimaryKeys($newPrimaryKeys);
872
-                    $this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
873
-                }
874
-
875
-                // Let's remove this object from the list of objects to save.
876
-                $this->removeFromToSaveObjectList($dbRow);
877
-            }
878
-
879
-            $object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
880
-        } elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
881
-            throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
882
-        }
883
-
884
-        // Finally, let's save all the many to many relationships to this bean.
885
-        $this->persistManyToManyRelationships($object);
886
-    }
887
-
888
-    private function persistManyToManyRelationships(AbstractTDBMObject $object)
889
-    {
890
-        foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
891
-            $tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
892
-            list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
893
-
894
-            $toRemoveFromStorage = [];
895
-
896
-            foreach ($storage as $remoteBean) {
897
-                /* @var $remoteBean AbstractTDBMObject */
898
-                $statusArr = $storage[$remoteBean];
899
-                $status = $statusArr['status'];
900
-                $reverse = $statusArr['reverse'];
901
-                if ($reverse) {
902
-                    continue;
903
-                }
904
-
905
-                if ($status === 'new') {
906
-                    $remoteBeanStatus = $remoteBean->_getStatus();
907
-                    if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
908
-                        // Let's save remote bean if needed.
909
-                        $this->save($remoteBean);
910
-                    }
911
-
912
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
913
-
914
-                    $types = [];
915
-                    $escapedFilters = [];
916
-
917
-                    foreach ($filters as $columnName => $value) {
918
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
919
-                        $types[] = $columnDescriptor->getType();
920
-                        $escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
921
-                    }
922
-
923
-                    $this->connection->insert($pivotTableName, $escapedFilters, $types);
924
-
925
-                    // Finally, let's mark relationships as saved.
926
-                    $statusArr['status'] = 'loaded';
927
-                    $storage[$remoteBean] = $statusArr;
928
-                    $remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
929
-                    $remoteStatusArr = $remoteStorage[$object];
930
-                    $remoteStatusArr['status'] = 'loaded';
931
-                    $remoteStorage[$object] = $remoteStatusArr;
932
-                } elseif ($status === 'delete') {
933
-                    $filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
934
-
935
-                    $types = [];
936
-
937
-                    foreach ($filters as $columnName => $value) {
938
-                        $columnDescriptor = $tableDescriptor->getColumn($columnName);
939
-                        $types[] = $columnDescriptor->getType();
940
-                    }
941
-
942
-                    $this->connection->delete($pivotTableName, $filters, $types);
943
-
944
-                    // Finally, let's remove relationships completely from bean.
945
-                    $toRemoveFromStorage[] = $remoteBean;
946
-
947
-                    $remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
948
-                }
949
-            }
950
-
951
-            // Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
952
-            // Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
953
-            foreach ($toRemoveFromStorage as $remoteBean) {
954
-                $storage->detach($remoteBean);
955
-            }
956
-        }
957
-    }
958
-
959
-    private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
960
-    {
961
-        $localBeanPk = $this->getPrimaryKeyValues($localBean);
962
-        $remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
963
-        $localColumns = $localFk->getLocalColumns();
964
-        $remoteColumns = $remoteFk->getLocalColumns();
965
-
966
-        $localFilters = array_combine($localColumns, $localBeanPk);
967
-        $remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
968
-
969
-        return array_merge($localFilters, $remoteFilters);
970
-    }
971
-
972
-    /**
973
-     * Returns the "values" of the primary key.
974
-     * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
975
-     *
976
-     * @param AbstractTDBMObject $bean
977
-     *
978
-     * @return array numerically indexed array of values
979
-     */
980
-    private function getPrimaryKeyValues(AbstractTDBMObject $bean)
981
-    {
982
-        $dbRows = $bean->_getDbRows();
983
-        $dbRow = reset($dbRows);
984
-
985
-        return array_values($dbRow->_getPrimaryKeys());
986
-    }
987
-
988
-    /**
989
-     * Returns a unique hash used to store the object based on its primary key.
990
-     * If the array contains only one value, then the value is returned.
991
-     * Otherwise, a hash representing the array is returned.
992
-     *
993
-     * @param array $primaryKeys An array of columns => values forming the primary key
994
-     *
995
-     * @return string
996
-     */
997
-    public function getObjectHash(array $primaryKeys)
998
-    {
999
-        if (count($primaryKeys) === 1) {
1000
-            return reset($primaryKeys);
1001
-        } else {
1002
-            ksort($primaryKeys);
1003
-
1004
-            return md5(json_encode($primaryKeys));
1005
-        }
1006
-    }
1007
-
1008
-    /**
1009
-     * Returns an array of primary keys from the object.
1010
-     * The primary keys are extracted from the object columns and not from the primary keys stored in the
1011
-     * $primaryKeys variable of the object.
1012
-     *
1013
-     * @param DbRow $dbRow
1014
-     *
1015
-     * @return array Returns an array of column => value
1016
-     */
1017
-    public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1018
-    {
1019
-        $table = $dbRow->_getDbTableName();
1020
-        $dbRowData = $dbRow->_getDbRow();
1021
-
1022
-        return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1023
-    }
1024
-
1025
-    /**
1026
-     * Returns an array of primary keys for the given row.
1027
-     * The primary keys are extracted from the object columns.
1028
-     *
1029
-     * @param $table
1030
-     * @param array $columns
1031
-     *
1032
-     * @return array
1033
-     */
1034
-    public function _getPrimaryKeysFromObjectData($table, array $columns)
1035
-    {
1036
-        $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1037
-        $values = array();
1038
-        foreach ($primaryKeyColumns as $column) {
1039
-            if (isset($columns[$column])) {
1040
-                $values[$column] = $columns[$column];
1041
-            }
1042
-        }
1043
-
1044
-        return $values;
1045
-    }
1046
-
1047
-    /**
1048
-     * Attaches $object to this TDBMService.
1049
-     * The $object must be in DETACHED state and will pass in NEW state.
1050
-     *
1051
-     * @param AbstractTDBMObject $object
1052
-     *
1053
-     * @throws TDBMInvalidOperationException
1054
-     */
1055
-    public function attach(AbstractTDBMObject $object)
1056
-    {
1057
-        $object->_attach($this);
1058
-    }
1059
-
1060
-    /**
1061
-     * Returns an associative array (column => value) for the primary keys from the table name and an
1062
-     * indexed array of primary key values.
1063
-     *
1064
-     * @param string $tableName
1065
-     * @param array  $indexedPrimaryKeys
1066
-     */
1067
-    public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1068
-    {
1069
-        $primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1070
-
1071
-        if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1072
-            throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
807
+				// Let's remove this object from the $new_objects static table.
808
+				$this->removeFromToSaveObjectList($dbRow);
809
+
810
+				// TODO: change this behaviour to something more sensible performance-wise
811
+				// Maybe a setting to trigger this globally?
812
+				//$this->status = TDBMObjectStateEnum::STATE_NOT_LOADED;
813
+				//$this->db_modified_state = false;
814
+				//$dbRow = array();
815
+
816
+				// Let's add this object to the list of objects in cache.
817
+				$this->_addToCache($dbRow);
818
+			}
819
+
820
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
821
+		} elseif ($status === TDBMObjectStateEnum::STATE_DIRTY) {
822
+			$dbRows = $object->_getDbRows();
823
+
824
+			foreach ($dbRows as $dbRow) {
825
+				$references = $dbRow->_getReferences();
826
+
827
+				// Let's save all references in NEW state (we need their primary key)
828
+				foreach ($references as $fkName => $reference) {
829
+					if ($reference !== null && $reference->_getStatus() === TDBMObjectStateEnum::STATE_NEW) {
830
+						$this->save($reference);
831
+					}
832
+				}
833
+
834
+				// Let's first get the primary keys
835
+				$tableName = $dbRow->_getDbTableName();
836
+				$dbRowData = $dbRow->_getDbRow();
837
+
838
+				$schema = $this->tdbmSchemaAnalyzer->getSchema();
839
+				$tableDescriptor = $schema->getTable($tableName);
840
+
841
+				$primaryKeys = $dbRow->_getPrimaryKeys();
842
+
843
+				$types = [];
844
+				$escapedDbRowData = [];
845
+				$escapedPrimaryKeys = [];
846
+
847
+				foreach ($dbRowData as $columnName => $value) {
848
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
849
+					$types[] = $columnDescriptor->getType();
850
+					$escapedDbRowData[$this->connection->quoteIdentifier($columnName)] = $value;
851
+				}
852
+				foreach ($primaryKeys as $columnName => $value) {
853
+					$columnDescriptor = $tableDescriptor->getColumn($columnName);
854
+					$types[] = $columnDescriptor->getType();
855
+					$escapedPrimaryKeys[$this->connection->quoteIdentifier($columnName)] = $value;
856
+				}
857
+
858
+				$this->connection->update($tableName, $escapedDbRowData, $escapedPrimaryKeys, $types);
859
+
860
+				// Let's check if the primary key has been updated...
861
+				$needsUpdatePk = false;
862
+				foreach ($primaryKeys as $column => $value) {
863
+					if (!isset($dbRowData[$column]) || $dbRowData[$column] != $value) {
864
+						$needsUpdatePk = true;
865
+						break;
866
+					}
867
+				}
868
+				if ($needsUpdatePk) {
869
+					$this->objectStorage->remove($tableName, $this->getObjectHash($primaryKeys));
870
+					$newPrimaryKeys = $this->getPrimaryKeysForObjectFromDbRow($dbRow);
871
+					$dbRow->_setPrimaryKeys($newPrimaryKeys);
872
+					$this->objectStorage->set($tableName, $this->getObjectHash($primaryKeys), $dbRow);
873
+				}
874
+
875
+				// Let's remove this object from the list of objects to save.
876
+				$this->removeFromToSaveObjectList($dbRow);
877
+			}
878
+
879
+			$object->_setStatus(TDBMObjectStateEnum::STATE_LOADED);
880
+		} elseif ($status === TDBMObjectStateEnum::STATE_DELETED) {
881
+			throw new TDBMInvalidOperationException('This object has been deleted. It cannot be saved.');
882
+		}
883
+
884
+		// Finally, let's save all the many to many relationships to this bean.
885
+		$this->persistManyToManyRelationships($object);
886
+	}
887
+
888
+	private function persistManyToManyRelationships(AbstractTDBMObject $object)
889
+	{
890
+		foreach ($object->_getCachedRelationships() as $pivotTableName => $storage) {
891
+			$tableDescriptor = $this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName);
892
+			list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $object);
893
+
894
+			$toRemoveFromStorage = [];
895
+
896
+			foreach ($storage as $remoteBean) {
897
+				/* @var $remoteBean AbstractTDBMObject */
898
+				$statusArr = $storage[$remoteBean];
899
+				$status = $statusArr['status'];
900
+				$reverse = $statusArr['reverse'];
901
+				if ($reverse) {
902
+					continue;
903
+				}
904
+
905
+				if ($status === 'new') {
906
+					$remoteBeanStatus = $remoteBean->_getStatus();
907
+					if ($remoteBeanStatus === TDBMObjectStateEnum::STATE_NEW || $remoteBeanStatus === TDBMObjectStateEnum::STATE_DETACHED) {
908
+						// Let's save remote bean if needed.
909
+						$this->save($remoteBean);
910
+					}
911
+
912
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
913
+
914
+					$types = [];
915
+					$escapedFilters = [];
916
+
917
+					foreach ($filters as $columnName => $value) {
918
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
919
+						$types[] = $columnDescriptor->getType();
920
+						$escapedFilters[$this->connection->quoteIdentifier($columnName)] = $value;
921
+					}
922
+
923
+					$this->connection->insert($pivotTableName, $escapedFilters, $types);
924
+
925
+					// Finally, let's mark relationships as saved.
926
+					$statusArr['status'] = 'loaded';
927
+					$storage[$remoteBean] = $statusArr;
928
+					$remoteStorage = $remoteBean->_getCachedRelationships()[$pivotTableName];
929
+					$remoteStatusArr = $remoteStorage[$object];
930
+					$remoteStatusArr['status'] = 'loaded';
931
+					$remoteStorage[$object] = $remoteStatusArr;
932
+				} elseif ($status === 'delete') {
933
+					$filters = $this->getPivotFilters($object, $remoteBean, $localFk, $remoteFk);
934
+
935
+					$types = [];
936
+
937
+					foreach ($filters as $columnName => $value) {
938
+						$columnDescriptor = $tableDescriptor->getColumn($columnName);
939
+						$types[] = $columnDescriptor->getType();
940
+					}
941
+
942
+					$this->connection->delete($pivotTableName, $filters, $types);
943
+
944
+					// Finally, let's remove relationships completely from bean.
945
+					$toRemoveFromStorage[] = $remoteBean;
946
+
947
+					$remoteBean->_getCachedRelationships()[$pivotTableName]->detach($object);
948
+				}
949
+			}
950
+
951
+			// Note: due to https://bugs.php.net/bug.php?id=65629, we cannot delete an element inside a foreach loop on a SplStorageObject.
952
+			// Therefore, we cache elements in the $toRemoveFromStorage to remove them at a later stage.
953
+			foreach ($toRemoveFromStorage as $remoteBean) {
954
+				$storage->detach($remoteBean);
955
+			}
956
+		}
957
+	}
958
+
959
+	private function getPivotFilters(AbstractTDBMObject $localBean, AbstractTDBMObject $remoteBean, ForeignKeyConstraint $localFk, ForeignKeyConstraint $remoteFk)
960
+	{
961
+		$localBeanPk = $this->getPrimaryKeyValues($localBean);
962
+		$remoteBeanPk = $this->getPrimaryKeyValues($remoteBean);
963
+		$localColumns = $localFk->getLocalColumns();
964
+		$remoteColumns = $remoteFk->getLocalColumns();
965
+
966
+		$localFilters = array_combine($localColumns, $localBeanPk);
967
+		$remoteFilters = array_combine($remoteColumns, $remoteBeanPk);
968
+
969
+		return array_merge($localFilters, $remoteFilters);
970
+	}
971
+
972
+	/**
973
+	 * Returns the "values" of the primary key.
974
+	 * This returns the primary key from the $primaryKey attribute, not the one stored in the columns.
975
+	 *
976
+	 * @param AbstractTDBMObject $bean
977
+	 *
978
+	 * @return array numerically indexed array of values
979
+	 */
980
+	private function getPrimaryKeyValues(AbstractTDBMObject $bean)
981
+	{
982
+		$dbRows = $bean->_getDbRows();
983
+		$dbRow = reset($dbRows);
984
+
985
+		return array_values($dbRow->_getPrimaryKeys());
986
+	}
987
+
988
+	/**
989
+	 * Returns a unique hash used to store the object based on its primary key.
990
+	 * If the array contains only one value, then the value is returned.
991
+	 * Otherwise, a hash representing the array is returned.
992
+	 *
993
+	 * @param array $primaryKeys An array of columns => values forming the primary key
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function getObjectHash(array $primaryKeys)
998
+	{
999
+		if (count($primaryKeys) === 1) {
1000
+			return reset($primaryKeys);
1001
+		} else {
1002
+			ksort($primaryKeys);
1003
+
1004
+			return md5(json_encode($primaryKeys));
1005
+		}
1006
+	}
1007
+
1008
+	/**
1009
+	 * Returns an array of primary keys from the object.
1010
+	 * The primary keys are extracted from the object columns and not from the primary keys stored in the
1011
+	 * $primaryKeys variable of the object.
1012
+	 *
1013
+	 * @param DbRow $dbRow
1014
+	 *
1015
+	 * @return array Returns an array of column => value
1016
+	 */
1017
+	public function getPrimaryKeysForObjectFromDbRow(DbRow $dbRow)
1018
+	{
1019
+		$table = $dbRow->_getDbTableName();
1020
+		$dbRowData = $dbRow->_getDbRow();
1021
+
1022
+		return $this->_getPrimaryKeysFromObjectData($table, $dbRowData);
1023
+	}
1024
+
1025
+	/**
1026
+	 * Returns an array of primary keys for the given row.
1027
+	 * The primary keys are extracted from the object columns.
1028
+	 *
1029
+	 * @param $table
1030
+	 * @param array $columns
1031
+	 *
1032
+	 * @return array
1033
+	 */
1034
+	public function _getPrimaryKeysFromObjectData($table, array $columns)
1035
+	{
1036
+		$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1037
+		$values = array();
1038
+		foreach ($primaryKeyColumns as $column) {
1039
+			if (isset($columns[$column])) {
1040
+				$values[$column] = $columns[$column];
1041
+			}
1042
+		}
1043
+
1044
+		return $values;
1045
+	}
1046
+
1047
+	/**
1048
+	 * Attaches $object to this TDBMService.
1049
+	 * The $object must be in DETACHED state and will pass in NEW state.
1050
+	 *
1051
+	 * @param AbstractTDBMObject $object
1052
+	 *
1053
+	 * @throws TDBMInvalidOperationException
1054
+	 */
1055
+	public function attach(AbstractTDBMObject $object)
1056
+	{
1057
+		$object->_attach($this);
1058
+	}
1059
+
1060
+	/**
1061
+	 * Returns an associative array (column => value) for the primary keys from the table name and an
1062
+	 * indexed array of primary key values.
1063
+	 *
1064
+	 * @param string $tableName
1065
+	 * @param array  $indexedPrimaryKeys
1066
+	 */
1067
+	public function _getPrimaryKeysFromIndexedPrimaryKeys($tableName, array $indexedPrimaryKeys)
1068
+	{
1069
+		$primaryKeyColumns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getPrimaryKeyColumns();
1070
+
1071
+		if (count($primaryKeyColumns) !== count($indexedPrimaryKeys)) {
1072
+			throw new TDBMException(sprintf('Wrong number of columns passed for primary key. Expected %s columns for table "%s",
1073 1073
 			got %s instead.', count($primaryKeyColumns), $tableName, count($indexedPrimaryKeys)));
1074
-        }
1075
-
1076
-        return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1077
-    }
1078
-
1079
-    /**
1080
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1081
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1082
-     *
1083
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1084
-     * we must be able to find all other tables.
1085
-     *
1086
-     * @param string[] $tables
1087
-     *
1088
-     * @return string[]
1089
-     */
1090
-    public function _getLinkBetweenInheritedTables(array $tables)
1091
-    {
1092
-        sort($tables);
1093
-
1094
-        return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1095
-            function () use ($tables) {
1096
-                return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1097
-            });
1098
-    }
1099
-
1100
-    /**
1101
-     * Return the list of tables (from child to parent) joining the tables passed in parameter.
1102
-     * Tables must be in a single line of inheritance. The method will find missing tables.
1103
-     *
1104
-     * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1105
-     * we must be able to find all other tables.
1106
-     *
1107
-     * @param string[] $tables
1108
-     *
1109
-     * @return string[]
1110
-     */
1111
-    private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1112
-    {
1113
-        $schemaAnalyzer = $this->schemaAnalyzer;
1114
-
1115
-        foreach ($tables as $currentTable) {
1116
-            $allParents = [$currentTable];
1117
-            while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1118
-                $currentTable = $currentFk->getForeignTableName();
1119
-                $allParents[] = $currentTable;
1120
-            }
1121
-
1122
-            // Now, does the $allParents contain all the tables we want?
1123
-            $notFoundTables = array_diff($tables, $allParents);
1124
-            if (empty($notFoundTables)) {
1125
-                // We have a winner!
1126
-                return $allParents;
1127
-            }
1128
-        }
1129
-
1130
-        throw TDBMInheritanceException::create($tables);
1131
-    }
1132
-
1133
-    /**
1134
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1135
-     *
1136
-     * @param string $table
1137
-     *
1138
-     * @return string[]
1139
-     */
1140
-    public function _getRelatedTablesByInheritance($table)
1141
-    {
1142
-        return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1143
-            return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1144
-        });
1145
-    }
1146
-
1147
-    /**
1148
-     * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1149
-     *
1150
-     * @param string $table
1151
-     *
1152
-     * @return string[]
1153
-     */
1154
-    private function _getRelatedTablesByInheritanceWithoutCache($table)
1155
-    {
1156
-        $schemaAnalyzer = $this->schemaAnalyzer;
1157
-
1158
-        // Let's scan the parent tables
1159
-        $currentTable = $table;
1160
-
1161
-        $parentTables = [];
1162
-
1163
-        // Get parent relationship
1164
-        while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1165
-            $currentTable = $currentFk->getForeignTableName();
1166
-            $parentTables[] = $currentTable;
1167
-        }
1168
-
1169
-        // Let's recurse in children
1170
-        $childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1171
-
1172
-        return array_merge(array_reverse($parentTables), $childrenTables);
1173
-    }
1174
-
1175
-    /**
1176
-     * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1177
-     *
1178
-     * @param string $table
1179
-     *
1180
-     * @return string[]
1181
-     */
1182
-    private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1183
-    {
1184
-        $tables = [$table];
1185
-        $keys = $schemaAnalyzer->getChildrenRelationships($table);
1186
-
1187
-        foreach ($keys as $key) {
1188
-            $tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1189
-        }
1190
-
1191
-        return $tables;
1192
-    }
1193
-
1194
-    /**
1195
-     * Casts a foreign key into SQL, assuming table name is used with no alias.
1196
-     * The returned value does contain only one table. For instance:.
1197
-     *
1198
-     * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1199
-     *
1200
-     * @param ForeignKeyConstraint $fk
1201
-     * @param bool                 $leftTableIsLocal
1202
-     *
1203
-     * @return string
1204
-     */
1205
-    /*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1074
+		}
1075
+
1076
+		return array_combine($primaryKeyColumns, $indexedPrimaryKeys);
1077
+	}
1078
+
1079
+	/**
1080
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1081
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1082
+	 *
1083
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1084
+	 * we must be able to find all other tables.
1085
+	 *
1086
+	 * @param string[] $tables
1087
+	 *
1088
+	 * @return string[]
1089
+	 */
1090
+	public function _getLinkBetweenInheritedTables(array $tables)
1091
+	{
1092
+		sort($tables);
1093
+
1094
+		return $this->fromCache($this->cachePrefix.'_linkbetweeninheritedtables_'.implode('__split__', $tables),
1095
+			function () use ($tables) {
1096
+				return $this->_getLinkBetweenInheritedTablesWithoutCache($tables);
1097
+			});
1098
+	}
1099
+
1100
+	/**
1101
+	 * Return the list of tables (from child to parent) joining the tables passed in parameter.
1102
+	 * Tables must be in a single line of inheritance. The method will find missing tables.
1103
+	 *
1104
+	 * Algorithm: one of those tables is the ultimate child. From this child, by recursively getting the parent,
1105
+	 * we must be able to find all other tables.
1106
+	 *
1107
+	 * @param string[] $tables
1108
+	 *
1109
+	 * @return string[]
1110
+	 */
1111
+	private function _getLinkBetweenInheritedTablesWithoutCache(array $tables)
1112
+	{
1113
+		$schemaAnalyzer = $this->schemaAnalyzer;
1114
+
1115
+		foreach ($tables as $currentTable) {
1116
+			$allParents = [$currentTable];
1117
+			while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1118
+				$currentTable = $currentFk->getForeignTableName();
1119
+				$allParents[] = $currentTable;
1120
+			}
1121
+
1122
+			// Now, does the $allParents contain all the tables we want?
1123
+			$notFoundTables = array_diff($tables, $allParents);
1124
+			if (empty($notFoundTables)) {
1125
+				// We have a winner!
1126
+				return $allParents;
1127
+			}
1128
+		}
1129
+
1130
+		throw TDBMInheritanceException::create($tables);
1131
+	}
1132
+
1133
+	/**
1134
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1135
+	 *
1136
+	 * @param string $table
1137
+	 *
1138
+	 * @return string[]
1139
+	 */
1140
+	public function _getRelatedTablesByInheritance($table)
1141
+	{
1142
+		return $this->fromCache($this->cachePrefix.'_relatedtables_'.$table, function () use ($table) {
1143
+			return $this->_getRelatedTablesByInheritanceWithoutCache($table);
1144
+		});
1145
+	}
1146
+
1147
+	/**
1148
+	 * Returns the list of tables related to this table (via a parent or child inheritance relationship).
1149
+	 *
1150
+	 * @param string $table
1151
+	 *
1152
+	 * @return string[]
1153
+	 */
1154
+	private function _getRelatedTablesByInheritanceWithoutCache($table)
1155
+	{
1156
+		$schemaAnalyzer = $this->schemaAnalyzer;
1157
+
1158
+		// Let's scan the parent tables
1159
+		$currentTable = $table;
1160
+
1161
+		$parentTables = [];
1162
+
1163
+		// Get parent relationship
1164
+		while ($currentFk = $schemaAnalyzer->getParentRelationship($currentTable)) {
1165
+			$currentTable = $currentFk->getForeignTableName();
1166
+			$parentTables[] = $currentTable;
1167
+		}
1168
+
1169
+		// Let's recurse in children
1170
+		$childrenTables = $this->exploreChildrenTablesRelationships($schemaAnalyzer, $table);
1171
+
1172
+		return array_merge(array_reverse($parentTables), $childrenTables);
1173
+	}
1174
+
1175
+	/**
1176
+	 * Explore all the children and descendant of $table and returns ForeignKeyConstraints on those.
1177
+	 *
1178
+	 * @param string $table
1179
+	 *
1180
+	 * @return string[]
1181
+	 */
1182
+	private function exploreChildrenTablesRelationships(SchemaAnalyzer $schemaAnalyzer, $table)
1183
+	{
1184
+		$tables = [$table];
1185
+		$keys = $schemaAnalyzer->getChildrenRelationships($table);
1186
+
1187
+		foreach ($keys as $key) {
1188
+			$tables = array_merge($tables, $this->exploreChildrenTablesRelationships($schemaAnalyzer, $key->getLocalTableName()));
1189
+		}
1190
+
1191
+		return $tables;
1192
+	}
1193
+
1194
+	/**
1195
+	 * Casts a foreign key into SQL, assuming table name is used with no alias.
1196
+	 * The returned value does contain only one table. For instance:.
1197
+	 *
1198
+	 * " LEFT JOIN table2 ON table1.id = table2.table1_id"
1199
+	 *
1200
+	 * @param ForeignKeyConstraint $fk
1201
+	 * @param bool                 $leftTableIsLocal
1202
+	 *
1203
+	 * @return string
1204
+	 */
1205
+	/*private function foreignKeyToSql(ForeignKeyConstraint $fk, $leftTableIsLocal) {
1206 1206
         $onClauses = [];
1207 1207
         $foreignTableName = $this->connection->quoteIdentifier($fk->getForeignTableName());
1208 1208
         $foreignColumns = $fk->getForeignColumns();
@@ -1228,411 +1228,411 @@  discard block
 block discarded – undo
1228 1228
         }
1229 1229
     }*/
1230 1230
 
1231
-    /**
1232
-     * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1233
-     *
1234
-     * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1235
-     * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1236
-     *
1237
-     * The findObjects method takes in parameter:
1238
-     * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1239
-     * 			`$mainTable` parameter should be the name of an existing table in database.
1240
-     *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1241
-     *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1242
-     *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1243
-     *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1244
-     *          Instead, please consider passing parameters (see documentation for more details).
1245
-     *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1246
-     *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1247
-     *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1248
-     *
1249
-     * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1250
-     * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1251
-     *
1252
-     * Finally, if filter_bag is null, the whole table is returned.
1253
-     *
1254
-     * @param string                       $mainTable             The name of the table queried
1255
-     * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1256
-     * @param array                        $parameters
1257
-     * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1258
-     * @param array                        $additionalTablesFetch
1259
-     * @param int                          $mode
1260
-     * @param string                       $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1261
-     *
1262
-     * @return ResultIterator An object representing an array of results
1263
-     *
1264
-     * @throws TDBMException
1265
-     */
1266
-    public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1267
-    {
1268
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1269
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1270
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1271
-        }
1272
-
1273
-        $mode = $mode ?: $this->mode;
1274
-
1275
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1276
-
1277
-        $parameters = array_merge($parameters, $additionalParameters);
1278
-
1279
-        $queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1280
-
1281
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1282
-    }
1283
-
1284
-    /**
1285
-     * @param string                       $mainTable   The name of the table queried
1286
-     * @param string                       $from        The from sql statement
1287
-     * @param string|array|null            $filter      The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1288
-     * @param array                        $parameters
1289
-     * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1290
-     * @param int                          $mode
1291
-     * @param string                       $className   Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1292
-     *
1293
-     * @return ResultIterator An object representing an array of results
1294
-     *
1295
-     * @throws TDBMException
1296
-     */
1297
-    public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1298
-    {
1299
-        // $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1300
-        if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1301
-            throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1302
-        }
1303
-
1304
-        $mode = $mode ?: $this->mode;
1305
-
1306
-        list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1307
-
1308
-        $parameters = array_merge($parameters, $additionalParameters);
1309
-
1310
-        $queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1311
-
1312
-        return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1313
-    }
1314
-
1315
-    /**
1316
-     * @param $table
1317
-     * @param array  $primaryKeys
1318
-     * @param array  $additionalTablesFetch
1319
-     * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1320
-     * @param string $className
1321
-     *
1322
-     * @return AbstractTDBMObject
1323
-     *
1324
-     * @throws TDBMException
1325
-     */
1326
-    public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1327
-    {
1328
-        $primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1329
-        $hash = $this->getObjectHash($primaryKeys);
1330
-
1331
-        if ($this->objectStorage->has($table, $hash)) {
1332
-            $dbRow = $this->objectStorage->get($table, $hash);
1333
-            $bean = $dbRow->getTDBMObject();
1334
-            if ($className !== null && !is_a($bean, $className)) {
1335
-                throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1336
-            }
1337
-
1338
-            return $bean;
1339
-        }
1340
-
1341
-        // Are we performing lazy fetching?
1342
-        if ($lazy === true) {
1343
-            // Can we perform lazy fetching?
1344
-            $tables = $this->_getRelatedTablesByInheritance($table);
1345
-            // Only allowed if no inheritance.
1346
-            if (count($tables) === 1) {
1347
-                if ($className === null) {
1348
-                    $className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1349
-                }
1350
-
1351
-                // Let's construct the bean
1352
-                if (!isset($this->reflectionClassCache[$className])) {
1353
-                    $this->reflectionClassCache[$className] = new \ReflectionClass($className);
1354
-                }
1355
-                // Let's bypass the constructor when creating the bean!
1356
-                $bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1357
-                /* @var $bean AbstractTDBMObject */
1358
-                $bean->_constructLazy($table, $primaryKeys, $this);
1359
-
1360
-                return $bean;
1361
-            }
1362
-        }
1363
-
1364
-        // Did not find the object in cache? Let's query it!
1365
-        return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1366
-    }
1367
-
1368
-    /**
1369
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1370
-     *
1371
-     * @param string            $mainTable             The name of the table queried
1372
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1373
-     * @param array             $parameters
1374
-     * @param array             $additionalTablesFetch
1375
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1376
-     *
1377
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1378
-     *
1379
-     * @throws TDBMException
1380
-     */
1381
-    public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1382
-    {
1383
-        $objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1384
-        $page = $objects->take(0, 2);
1385
-        $count = $page->count();
1386
-        if ($count > 1) {
1387
-            throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1388
-        } elseif ($count === 0) {
1389
-            return;
1390
-        }
1391
-
1392
-        return $page[0];
1393
-    }
1394
-
1395
-    /**
1396
-     * Returns a unique bean (or null) according to the filters passed in parameter.
1397
-     *
1398
-     * @param string            $mainTable  The name of the table queried
1399
-     * @param string            $from       The from sql statement
1400
-     * @param string|array|null $filter     The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1401
-     * @param array             $parameters
1402
-     * @param string            $className  Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1403
-     *
1404
-     * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1405
-     *
1406
-     * @throws TDBMException
1407
-     */
1408
-    public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1409
-    {
1410
-        $objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1411
-        $page = $objects->take(0, 2);
1412
-        $count = $page->count();
1413
-        if ($count > 1) {
1414
-            throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1415
-        } elseif ($count === 0) {
1416
-            return;
1417
-        }
1418
-
1419
-        return $page[0];
1420
-    }
1421
-
1422
-    /**
1423
-     * Returns a unique bean according to the filters passed in parameter.
1424
-     * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1425
-     *
1426
-     * @param string            $mainTable             The name of the table queried
1427
-     * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1428
-     * @param array             $parameters
1429
-     * @param array             $additionalTablesFetch
1430
-     * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1431
-     *
1432
-     * @return AbstractTDBMObject The object we want
1433
-     *
1434
-     * @throws TDBMException
1435
-     */
1436
-    public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1437
-    {
1438
-        $bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1439
-        if ($bean === null) {
1440
-            throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1441
-        }
1442
-
1443
-        return $bean;
1444
-    }
1445
-
1446
-    /**
1447
-     * @param array $beanData An array of data: array<table, array<column, value>>
1448
-     *
1449
-     * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1450
-     *
1451
-     * @throws TDBMInheritanceException
1452
-     */
1453
-    public function _getClassNameFromBeanData(array $beanData)
1454
-    {
1455
-        if (count($beanData) === 1) {
1456
-            $tableName = array_keys($beanData)[0];
1457
-            $allTables = [$tableName];
1458
-        } else {
1459
-            $tables = [];
1460
-            foreach ($beanData as $table => $row) {
1461
-                $primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1462
-                $pkSet = false;
1463
-                foreach ($primaryKeyColumns as $columnName) {
1464
-                    if ($row[$columnName] !== null) {
1465
-                        $pkSet = true;
1466
-                        break;
1467
-                    }
1468
-                }
1469
-                if ($pkSet) {
1470
-                    $tables[] = $table;
1471
-                }
1472
-            }
1473
-
1474
-            // $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1475
-            try {
1476
-                $allTables = $this->_getLinkBetweenInheritedTables($tables);
1477
-            } catch (TDBMInheritanceException $e) {
1478
-                throw TDBMInheritanceException::extendException($e, $this, $beanData);
1479
-            }
1480
-            $tableName = $allTables[0];
1481
-        }
1482
-
1483
-        // Only one table in this bean. Life is sweat, let's look at its type:
1484
-        if (isset($this->tableToBeanMap[$tableName])) {
1485
-            return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1486
-        } else {
1487
-            return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1488
-        }
1489
-    }
1490
-
1491
-    /**
1492
-     * Returns an item from cache or computes it using $closure and puts it in cache.
1493
-     *
1494
-     * @param string   $key
1495
-     * @param callable $closure
1496
-     *
1497
-     * @return mixed
1498
-     */
1499
-    private function fromCache(string $key, callable $closure)
1500
-    {
1501
-        $item = $this->cache->fetch($key);
1502
-        if ($item === false) {
1503
-            $item = $closure();
1504
-            $this->cache->save($key, $item);
1505
-        }
1506
-
1507
-        return $item;
1508
-    }
1509
-
1510
-    /**
1511
-     * Returns the foreign key object.
1512
-     *
1513
-     * @param string $table
1514
-     * @param string $fkName
1515
-     *
1516
-     * @return ForeignKeyConstraint
1517
-     */
1518
-    public function _getForeignKeyByName(string $table, string $fkName)
1519
-    {
1520
-        return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1521
-    }
1522
-
1523
-    /**
1524
-     * @param $pivotTableName
1525
-     * @param AbstractTDBMObject $bean
1526
-     *
1527
-     * @return AbstractTDBMObject[]
1528
-     */
1529
-    public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1530
-    {
1531
-        list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1532
-        /* @var $localFk ForeignKeyConstraint */
1533
-        /* @var $remoteFk ForeignKeyConstraint */
1534
-        $remoteTable = $remoteFk->getForeignTableName();
1535
-
1536
-        $primaryKeys = $this->getPrimaryKeyValues($bean);
1537
-        $columnNames = array_map(function ($name) use ($pivotTableName) {
1538
-            return $pivotTableName.'.'.$name;
1539
-        }, $localFk->getLocalColumns());
1540
-
1541
-        $filter = array_combine($columnNames, $primaryKeys);
1542
-
1543
-        return $this->findObjects($remoteTable, $filter);
1544
-    }
1545
-
1546
-    /**
1547
-     * @param $pivotTableName
1548
-     * @param AbstractTDBMObject $bean The LOCAL bean
1549
-     *
1550
-     * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1551
-     *
1552
-     * @throws TDBMException
1553
-     */
1554
-    private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1555
-    {
1556
-        $fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1557
-        $table1 = $fks[0]->getForeignTableName();
1558
-        $table2 = $fks[1]->getForeignTableName();
1559
-
1560
-        $beanTables = array_map(function (DbRow $dbRow) {
1561
-            return $dbRow->_getDbTableName();
1562
-        }, $bean->_getDbRows());
1563
-
1564
-        if (in_array($table1, $beanTables)) {
1565
-            return [$fks[0], $fks[1]];
1566
-        } elseif (in_array($table2, $beanTables)) {
1567
-            return [$fks[1], $fks[0]];
1568
-        } else {
1569
-            throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1570
-        }
1571
-    }
1572
-
1573
-    /**
1574
-     * Returns a list of pivot tables linked to $bean.
1575
-     *
1576
-     * @param AbstractTDBMObject $bean
1577
-     *
1578
-     * @return string[]
1579
-     */
1580
-    public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1581
-    {
1582
-        $junctionTables = [];
1583
-        $allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1584
-        foreach ($bean->_getDbRows() as $dbRow) {
1585
-            foreach ($allJunctionTables as $table) {
1586
-                // There are exactly 2 FKs since this is a pivot table.
1587
-                $fks = array_values($table->getForeignKeys());
1588
-
1589
-                if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1590
-                    $junctionTables[] = $table->getName();
1591
-                }
1592
-            }
1593
-        }
1594
-
1595
-        return $junctionTables;
1596
-    }
1597
-
1598
-    /**
1599
-     * Array of types for tables.
1600
-     * Key: table name
1601
-     * Value: array of types indexed by column.
1602
-     *
1603
-     * @var array[]
1604
-     */
1605
-    private $typesForTable = [];
1606
-
1607
-    /**
1608
-     * @internal
1609
-     *
1610
-     * @param string $tableName
1611
-     *
1612
-     * @return Type[]
1613
-     */
1614
-    public function _getColumnTypesForTable(string $tableName)
1615
-    {
1616
-        if (!isset($typesForTable[$tableName])) {
1617
-            $columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1618
-            $typesForTable[$tableName] = array_map(function (Column $column) {
1619
-                return $column->getType();
1620
-            }, $columns);
1621
-        }
1622
-
1623
-        return $typesForTable[$tableName];
1624
-    }
1625
-
1626
-    /**
1627
-     * Sets the minimum log level.
1628
-     * $level must be one of Psr\Log\LogLevel::xxx.
1629
-     *
1630
-     * Defaults to LogLevel::WARNING
1631
-     *
1632
-     * @param string $level
1633
-     */
1634
-    public function setLogLevel(string $level)
1635
-    {
1636
-        $this->logger = new LevelFilter($this->rootLogger, $level);
1637
-    }
1231
+	/**
1232
+	 * Returns a `ResultIterator` object representing filtered records of "$mainTable" .
1233
+	 *
1234
+	 * The findObjects method should be the most used query method in TDBM if you want to query the database for objects.
1235
+	 * (Note: if you want to query the database for an object by its primary key, use the findObjectByPk method).
1236
+	 *
1237
+	 * The findObjects method takes in parameter:
1238
+	 * 	- mainTable: the kind of bean you want to retrieve. In TDBM, a bean matches a database row, so the
1239
+	 * 			`$mainTable` parameter should be the name of an existing table in database.
1240
+	 *  - filter: The filter is a filter bag. It is what you use to filter your request (the WHERE part in SQL).
1241
+	 *          It can be a string (SQL Where clause), or even a bean or an associative array (key = column to filter, value = value to find)
1242
+	 *  - parameters: The parameters used in the filter. If you pass a SQL string as a filter, be sure to avoid
1243
+	 *          concatenating parameters in the string (this leads to SQL injection and also to poor caching performance).
1244
+	 *          Instead, please consider passing parameters (see documentation for more details).
1245
+	 *  - additionalTablesFetch: An array of SQL tables names. The beans related to those tables will be fetched along
1246
+	 *          the main table. This is useful to avoid hitting the database with numerous subqueries.
1247
+	 *  - mode: The fetch mode of the result. See `setFetchMode()` method for more details.
1248
+	 *
1249
+	 * The `findObjects` method will return a `ResultIterator`. A `ResultIterator` is an object that behaves as an array
1250
+	 * (in ARRAY mode) at least. It can be iterated using a `foreach` loop.
1251
+	 *
1252
+	 * Finally, if filter_bag is null, the whole table is returned.
1253
+	 *
1254
+	 * @param string                       $mainTable             The name of the table queried
1255
+	 * @param string|array|null            $filter                The SQL filters to apply to the query (the WHERE part). Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1256
+	 * @param array                        $parameters
1257
+	 * @param string|UncheckedOrderBy|null $orderString           The ORDER BY part of the query. Columns from tables different from $mainTable must be prefixed by the table name (in the form: table.column)
1258
+	 * @param array                        $additionalTablesFetch
1259
+	 * @param int                          $mode
1260
+	 * @param string                       $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1261
+	 *
1262
+	 * @return ResultIterator An object representing an array of results
1263
+	 *
1264
+	 * @throws TDBMException
1265
+	 */
1266
+	public function findObjects(string $mainTable, $filter = null, array $parameters = array(), $orderString = null, array $additionalTablesFetch = array(), $mode = null, string $className = null)
1267
+	{
1268
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1269
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1270
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1271
+		}
1272
+
1273
+		$mode = $mode ?: $this->mode;
1274
+
1275
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1276
+
1277
+		$parameters = array_merge($parameters, $additionalParameters);
1278
+
1279
+		$queryFactory = new FindObjectsQueryFactory($mainTable, $additionalTablesFetch, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer);
1280
+
1281
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1282
+	}
1283
+
1284
+	/**
1285
+	 * @param string                       $mainTable   The name of the table queried
1286
+	 * @param string                       $from        The from sql statement
1287
+	 * @param string|array|null            $filter      The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1288
+	 * @param array                        $parameters
1289
+	 * @param string|UncheckedOrderBy|null $orderString The ORDER BY part of the query. All columns must be prefixed by the table name (in the form: table.column)
1290
+	 * @param int                          $mode
1291
+	 * @param string                       $className   Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1292
+	 *
1293
+	 * @return ResultIterator An object representing an array of results
1294
+	 *
1295
+	 * @throws TDBMException
1296
+	 */
1297
+	public function findObjectsFromSql(string $mainTable, string $from, $filter = null, array $parameters = array(), $orderString = null, $mode = null, string $className = null)
1298
+	{
1299
+		// $mainTable is not secured in MagicJoin, let's add a bit of security to avoid SQL injection.
1300
+		if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $mainTable)) {
1301
+			throw new TDBMException(sprintf("Invalid table name: '%s'", $mainTable));
1302
+		}
1303
+
1304
+		$mode = $mode ?: $this->mode;
1305
+
1306
+		list($filterString, $additionalParameters) = $this->buildFilterFromFilterBag($filter);
1307
+
1308
+		$parameters = array_merge($parameters, $additionalParameters);
1309
+
1310
+		$queryFactory = new FindObjectsFromSqlQueryFactory($mainTable, $from, $filterString, $orderString, $this, $this->tdbmSchemaAnalyzer->getSchema(), $this->orderByAnalyzer, $this->schemaAnalyzer, $this->cache, $this->cachePrefix);
1311
+
1312
+		return new ResultIterator($queryFactory, $parameters, $this->objectStorage, $className, $this, $this->magicQuery, $mode, $this->logger);
1313
+	}
1314
+
1315
+	/**
1316
+	 * @param $table
1317
+	 * @param array  $primaryKeys
1318
+	 * @param array  $additionalTablesFetch
1319
+	 * @param bool   $lazy                  Whether to perform lazy loading on this object or not
1320
+	 * @param string $className
1321
+	 *
1322
+	 * @return AbstractTDBMObject
1323
+	 *
1324
+	 * @throws TDBMException
1325
+	 */
1326
+	public function findObjectByPk(string $table, array $primaryKeys, array $additionalTablesFetch = array(), bool $lazy = false, string $className = null)
1327
+	{
1328
+		$primaryKeys = $this->_getPrimaryKeysFromObjectData($table, $primaryKeys);
1329
+		$hash = $this->getObjectHash($primaryKeys);
1330
+
1331
+		if ($this->objectStorage->has($table, $hash)) {
1332
+			$dbRow = $this->objectStorage->get($table, $hash);
1333
+			$bean = $dbRow->getTDBMObject();
1334
+			if ($className !== null && !is_a($bean, $className)) {
1335
+				throw new TDBMException("TDBM cannot create a bean of class '".$className."'. The requested object was already loaded and its class is '".get_class($bean)."'");
1336
+			}
1337
+
1338
+			return $bean;
1339
+		}
1340
+
1341
+		// Are we performing lazy fetching?
1342
+		if ($lazy === true) {
1343
+			// Can we perform lazy fetching?
1344
+			$tables = $this->_getRelatedTablesByInheritance($table);
1345
+			// Only allowed if no inheritance.
1346
+			if (count($tables) === 1) {
1347
+				if ($className === null) {
1348
+					$className = isset($this->tableToBeanMap[$table]) ? $this->tableToBeanMap[$table] : 'Mouf\\Database\\TDBM\\TDBMObject';
1349
+				}
1350
+
1351
+				// Let's construct the bean
1352
+				if (!isset($this->reflectionClassCache[$className])) {
1353
+					$this->reflectionClassCache[$className] = new \ReflectionClass($className);
1354
+				}
1355
+				// Let's bypass the constructor when creating the bean!
1356
+				$bean = $this->reflectionClassCache[$className]->newInstanceWithoutConstructor();
1357
+				/* @var $bean AbstractTDBMObject */
1358
+				$bean->_constructLazy($table, $primaryKeys, $this);
1359
+
1360
+				return $bean;
1361
+			}
1362
+		}
1363
+
1364
+		// Did not find the object in cache? Let's query it!
1365
+		return $this->findObjectOrFail($table, $primaryKeys, [], $additionalTablesFetch, $className);
1366
+	}
1367
+
1368
+	/**
1369
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1370
+	 *
1371
+	 * @param string            $mainTable             The name of the table queried
1372
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1373
+	 * @param array             $parameters
1374
+	 * @param array             $additionalTablesFetch
1375
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1376
+	 *
1377
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1378
+	 *
1379
+	 * @throws TDBMException
1380
+	 */
1381
+	public function findObject(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1382
+	{
1383
+		$objects = $this->findObjects($mainTable, $filter, $parameters, null, $additionalTablesFetch, self::MODE_ARRAY, $className);
1384
+		$page = $objects->take(0, 2);
1385
+		$count = $page->count();
1386
+		if ($count > 1) {
1387
+			throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1388
+		} elseif ($count === 0) {
1389
+			return;
1390
+		}
1391
+
1392
+		return $page[0];
1393
+	}
1394
+
1395
+	/**
1396
+	 * Returns a unique bean (or null) according to the filters passed in parameter.
1397
+	 *
1398
+	 * @param string            $mainTable  The name of the table queried
1399
+	 * @param string            $from       The from sql statement
1400
+	 * @param string|array|null $filter     The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1401
+	 * @param array             $parameters
1402
+	 * @param string            $className  Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1403
+	 *
1404
+	 * @return AbstractTDBMObject|null The object we want, or null if no object matches the filters
1405
+	 *
1406
+	 * @throws TDBMException
1407
+	 */
1408
+	public function findObjectFromSql($mainTable, $from, $filter = null, array $parameters = array(), $className = null)
1409
+	{
1410
+		$objects = $this->findObjectsFromSql($mainTable, $from, $filter, $parameters, null, self::MODE_ARRAY, $className);
1411
+		$page = $objects->take(0, 2);
1412
+		$count = $page->count();
1413
+		if ($count > 1) {
1414
+			throw new DuplicateRowException("Error while querying an object for table '$mainTable': More than 1 row have been returned, but we should have received at most one.");
1415
+		} elseif ($count === 0) {
1416
+			return;
1417
+		}
1418
+
1419
+		return $page[0];
1420
+	}
1421
+
1422
+	/**
1423
+	 * Returns a unique bean according to the filters passed in parameter.
1424
+	 * Throws a NoBeanFoundException if no bean was found for the filter passed in parameter.
1425
+	 *
1426
+	 * @param string            $mainTable             The name of the table queried
1427
+	 * @param string|array|null $filter                The SQL filters to apply to the query (the WHERE part). All columns must be prefixed by the table name (in the form: table.column)
1428
+	 * @param array             $parameters
1429
+	 * @param array             $additionalTablesFetch
1430
+	 * @param string            $className             Optional: The name of the class to instantiate. This class must extend the TDBMObject class. If none is specified, a TDBMObject instance will be returned
1431
+	 *
1432
+	 * @return AbstractTDBMObject The object we want
1433
+	 *
1434
+	 * @throws TDBMException
1435
+	 */
1436
+	public function findObjectOrFail(string $mainTable, $filter = null, array $parameters = array(), array $additionalTablesFetch = array(), string $className = null)
1437
+	{
1438
+		$bean = $this->findObject($mainTable, $filter, $parameters, $additionalTablesFetch, $className);
1439
+		if ($bean === null) {
1440
+			throw new NoBeanFoundException("No result found for query on table '".$mainTable."'");
1441
+		}
1442
+
1443
+		return $bean;
1444
+	}
1445
+
1446
+	/**
1447
+	 * @param array $beanData An array of data: array<table, array<column, value>>
1448
+	 *
1449
+	 * @return array an array with first item = class name, second item = table name and third item = list of tables needed
1450
+	 *
1451
+	 * @throws TDBMInheritanceException
1452
+	 */
1453
+	public function _getClassNameFromBeanData(array $beanData)
1454
+	{
1455
+		if (count($beanData) === 1) {
1456
+			$tableName = array_keys($beanData)[0];
1457
+			$allTables = [$tableName];
1458
+		} else {
1459
+			$tables = [];
1460
+			foreach ($beanData as $table => $row) {
1461
+				$primaryKeyColumns = $this->getPrimaryKeyColumns($table);
1462
+				$pkSet = false;
1463
+				foreach ($primaryKeyColumns as $columnName) {
1464
+					if ($row[$columnName] !== null) {
1465
+						$pkSet = true;
1466
+						break;
1467
+					}
1468
+				}
1469
+				if ($pkSet) {
1470
+					$tables[] = $table;
1471
+				}
1472
+			}
1473
+
1474
+			// $tables contains the tables for this bean. Let's view the top most part of the hierarchy
1475
+			try {
1476
+				$allTables = $this->_getLinkBetweenInheritedTables($tables);
1477
+			} catch (TDBMInheritanceException $e) {
1478
+				throw TDBMInheritanceException::extendException($e, $this, $beanData);
1479
+			}
1480
+			$tableName = $allTables[0];
1481
+		}
1482
+
1483
+		// Only one table in this bean. Life is sweat, let's look at its type:
1484
+		if (isset($this->tableToBeanMap[$tableName])) {
1485
+			return [$this->tableToBeanMap[$tableName], $tableName, $allTables];
1486
+		} else {
1487
+			return ['Mouf\\Database\\TDBM\\TDBMObject', $tableName, $allTables];
1488
+		}
1489
+	}
1490
+
1491
+	/**
1492
+	 * Returns an item from cache or computes it using $closure and puts it in cache.
1493
+	 *
1494
+	 * @param string   $key
1495
+	 * @param callable $closure
1496
+	 *
1497
+	 * @return mixed
1498
+	 */
1499
+	private function fromCache(string $key, callable $closure)
1500
+	{
1501
+		$item = $this->cache->fetch($key);
1502
+		if ($item === false) {
1503
+			$item = $closure();
1504
+			$this->cache->save($key, $item);
1505
+		}
1506
+
1507
+		return $item;
1508
+	}
1509
+
1510
+	/**
1511
+	 * Returns the foreign key object.
1512
+	 *
1513
+	 * @param string $table
1514
+	 * @param string $fkName
1515
+	 *
1516
+	 * @return ForeignKeyConstraint
1517
+	 */
1518
+	public function _getForeignKeyByName(string $table, string $fkName)
1519
+	{
1520
+		return $this->tdbmSchemaAnalyzer->getSchema()->getTable($table)->getForeignKey($fkName);
1521
+	}
1522
+
1523
+	/**
1524
+	 * @param $pivotTableName
1525
+	 * @param AbstractTDBMObject $bean
1526
+	 *
1527
+	 * @return AbstractTDBMObject[]
1528
+	 */
1529
+	public function _getRelatedBeans(string $pivotTableName, AbstractTDBMObject $bean)
1530
+	{
1531
+		list($localFk, $remoteFk) = $this->getPivotTableForeignKeys($pivotTableName, $bean);
1532
+		/* @var $localFk ForeignKeyConstraint */
1533
+		/* @var $remoteFk ForeignKeyConstraint */
1534
+		$remoteTable = $remoteFk->getForeignTableName();
1535
+
1536
+		$primaryKeys = $this->getPrimaryKeyValues($bean);
1537
+		$columnNames = array_map(function ($name) use ($pivotTableName) {
1538
+			return $pivotTableName.'.'.$name;
1539
+		}, $localFk->getLocalColumns());
1540
+
1541
+		$filter = array_combine($columnNames, $primaryKeys);
1542
+
1543
+		return $this->findObjects($remoteTable, $filter);
1544
+	}
1545
+
1546
+	/**
1547
+	 * @param $pivotTableName
1548
+	 * @param AbstractTDBMObject $bean The LOCAL bean
1549
+	 *
1550
+	 * @return ForeignKeyConstraint[] First item: the LOCAL bean, second item: the REMOTE bean
1551
+	 *
1552
+	 * @throws TDBMException
1553
+	 */
1554
+	private function getPivotTableForeignKeys(string $pivotTableName, AbstractTDBMObject $bean)
1555
+	{
1556
+		$fks = array_values($this->tdbmSchemaAnalyzer->getSchema()->getTable($pivotTableName)->getForeignKeys());
1557
+		$table1 = $fks[0]->getForeignTableName();
1558
+		$table2 = $fks[1]->getForeignTableName();
1559
+
1560
+		$beanTables = array_map(function (DbRow $dbRow) {
1561
+			return $dbRow->_getDbTableName();
1562
+		}, $bean->_getDbRows());
1563
+
1564
+		if (in_array($table1, $beanTables)) {
1565
+			return [$fks[0], $fks[1]];
1566
+		} elseif (in_array($table2, $beanTables)) {
1567
+			return [$fks[1], $fks[0]];
1568
+		} else {
1569
+			throw new TDBMException("Unexpected bean type in getPivotTableForeignKeys. Awaiting beans from table {$table1} and {$table2} for pivot table {$pivotTableName}");
1570
+		}
1571
+	}
1572
+
1573
+	/**
1574
+	 * Returns a list of pivot tables linked to $bean.
1575
+	 *
1576
+	 * @param AbstractTDBMObject $bean
1577
+	 *
1578
+	 * @return string[]
1579
+	 */
1580
+	public function _getPivotTablesLinkedToBean(AbstractTDBMObject $bean)
1581
+	{
1582
+		$junctionTables = [];
1583
+		$allJunctionTables = $this->schemaAnalyzer->detectJunctionTables(true);
1584
+		foreach ($bean->_getDbRows() as $dbRow) {
1585
+			foreach ($allJunctionTables as $table) {
1586
+				// There are exactly 2 FKs since this is a pivot table.
1587
+				$fks = array_values($table->getForeignKeys());
1588
+
1589
+				if ($fks[0]->getForeignTableName() === $dbRow->_getDbTableName() || $fks[1]->getForeignTableName() === $dbRow->_getDbTableName()) {
1590
+					$junctionTables[] = $table->getName();
1591
+				}
1592
+			}
1593
+		}
1594
+
1595
+		return $junctionTables;
1596
+	}
1597
+
1598
+	/**
1599
+	 * Array of types for tables.
1600
+	 * Key: table name
1601
+	 * Value: array of types indexed by column.
1602
+	 *
1603
+	 * @var array[]
1604
+	 */
1605
+	private $typesForTable = [];
1606
+
1607
+	/**
1608
+	 * @internal
1609
+	 *
1610
+	 * @param string $tableName
1611
+	 *
1612
+	 * @return Type[]
1613
+	 */
1614
+	public function _getColumnTypesForTable(string $tableName)
1615
+	{
1616
+		if (!isset($typesForTable[$tableName])) {
1617
+			$columns = $this->tdbmSchemaAnalyzer->getSchema()->getTable($tableName)->getColumns();
1618
+			$typesForTable[$tableName] = array_map(function (Column $column) {
1619
+				return $column->getType();
1620
+			}, $columns);
1621
+		}
1622
+
1623
+		return $typesForTable[$tableName];
1624
+	}
1625
+
1626
+	/**
1627
+	 * Sets the minimum log level.
1628
+	 * $level must be one of Psr\Log\LogLevel::xxx.
1629
+	 *
1630
+	 * Defaults to LogLevel::WARNING
1631
+	 *
1632
+	 * @param string $level
1633
+	 */
1634
+	public function setLogLevel(string $level)
1635
+	{
1636
+		$this->logger = new LevelFilter($this->rootLogger, $level);
1637
+	}
1638 1638
 }
Please login to merge, or discard this patch.
src/Mouf/Database/TDBM/Utils/AbstractBeanPropertyDescriptor.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -9,131 +9,131 @@
 block discarded – undo
9 9
  */
10 10
 abstract class AbstractBeanPropertyDescriptor
11 11
 {
12
-    /**
13
-     * @var Table
14
-     */
15
-    protected $table;
16
-
17
-    /**
18
-     * Whether to use the more complex name in case of conflict.
19
-     *
20
-     * @var bool
21
-     */
22
-    protected $alternativeName = false;
23
-
24
-    /**
25
-     * @param Table $table
26
-     */
27
-    public function __construct(Table $table)
28
-    {
29
-        $this->table = $table;
30
-    }
31
-
32
-    /**
33
-     * Use the more complex name in case of conflict.
34
-     */
35
-    public function useAlternativeName()
36
-    {
37
-        $this->alternativeName = true;
38
-    }
39
-
40
-    /**
41
-     * Returns the name of the class linked to this property or null if this is not a foreign key.
42
-     *
43
-     * @return null|string
44
-     */
45
-    abstract public function getClassName();
46
-
47
-    /**
48
-     * Returns the param annotation for this property (useful for constructor).
49
-     *
50
-     * @return string
51
-     */
52
-    abstract public function getParamAnnotation();
53
-
54
-    public function getVariableName()
55
-    {
56
-        return '$'.$this->getLowerCamelCaseName();
57
-    }
58
-
59
-    public function getLowerCamelCaseName()
60
-    {
61
-        return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
62
-    }
63
-
64
-    abstract public function getUpperCamelCaseName();
65
-
66
-    public function getSetterName()
67
-    {
68
-        return 'set'.$this->getUpperCamelCaseName();
69
-    }
70
-
71
-    public function getGetterName()
72
-    {
73
-        return 'get'.$this->getUpperCamelCaseName();
74
-    }
75
-
76
-    /**
77
-     * Returns the PHP code used in the ben constructor for this property.
78
-     *
79
-     * @return string
80
-     */
81
-    public function getConstructorAssignCode()
82
-    {
83
-        $str = '        $this->%s(%s);';
84
-
85
-        return sprintf($str, $this->getSetterName(), $this->getVariableName());
86
-    }
87
-
88
-    /**
89
-     * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
90
-     *
91
-     * @return bool
92
-     */
93
-    abstract public function isCompulsory();
94
-
95
-    /**
96
-     * Returns true if the property has a default value.
97
-     *
98
-     * @return bool
99
-     */
100
-    abstract public function hasDefault();
101
-
102
-    /**
103
-     * Returns the code that assigns a value to its default value.
104
-     *
105
-     * @return string
106
-     *
107
-     * @throws \TDBMException
108
-     */
109
-    abstract public function assignToDefaultCode();
110
-
111
-    /**
112
-     * Returns true if the property is the primary key.
113
-     *
114
-     * @return bool
115
-     */
116
-    abstract public function isPrimaryKey();
117
-
118
-    /**
119
-     * @return Table
120
-     */
121
-    public function getTable()
122
-    {
123
-        return $this->table;
124
-    }
125
-
126
-    /**
127
-     * Returns the PHP code for getters and setters.
128
-     *
129
-     * @return string
130
-     */
131
-    abstract public function getGetterSetterCode();
132
-
133
-    /**
134
-     * Returns the part of code useful when doing json serialization.
135
-     *
136
-     * @return string
137
-     */
138
-    abstract public function getJsonSerializeCode();
12
+	/**
13
+	 * @var Table
14
+	 */
15
+	protected $table;
16
+
17
+	/**
18
+	 * Whether to use the more complex name in case of conflict.
19
+	 *
20
+	 * @var bool
21
+	 */
22
+	protected $alternativeName = false;
23
+
24
+	/**
25
+	 * @param Table $table
26
+	 */
27
+	public function __construct(Table $table)
28
+	{
29
+		$this->table = $table;
30
+	}
31
+
32
+	/**
33
+	 * Use the more complex name in case of conflict.
34
+	 */
35
+	public function useAlternativeName()
36
+	{
37
+		$this->alternativeName = true;
38
+	}
39
+
40
+	/**
41
+	 * Returns the name of the class linked to this property or null if this is not a foreign key.
42
+	 *
43
+	 * @return null|string
44
+	 */
45
+	abstract public function getClassName();
46
+
47
+	/**
48
+	 * Returns the param annotation for this property (useful for constructor).
49
+	 *
50
+	 * @return string
51
+	 */
52
+	abstract public function getParamAnnotation();
53
+
54
+	public function getVariableName()
55
+	{
56
+		return '$'.$this->getLowerCamelCaseName();
57
+	}
58
+
59
+	public function getLowerCamelCaseName()
60
+	{
61
+		return TDBMDaoGenerator::toVariableName($this->getUpperCamelCaseName());
62
+	}
63
+
64
+	abstract public function getUpperCamelCaseName();
65
+
66
+	public function getSetterName()
67
+	{
68
+		return 'set'.$this->getUpperCamelCaseName();
69
+	}
70
+
71
+	public function getGetterName()
72
+	{
73
+		return 'get'.$this->getUpperCamelCaseName();
74
+	}
75
+
76
+	/**
77
+	 * Returns the PHP code used in the ben constructor for this property.
78
+	 *
79
+	 * @return string
80
+	 */
81
+	public function getConstructorAssignCode()
82
+	{
83
+		$str = '        $this->%s(%s);';
84
+
85
+		return sprintf($str, $this->getSetterName(), $this->getVariableName());
86
+	}
87
+
88
+	/**
89
+	 * Returns true if the property is compulsory (and therefore should be fetched in the constructor).
90
+	 *
91
+	 * @return bool
92
+	 */
93
+	abstract public function isCompulsory();
94
+
95
+	/**
96
+	 * Returns true if the property has a default value.
97
+	 *
98
+	 * @return bool
99
+	 */
100
+	abstract public function hasDefault();
101
+
102
+	/**
103
+	 * Returns the code that assigns a value to its default value.
104
+	 *
105
+	 * @return string
106
+	 *
107
+	 * @throws \TDBMException
108
+	 */
109
+	abstract public function assignToDefaultCode();
110
+
111
+	/**
112
+	 * Returns true if the property is the primary key.
113
+	 *
114
+	 * @return bool
115
+	 */
116
+	abstract public function isPrimaryKey();
117
+
118
+	/**
119
+	 * @return Table
120
+	 */
121
+	public function getTable()
122
+	{
123
+		return $this->table;
124
+	}
125
+
126
+	/**
127
+	 * Returns the PHP code for getters and setters.
128
+	 *
129
+	 * @return string
130
+	 */
131
+	abstract public function getGetterSetterCode();
132
+
133
+	/**
134
+	 * Returns the part of code useful when doing json serialization.
135
+	 *
136
+	 * @return string
137
+	 */
138
+	abstract public function getJsonSerializeCode();
139 139
 }
Please login to merge, or discard this patch.