diff options
author | Matthieu Napoli <matthieu@mnapoli.fr> | 2014-11-11 01:31:45 +0300 |
---|---|---|
committer | Matthieu Napoli <matthieu@mnapoli.fr> | 2014-11-11 06:28:11 +0300 |
commit | 94303fb5c5d211d441656dcc9ba1b9893c288ce4 (patch) | |
tree | a74a0cf3c0a0abb2cc7154a7e46aec55da90fa32 /core/Sequence.php | |
parent | 055f97093900db9ed4516d9d8b2c11e4b64f4212 (diff) |
Added dependency injection in Core\Sequence so that the SiteMigration plugin can provide an alternative database
Diffstat (limited to 'core/Sequence.php')
-rw-r--r-- | core/Sequence.php | 26 |
1 files changed, 13 insertions, 13 deletions
diff --git a/core/Sequence.php b/core/Sequence.php index 655332dced..d755ad6d06 100644 --- a/core/Sequence.php +++ b/core/Sequence.php @@ -9,6 +9,7 @@ namespace Piwik; use Exception; +use Piwik\Db\AdapterInterface; /** * Used for generating auto increment ids. @@ -24,13 +25,20 @@ class Sequence private $name; /** + * @var AdapterInterface + */ + private $db; + + /** * The name of the table or sequence you want to get an id for. * * @param string $name eg 'archive_numeric_2014_11' + * @param AdapterInterface $db You can optionally pass a DB adapter to make it work against another database. */ - public function __construct($name) + public function __construct($name, $db = null) { $this->name = $name; + $this->db = $db ?: Db::get(); } private function getTableName() @@ -51,9 +59,8 @@ class Sequence $initialValue = (int) $initialValue; $table = $this->getTableName(); - $db = $this->getDb(); - $db->insert($table, array('name' => $this->name, 'value' => $initialValue)); + $this->db->insert($table, array('name' => $this->name, 'value' => $initialValue)); return $initialValue; } @@ -70,15 +77,14 @@ class Sequence $table = $this->getTableName(); $sql = 'UPDATE ' . $table . ' SET value = LAST_INSERT_ID(value + 1) WHERE name = ?'; - $db = $this->getDb(); - $result = $db->query($sql, array($this->name)); + $result = $this->db->query($sql, array($this->name)); $rowCount = $result->rowCount(); if (1 !== $rowCount) { throw new Exception("Sequence '" . $this->name . "' not found."); } - $createdId = $db->lastInsertId(); + $createdId = $this->db->lastInsertId(); return (int) $createdId; } @@ -93,16 +99,10 @@ class Sequence $table = $this->getTableName(); $sql = 'SELECT value FROM ' . $table . ' WHERE name = ?'; - $db = $this->getDb(); - $id = $db->fetchOne($sql, array($this->name)); + $id = $this->db->fetchOne($sql, array($this->name)); if (!empty($id) || '0' === $id || 0 === $id) { return (int) $id; } } - - private function getDb() - { - return Db::get(); - } } |