Skip to content

Commit

Permalink
Added data type validation passed to bind method
Browse files Browse the repository at this point in the history
  • Loading branch information
dbalabka committed Sep 6, 2017
1 parent e18cef2 commit cf55e23
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/Stmt.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ public function bind($paramId, $data) {
$i = reset($array);
}

if (!is_scalar($data) && !(is_object($data) && method_exists($data, '__toString'))) {
throw new \InvalidArgumentException("Data must be scalar or object that implements __toString method");
}

do {
$realId = -1;
while (isset($this->named[++$realId]) || $i-- > 0) {
Expand Down
69 changes: 69 additions & 0 deletions test/Mysql/StmtTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

use Amp\Mysql\Stmt;
use PHPUnit\Framework\TestCase;
use Amp\Mysql\ResultProxy;

class StmtTest extends TestCase
{
protected $processor;
protected $resultProxy;

public function setUp()
{
$this->processor = $this->prophesize('Amp\Mysql\Processor');
$this->resultProxy = new ResultProxy();
}

/**
* @dataProvider provideTestBindDataTypes
*/
public function testBindDataTypes($data, $expectedException)
{
// arrange
$query = 'SELECT * FROM test WHERE id = ?';
$stmtId = 1;
$paramId = 0;
$named = [];

$this->processor->alive()->willReturn(true);
$this->processor->delRef()->shouldBeCalled();
$this->processor->closeStmt(\Prophecy\Argument::any())->shouldBeCalled();
$this->resultProxy->columnsToFetch = 1;
$stmt = new Stmt($this->processor->reveal(), $query, $stmtId, $named, $this->resultProxy);

// assert
if ($expectedException) {
$this->expectException($expectedException);
$this->processor->bindParam($stmtId, \Prophecy\Argument::any(), $data)->shouldNotBeCalled();
} else {
$this->addToAssertionCount(1);
$this->processor->bindParam($stmtId, \Prophecy\Argument::any(), $data)->shouldBeCalled();
}

// act
$stmt->bind($paramId, $data);
}

public function provideTestBindDataTypes()
{
return [
'test scalar' => [
'data' => 1,
'expectedException' => false,
],
'test object' => [
'data' => (object) [],
'expectedException' => 'InvalidArgumentException',
],
'test array' => [
'data' => [],
'expectedException' => 'InvalidArgumentException',
],
'test object with __toString defined' => [
'data' => new class { public function __toString() {return '';} },
'expectedException' => false,
],
];
}
}

0 comments on commit cf55e23

Please sign in to comment.