Browse Source

added PDO-fetch-type FETCH_OBJ to PDOStatement

David Albrecht 10 years ago
parent
commit
4dd93b2956
2 changed files with 33 additions and 0 deletions
  1. 6 0
      src/Database/Statement/PDOStatement.php
  2. 27 0
      tests/TestCase/Database/QueryTest.php

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

@@ -97,6 +97,9 @@ class PDOStatement extends StatementDecorator
         if ($type === 'assoc') {
             return $this->_statement->fetch(PDO::FETCH_ASSOC);
         }
+        if ($type === 'obj') {
+            return $this->_statement->fetch(PDO::FETCH_OBJ);
+        }
         return $this->_statement->fetch($type);
     }
 
@@ -122,6 +125,9 @@ class PDOStatement extends StatementDecorator
         if ($type === 'assoc') {
             return $this->_statement->fetchAll(PDO::FETCH_ASSOC);
         }
+        if ($type === 'obj') {
+            return $this->_statement->fetchAll(PDO::FETCH_OBJ);
+        }
         return $this->_statement->fetchAll($type);
     }
 }

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

@@ -3675,4 +3675,31 @@ class QueryTest extends TestCase
         $pattern = str_replace('>', '[`"\]]' . $optional, $pattern);
         $this->assertRegExp('#' . $pattern . '#', $query);
     }
+
+    /**
+     * Tests that fetch returns an anonymous object when the string 'obj'
+     * is passed as an argument
+     *
+     * @return void
+     */
+    public function testSelectWithObjFetchType()
+    {
+        $query = new Query($this->connection);
+        $result = $query
+            ->select(['id'])
+            ->from('comments')
+            ->where(['id' => '1'])
+            ->execute();
+        $obj = (object)['id' => 1];
+        $this->assertEquals($obj, $result->fetch('obj'));
+
+        $query = new Query($this->connection);
+        $result = $query
+            ->select(['id'])
+            ->from('comments')
+            ->where(['id' => '1'])
+            ->execute();
+        $rows = $result->fetchAll('obj');
+        $this->assertEquals($obj, $rows[0]);
+    }
 }