Skip to content

Commit

Permalink
#7 writing tests, #25 in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
v-dem committed Jul 27, 2019
1 parent 9683966 commit 7019dea
Show file tree
Hide file tree
Showing 17 changed files with 141 additions and 104 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
composer.lock
vendor
coverage.xml
12 changes: 12 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
language: php
php:
- 7.2
- 7.3

before_script:
- composer install

script: phpunit

after_success:
- bash <(curl -s https://codecov.io/bash)
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[![Build Status](https://travis-ci.com/v-dem/queasy-db.svg?branch=master)](https://travis-ci.com/v-dem/queasy-db) [![codecov](https://codecov.io/gh/v-dem/queasy-db/branch/master/graph/badge.svg)](https://codecov.io/gh/v-dem/queasy-db)

# [Queasy PHP Framework](https://github.com/v-dem/queasy-app/) - Database

## Package `v-dem/queasy-db`
Expand Down
26 changes: 26 additions & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
codecov:
notify:
require_ci_to_pass: yes

coverage:
precision: 2
round: down
range: "70...100"

status:
project: yes
patch: yes
changes: no

parsers:
gcov:
branch_detection:
conditional: yes
loop: yes
method: no
macro: no

comment:
layout: "header, diff"
behavior: default
require_changes: no
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@
}
},
"scripts": {
"test": "phpunit --coverage-clover clover.xml"
"test": "phpunit --coverage-clover coverage.xml"
}
}
27 changes: 27 additions & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutOutputDuringTests="true">
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/src/</directory>
</testsuite>
</testsuites>
<logging>
<log type="coverage-text" target="php://stdout" showUncoveredFiles="true" />
<log type="coverage-clover" target="coverage.xml" showUncoveredFiles="false" />
</logging>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
</phpunit>
2 changes: 1 addition & 1 deletion src/ConnectionString.php → src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use ArrayAccess;

class ConnectionString
class Connection
{
const DEFAULT = 'sqlite::memory:';
const DEFAULT_DRIVER = 'sqlite';
Expand Down
36 changes: 6 additions & 30 deletions src/Db.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,30 +20,6 @@ class Db extends PDO
const RETURN_ONE = 1;
const RETURN_ALL = 2;

/**
* Creates a key/value map by an array key or object field.
*
* @param string $field Field or key name
* @param array $rows Array of arrays or objects
*
* @return array Array containing $field as a key and responsive row as a value
*/
public static function map($field, array $rows)
{
$result = array();
foreach ($rows as $row) {
if (is_object($row)) {
$result[$row[$field]] = $row;
} elseif (is_array($row)) {
$result[$row->$field] = $row;
} else {
throw InvalidArgumentException::rowsUnexpectedValue();
}
}

return $result;
}

private $tables = array();

private $queries = array();
Expand All @@ -60,20 +36,20 @@ public static function map($field, array $rows)
*/
protected $logger;

public function __construct($config)
public function __construct($config = array())
{
$this->setConfig($config);

$config = $this->config();

try {
$connection = isset($config['connection'])? $config['connection']: null;
$connectionString = new ConnectionString($connection);
$connectionConfig = isset($config['connection'])? $config['connection']: null;
$connectionString = new Connection($connectionConfig);
parent::__construct(
$connectionString(),
isset($connection['user'])? $connection['user']: null,
isset($connection['password'])? $connection['password']: null,
isset($connection['options'])? $connection['options']: null
isset($connectionConfig['user'])? $connectionConfig['user']: null,
isset($connectionConfig['password'])? $connectionConfig['password']: null,
isset($connectionConfig['options'])? $connectionConfig['options']: null
);
} catch (Exception $e) {
throw DbException::connectionFailed($e);
Expand Down
50 changes: 28 additions & 22 deletions src/query/AbstractQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ abstract class AbstractQuery implements QueryInterface
private $statement;

/**
* The logger instance.
* Logger instance.
*
* @var LoggerInterface
*/
Expand All @@ -27,6 +27,7 @@ abstract class AbstractQuery implements QueryInterface
/**
* Constructor.
*
* @param PDO $db PDO instance
* @param string $query Query string
*
* @throws DbException When query can't be prepared
Expand All @@ -39,40 +40,26 @@ public function __construct(PDO $db, $query = null)

abstract public function run(array $params = array());

public function __invoke(array $params = array())
{
return $this->run(func_get_args());
}

public function statement()
{
if (!$this->statement) {
try {
$this->statement = $this->db()->prepare($this->query());
} catch (Exception $e) {
throw DbException::cannotPrepareStatement($query, $e);
throw DbException::cannotPrepareStatement($this->query(), $e);
}
}

return $this->statement;
}

protected function db()
{
return $this->db;
}

protected function query()
{
if (empty($this->query)) {
throw new DbException('Query is empty.');
}

return $this->query;
}

protected function setQuery($query)
{
$this->query = $query;
}

/**
* Sets a logger.
* Set a logger.
*
* @param LoggerInterface $logger
*/
Expand All @@ -90,5 +77,24 @@ protected function logger()

return $this->logger;
}

protected function db()
{
return $this->db;
}

protected function query()
{
if (empty($this->query)) {
throw new DbException('Query is empty.');
}

return $this->query;
}

protected function setQuery($query)
{
$this->query = $query;
}
}

6 changes: 3 additions & 3 deletions src/query/BatchInsertQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
class BatchInsertQuery extends TableQuery
{
/**
* Build SQL query.
* Execute multiple rows INSERT query.
*
* @param array $params Query parameters
* @param array $params Query parameters (array of arrays)
*
* @return int Number of affected records (1 if row was inserted)
* @return int Number of inserted records
*
* @throws DbException On error
*/
Expand Down
6 changes: 3 additions & 3 deletions src/query/BatchNamedInsertQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
class BatchNamedInsertQuery extends TableQuery
{
/**
* Build SQL query.
* Execute multiple rows INSERT query using key-value arrays or objects.
*
* @param array $params Query parameters
* @param array $params Query parameters (array of key-value arrays or objects)
*
* @return int Number of affected records (1 if row was inserted)
* @return int Number of inserted records
*
* @throws DbException On error
*/
Expand Down
6 changes: 3 additions & 3 deletions src/query/BatchSeparatelyNamedInsertQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
class BatchSeparatelyNamedInsertQuery extends BatchNamedInsertQuery
{
/**
* Build SQL query.
* Execute INSERT query with column names array as the first $params item and rows as the second.
*
* @param array $params Query parameters
* @param array $params Query parameters (1st item is array with column names and 2nd is array of arrays)
*
* @return int Number of affected records (1 if row was inserted)
* @return int Number of inserted records
*
* @throws DbException On error
*/
Expand Down
26 changes: 4 additions & 22 deletions src/query/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,12 @@ class Query extends AbstractQuery
*
* @param array $params Query arguments
*
* @return int Number of affected rows for UPDATE/INSERT/DELETE queries or queasy\db\Statement instance for SELECT queries
* @return int|Statement Number of affected rows for UPDATE/INSERT/DELETE queries or queasy\db\Statement instance for SELECT queries
*
* @throws DbException On error
*/
public function run(array $params = array())
{
/*
$args = array();
if (func_num_args() > 0) {
if (is_array(func_get_arg(0))) { // Check if params passed as an array (key-value pairs), other args are ignored in this case
$args = func_get_arg(0);
} else { // Params passed as a list of args
$args = func_get_args();
}
}
$argKeys = array_keys($args);
while ((1 == count($args)) && (is_array($args[$argKeys[0]]))) {
$args = $args[0];
$argKeys = array_keys($args);
}
*/

$counter = 1;
foreach ($params as $paramKey => $paramValue) {
// Detect parameter type
Expand All @@ -64,9 +46,9 @@ public function run(array $params = array())
throw DbException::cannotExecuteQuery($this->query(), $sqlErrorCode, $errorMessage);
}

return ($this->statement()->columnCount())
? $this->statement()
: $this->statement()->rowCount();
return ($this->statement()->columnCount()) // Check if it was SELECT query
? $this->statement() // And return Statement if yes
: $this->statement()->rowCount(); // Or return number of affected rows if no
}

protected function getParamType($value)
Expand Down
2 changes: 2 additions & 0 deletions src/query/QueryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@
interface QueryInterface
{
public function run(array $params = array());

public function __invoke(array $params = array());
}

4 changes: 2 additions & 2 deletions src/query/SingleInsertQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
class SingleInsertQuery extends TableQuery
{
/**
* Build SQL query.
* Execute INSERT query.
*
* @param array $params Query parameters
*
* @return int Number of affected records (1 if row was inserted)
* @return int Insert id generated by database
*
* @throws DbException On error
*/
Expand Down
11 changes: 7 additions & 4 deletions src/query/SingleNamedInsertQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@
class SingleNamedInsertQuery extends TableQuery
{
/**
* Build SQL query.
* Execute INSERT query with named parameters.
*
* @param array $params Query parameters
* @param array $params Query parameters (key - value array)
*
* @return int Number of affected records (1 if row was inserted)
* @return int Insert id generated by database
*
* @throws DbException On error
*/
public function run(array $params = array())
{
// Workaround for empty $params (for example when a record is inserted just to get an id and other columns can be NULL)
if (empty($params)) {
$query = new SingleInsertQuery($this->db(), $this->tableName());

Expand All @@ -42,7 +43,9 @@ public function run(array $params = array())

$this->setQuery($query);

return parent::run($params);
parent::run($params);

return $this->db()->id();
}
}

Loading

0 comments on commit 7019dea

Please sign in to comment.