Browse Source

Added methods to fetchAssoc(), fetchColumn($position), fetchObject(), fetchAllObjects()

Eugene Ritter 8 years ago
parent
commit
051c6e35e9

+ 16 - 1
src/Database/Statement/BufferedStatement.php

@@ -92,7 +92,6 @@ class BufferedStatement extends StatementDecorator
         }
 
         $record = parent::fetch($type);
-
         if ($record === false) {
             $this->_allFetched = true;
             $this->_counter = $this->_count + 1;
@@ -107,6 +106,22 @@ class BufferedStatement extends StatementDecorator
     }
 
     /**
+     * {@inheritdoc}
+     */
+    public function fetchAssoc()
+    {
+        return $this->fetch(parent::FETCH_TYPE_ASSOC);
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function fetchobject()
+    {
+        return $this->fetch(parent::FETCH_TYPE_OBJ);
+    }
+
+    /**
      * {@inheritDoc}
      *
      * @param string $type The type to fetch.

+ 6 - 6
src/Database/Statement/PDOStatement.php

@@ -90,13 +90,13 @@ class PDOStatement extends StatementDecorator
      */
     public function fetch($type = 'num')
     {
-        if ($type === 'num') {
+        if ($type === static::FETCH_TYPE_NUM) {
             return $this->_statement->fetch(PDO::FETCH_NUM);
         }
-        if ($type === 'assoc') {
+        if ($type === static::FETCH_TYPE_ASSOC) {
             return $this->_statement->fetch(PDO::FETCH_ASSOC);
         }
-        if ($type === 'obj') {
+        if ($type === static::FETCH_TYPE_OBJ) {
             return $this->_statement->fetch(PDO::FETCH_OBJ);
         }
 
@@ -119,13 +119,13 @@ class PDOStatement extends StatementDecorator
      */
     public function fetchAll($type = 'num')
     {
-        if ($type === 'num') {
+        if ($type === static::FETCH_TYPE_NUM) {
             return $this->_statement->fetchAll(PDO::FETCH_NUM);
         }
-        if ($type === 'assoc') {
+        if ($type === static::FETCH_TYPE_ASSOC) {
             return $this->_statement->fetchAll(PDO::FETCH_ASSOC);
         }
-        if ($type === 'obj') {
+        if ($type === static::FETCH_TYPE_OBJ) {
             return $this->_statement->fetchAll(PDO::FETCH_OBJ);
         }
 

+ 63 - 0
src/Database/Statement/StatementDecorator.php

@@ -36,6 +36,25 @@ class StatementDecorator implements StatementInterface, Countable, IteratorAggre
     use TypeConverterTrait;
 
     /**
+     * Used to designate that numeric indexes be returned in a result when calling fetch methods
+     *
+     * @var string
+     */
+    const FETCH_TYPE_NUM = 'num';
+    /**
+     * Used to designate that associated array be returned in a result when calling fetch methods
+     *
+     * @var string
+     */
+    const FETCH_TYPE_ASSOC = 'assoc';
+    /**
+     * Used to designate that objects of \StdClass be returned in a result when calling fetch methods
+     *
+     * @var string
+     */
+    const FETCH_TYPE_OBJ = 'obj';
+
+    /**
      * Statement instance implementation, such as PDOStatement
      * or any other custom implementation.
      *
@@ -197,6 +216,40 @@ class StatementDecorator implements StatementInterface, Countable, IteratorAggre
     }
 
     /**
+     * Returns the next row as a StdClass object
+     *
+     * @return array|false Result array containing columns and values in an anonymous object or false if no results
+     */
+    public function fetchObject()
+    {
+        return $this->fetch(static::FETCH_TYPE_OBJ);
+    }
+
+    /**
+     * @return array|false Result array containing columns and values an an associative array or false if no results
+     */
+    public function fetchAssoc()
+    {
+        return $this->fetch(static::FETCH_TYPE_ASSOC);
+    }
+
+    /**
+     * Returns the value of the result at position.
+     *
+     * @param int $position The numeric position of the column to retrieve in the result
+     * @return mixed|false Returns the specific value of the column designated at $position
+     */
+    public function fetchColumn($position)
+    {
+        $result = $this->_statement->fetch(static::FETCH_TYPE_NUM);
+        if (isset($result[$position])) {
+            return $result[$position];
+        };
+
+        return false;
+    }
+
+    /**
      * Returns an array with all rows resulting from executing this statement.
      *
      * ### Example:
@@ -216,6 +269,16 @@ class StatementDecorator implements StatementInterface, Countable, IteratorAggre
     }
 
     /**
+     * Returns an array of \StdClass objects or false
+     *
+     * @return \StdClass[]|false
+     */
+    public function fetchAllObjects()
+    {
+        return $this->fetchAll(static::FETCH_TYPE_OBJ);
+    }
+
+    /**
      * Returns the number of rows affected by this SQL statement.
      *
      * ### Example:

+ 118 - 0
tests/TestCase/Database/QueryTest.php

@@ -4697,4 +4697,122 @@ class QueryTest extends TestCase
         $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
         $this->assertRegExp('#' . $pattern . '#', $query);
     }
+
+    /**
+     * Test that calling fetchAssoc return an associated array.
+     * @return void
+     */
+    public function testFetchAssoc()
+    {
+        $this->loadFixtures('Profiles');
+        $query = new Query($this->connection);
+        $results = $query
+            ->select([
+                'id',
+                'user_id',
+                'is_active'
+            ])
+            ->from('profiles')
+            ->limit(1)
+            ->execute()
+            ->fetchAssoc();
+        $this->assertSame(['id' => '1', 'user_id' => '1', 'is_active' => '0'], $results);
+    }
+
+    /**
+     * Test that calling fetchObject returns a \StdClass object
+     * @return void
+     */
+    public function testFetchObject()
+    {
+        $this->loadFixtures('Profiles');
+        $query = new Query($this->connection);
+        $results = $query
+            ->select([
+                'id',
+                'user_id',
+                'is_active'
+            ])
+            ->from('profiles')
+            ->limit(1)
+            ->execute()
+            ->fetchObject();
+        $this->assertInstanceOf(\StdClass::class, $results);
+        $this->assertObjectHasAttribute('id', $results);
+        $this->assertObjectHasAttribute('user_id', $results);
+        $this->assertObjectHasAttribute('is_active', $results);
+        $this->assertEquals($results->id, '1');
+        $this->assertEquals($results->user_id, '1');
+        $this->assertEquals($results->is_active, '0');
+    }
+
+    /**
+     * Test that calling fetchColumn returns the correct column value.
+     * @return void
+     */
+    public function testFetchColumn()
+    {
+        $this->loadFixtures('Profiles');
+        $query = new Query($this->connection);
+        $query
+            ->select([
+                'id',
+                'user_id',
+                'is_active'
+            ])
+            ->from('profiles')
+            ->where(['id' => 2])
+            ->limit(1);
+        $statement = $query->execute();
+        $results = $statement->fetchColumn(0);
+        $this->assertEquals('2', $results[0]);
+    }
+
+    /**
+     * Test that calling fetchAssoc, fetchColum and fetchObject in sequence
+     * alters the fetched data to the correct types and values.
+     * @return void
+     */
+    public function testFetchAllAssocColumnAndObj()
+    {
+        $this->loadFixtures('Profiles');
+        $query = new Query($this->connection);
+        $query
+            ->select([
+                'id',
+                'user_id',
+                'is_active'
+            ])
+            ->from('profiles');
+        $statement = $query->execute();
+        $results = $statement->fetchAssoc();
+        $this->assertEquals('1', $results['id']);
+        $results = $statement->fetchAssoc();
+        $this->assertEquals('2', $results['id']);
+        $results = $statement->fetchColumn(0);
+        $this->assertEquals('3', $results[0]);
+        $results = $statement->fetchObject();
+        $this->assertEquals('4', $results->id);
+    }
+
+    /**
+     * Test that an array of objects is returned
+     * @return void
+     */
+    public function testFetchAllObjects()
+    {
+        $this->loadFixtures('Profiles');
+        $query = new Query($this->connection);
+        $query
+            ->select([
+                'id',
+                'user_id',
+                'is_active'
+            ])
+            ->from('profiles');
+        $statement = $query->execute();
+        $results = $statement->fetchAllObjects();
+        $this->assertInstanceOf(\StdClass::class, $results[0]);
+        $this->assertEquals('2', $results[1]->id);
+    }
 }