Update vendor

This commit is contained in:
Frederic Guillot 2015-09-12 13:34:36 -04:00
parent bf7b3fbfa8
commit 94df3bd8d8
38 changed files with 200 additions and 3290 deletions

View File

@ -4,9 +4,9 @@
},
"require": {
"fguillot/simple-validator": "v1.0.0",
"fguillot/json-rpc": "v1.0.1",
"fguillot/picodb": "v1.0.1",
"fguillot/picofeed": "v0.1.9"
"fguillot/json-rpc": "v1.0.2",
"fguillot/picodb": "v1.0.2",
"fguillot/picofeed": "v0.1.10"
},
"require-dev": {
"phpunit/phpunit": "4.8.3",

2
vendor/autoload.php vendored
View File

@ -4,4 +4,4 @@
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInitc059b513a8543dde562d574abce226dd::getLoader();
return ComposerAutoloaderInit26454215d679bdaf4be648601e93de89::getLoader();

View File

@ -12,6 +12,7 @@ return array(
'JsonRPC\\ConnectionFailureException' => $vendorDir . '/fguillot/json-rpc/src/JsonRPC/Client.php',
'JsonRPC\\InvalidJsonFormat' => $vendorDir . '/fguillot/json-rpc/src/JsonRPC/Server.php',
'JsonRPC\\InvalidJsonRpcFormat' => $vendorDir . '/fguillot/json-rpc/src/JsonRPC/Server.php',
'JsonRPC\\ResponseException' => $vendorDir . '/fguillot/json-rpc/src/JsonRPC/ResponseException.php',
'JsonRPC\\Server' => $vendorDir . '/fguillot/json-rpc/src/JsonRPC/Server.php',
'JsonRPC\\ServerErrorException' => $vendorDir . '/fguillot/json-rpc/src/JsonRPC/Client.php',
'PicoDb\\Condition' => $vendorDir . '/fguillot/picodb/lib/PicoDb/Condition.php',

View File

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitc059b513a8543dde562d574abce226dd
class ComposerAutoloaderInit26454215d679bdaf4be648601e93de89
{
private static $loader;
@ -19,9 +19,9 @@ class ComposerAutoloaderInitc059b513a8543dde562d574abce226dd
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitc059b513a8543dde562d574abce226dd', 'loadClassLoader'), true, true);
spl_autoload_register(array('ComposerAutoloaderInit26454215d679bdaf4be648601e93de89', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitc059b513a8543dde562d574abce226dd', 'loadClassLoader'));
spl_autoload_unregister(array('ComposerAutoloaderInit26454215d679bdaf4be648601e93de89', 'loadClassLoader'));
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
@ -42,14 +42,14 @@ class ComposerAutoloaderInitc059b513a8543dde562d574abce226dd
$includeFiles = require __DIR__ . '/autoload_files.php';
foreach ($includeFiles as $file) {
composerRequirec059b513a8543dde562d574abce226dd($file);
composerRequire26454215d679bdaf4be648601e93de89($file);
}
return $loader;
}
}
function composerRequirec059b513a8543dde562d574abce226dd($file)
function composerRequire26454215d679bdaf4be648601e93de89($file)
{
require $file;
}

View File

@ -1,81 +1,4 @@
[
{
"name": "fguillot/json-rpc",
"version": "v1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/fguillot/JsonRPC.git",
"reference": "9a117e964c4c6ad026da7ae1ca155f7686e3deaf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fguillot/JsonRPC/zipball/9a117e964c4c6ad026da7ae1ca155f7686e3deaf",
"reference": "9a117e964c4c6ad026da7ae1ca155f7686e3deaf",
"shasum": ""
},
"require": {
"php": ">=5.3.4"
},
"time": "2015-08-07 22:31:21",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"JsonRPC": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frédéric Guillot"
}
],
"description": "Simple Json-RPC client/server library that just works",
"homepage": "https://github.com/fguillot/JsonRPC"
},
{
"name": "fguillot/picodb",
"version": "v1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/fguillot/picoDb.git",
"reference": "8a311523d114180e04a1e08ced6766f26d7ebbae"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fguillot/picoDb/zipball/8a311523d114180e04a1e08ced6766f26d7ebbae",
"reference": "8a311523d114180e04a1e08ced6766f26d7ebbae",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2015-08-13 01:44:29",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"PicoDb": "lib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frédéric Guillot",
"homepage": "http://fredericguillot.com"
}
],
"description": "Minimalist database query builder",
"homepage": "https://github.com/fguillot/picoDb"
},
{
"name": "fguillot/simple-validator",
"version": "1.0.0",
@ -116,17 +39,17 @@
},
{
"name": "fguillot/picofeed",
"version": "v0.1.9",
"version_normalized": "0.1.9.0",
"version": "v0.1.10",
"version_normalized": "0.1.10.0",
"source": {
"type": "git",
"url": "https://github.com/fguillot/picoFeed.git",
"reference": "b1dc17e00215c6ffb6ff2fbc6d193d6403c8bb71"
"reference": "a2cc36244278afbfb9578037b1700ca3cd5a87d7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fguillot/picoFeed/zipball/b1dc17e00215c6ffb6ff2fbc6d193d6403c8bb71",
"reference": "b1dc17e00215c6ffb6ff2fbc6d193d6403c8bb71",
"url": "https://api.github.com/repos/fguillot/picoFeed/zipball/a2cc36244278afbfb9578037b1700ca3cd5a87d7",
"reference": "a2cc36244278afbfb9578037b1700ca3cd5a87d7",
"shasum": ""
},
"require": {
@ -140,7 +63,7 @@
"suggest": {
"ext-curl": "PicoFeed will use cURL if present"
},
"time": "2015-08-27 23:26:39",
"time": "2015-09-12 11:05:28",
"bin": [
"picofeed"
],
@ -162,5 +85,82 @@
],
"description": "Modern library to handle RSS/Atom feeds",
"homepage": "https://github.com/fguillot/picoFeed"
},
{
"name": "fguillot/json-rpc",
"version": "v1.0.2",
"version_normalized": "1.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/fguillot/JsonRPC.git",
"reference": "265cf039c2823f684349de78c0c03a597992bea9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fguillot/JsonRPC/zipball/265cf039c2823f684349de78c0c03a597992bea9",
"reference": "265cf039c2823f684349de78c0c03a597992bea9",
"shasum": ""
},
"require": {
"php": ">=5.3.4"
},
"time": "2015-09-12 16:27:13",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"JsonRPC": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frédéric Guillot"
}
],
"description": "Simple Json-RPC client/server library that just works",
"homepage": "https://github.com/fguillot/JsonRPC"
},
{
"name": "fguillot/picodb",
"version": "v1.0.2",
"version_normalized": "1.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/fguillot/picoDb.git",
"reference": "61f492c125d9195ce869447e2b2450adeb3b01d6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/fguillot/picoDb/zipball/61f492c125d9195ce869447e2b2450adeb3b01d6",
"reference": "61f492c125d9195ce869447e2b2450adeb3b01d6",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2015-08-27 23:33:16",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-0": {
"PicoDb": "lib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frédéric Guillot",
"homepage": "http://fredericguillot.com"
}
],
"description": "Minimalist database query builder",
"homepage": "https://github.com/fguillot/picoDb"
}
]

View File

@ -1,2 +0,0 @@
.DS_Store
vendor/

View File

@ -1,19 +0,0 @@
language: php
php:
- 7.0
- 5.6
- 5.5
- 5.4
- 5.3
matrix:
fast_finish: true
allow_failures:
- php: 7.0
before_script:
- composer dump-autoload
script:
- phpunit

View File

@ -1,364 +0,0 @@
JsonRPC PHP Client and Server
=============================
A simple Json-RPC client/server that just works.
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/fguillot/JsonRPC/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/fguillot/JsonRPC/?branch=master)
[![Build Status](https://travis-ci.org/fguillot/JsonRPC.svg?branch=master)](https://travis-ci.org/fguillot/JsonRPC)
Features
--------
- JSON-RPC 2.0 protocol only
- The server support batch requests and notifications
- Authentication and IP based client restrictions
- Minimalist: there is only 2 files
- Fully unit tested
- Requirements: PHP >= 5.3.4
- License: MIT
Author
------
Frédéric Guillot
Installation with Composer
--------------------------
```bash
composer require fguillot/json-rpc @stable
```
Examples
--------
### Server
Callback binding:
```php
<?php
use JsonRPC\Server;
$server = new Server;
// Procedures registration
$server->register('addition', function ($a, $b) {
return $a + $b;
});
$server->register('random', function ($start, $end) {
return mt_rand($start, $end);
});
// Return the response to the client
echo $server->execute();
?>
```
Class/Method binding:
```php
<?php
use JsonRPC\Server;
class Api
{
public function doSomething($arg1, $arg2 = 3)
{
return $arg1 + $arg2;
}
}
$server = new Server;
// Bind the method Api::doSomething() to the procedure myProcedure
$server->bind('myProcedure', 'Api', 'doSomething');
// Use a class instance instead of the class name
$server->bind('mySecondProcedure', new Api, 'doSomething');
// The procedure and the method are the same
$server->bind('doSomething', 'Api');
// Attach the class, client will be able to call directly Api::doSomething()
$server->attach(new Api);
echo $server->execute();
?>
```
Before callback:
Before each procedure execution, a custom method can be called.
This method receive the following arguments: `$username, $password, $class, $method`.
```php
<?php
use JsonRPC\Server;
use JsonRPC\AuthenticationFailure;
class Api
{
public function beforeProcedure($username, $password, $class, $method)
{
if ($login_condition_failed) {
throw new AuthenticationFailure('Wrong credentials!');
}
}
public function addition($a, $b)
{
return $a + $b;
}
}
$server = new Server;
$server->authentication(['myuser' => 'mypassword']);
// Register the before callback
$server->before('beforeProcedure');
$server->attach(new Api);
echo $server->execute();
?>
```
You can use this method to implements a custom authentication system or anything else.
If you would like to reject the authentication, you can throw the exception `JsonRPC\AuthenticationFailure`.
### Client
Example with positional parameters:
```php
<?php
use JsonRPC\Client;
$client = new Client('http://localhost/server.php');
$result = $client->execute('addition', [3, 5]);
var_dump($result);
```
Example with named arguments:
```php
<?php
use JsonRPC\Client;
$client = new Client('http://localhost/server.php');
$result = $client->execute('random', ['end' => 10, 'start' => 1]);
var_dump($result);
```
Arguments are called in the right order.
Examples with shortcut methods:
```php
<?php
use JsonRPC\Client;
$client = new Client('http://localhost/server.php');
$result = $client->random(50, 100);
var_dump($result);
```
The example above use positional arguments for the request and this one use named arguments:
```php
$result = $client->random(['end' => 10, 'start' => 1]);
```
### Client batch requests
Call several procedures in a single HTTP request:
```php
<?php
use JsonRPC\Client;
$client = new Client('http://localhost/server.php');
$results = $client->batch()
->foo(['arg1' => 'bar'])
->random(1, 100)
->add(4, 3)
->execute('add', [2, 5])
->send();
print_r($results);
```
All results are stored at the same position of the call.
### Client exceptions
- `BadFunctionCallException`: Procedure not found on the server
- `InvalidArgumentException`: Wrong procedure arguments
- `JsonRPC\AccessDeniedException`: Access denied
- `JsonRPC\ConnectionFailureException`: Connection failure
- `JsonRPC\ServerErrorException`: Internal server error
- `RuntimeException`: Protocol error
### Enable client debugging
You can enable the debug to see the JSON request and response:
```php
<?php
use JsonRPC\Client;
$client = new Client('http://localhost/server.php');
$client->debug = true;
```
The debug output is sent to the PHP's system logger.
You can configure the log destination in your `php.ini`.
Output example:
```json
==> Request:
{
"jsonrpc": "2.0",
"method": "removeCategory",
"id": 486782327,
"params": [
1
]
}
==> Response:
{
"jsonrpc": "2.0",
"id": 486782327,
"result": true
}
```
### IP based client restrictions
The server can allow only some IP adresses:
```php
<?php
use JsonRPC\Server;
$server = new Server;
// IP client restrictions
$server->allowHosts(['192.168.0.1', '127.0.0.1']);
// Procedures registration
[...]
// Return the response to the client
echo $server->execute();
```
If the client is blocked, you got a 403 Forbidden HTTP response.
### HTTP Basic Authentication
If you use HTTPS, you can allow client by using a username/password.
```php
<?php
use JsonRPC\Server;
$server = new Server;
// List of users to allow
$server->authentication(['user1' => 'password1', 'user2' => 'password2']);
// Procedures registration
[...]
// Return the response to the client
echo $server->execute();
```
On the client, set credentials like that:
```php
<?php
use JsonRPC\Client;
$client = new Client('http://localhost/server.php');
$client->authentication('user1', 'password1');
```
If the authentication failed, the client throw a RuntimeException.
Using an alternative authentication header:
```php
use JsonRPC\Server;
$server = new Server;
$server->setAuthenticationHeader('X-Authentication');
$server->authentication(['myusername' => 'mypassword']);
```
The example above will use the HTTP header `X-Authentication` instead of the standard `Authorization: Basic [BASE64_CREDENTIALS]`.
The username/password values need be encoded in base64: `base64_encode('username:password')`.
### Exceptions
If you want to send an error to the client you can throw an exception.
You should configure which exceptions should be relayed to the client first:
```php
<?php
use JsonRPC\Server;
class MyException extends RuntimeException {};
$server = new Server;
// Exceptions that should be relayed to the client, if they occur
$server->attachException('MyException');
// Procedures registration
[...]
// Return the response to the client
echo $server->execute();
```
Then you can throw that exception inside your procedure:
```
throw new MyException("An error occured", 123);
```
To relay all exceptions regardless of type, leave out the exception class name:
```
$server->attachException();
```

View File

@ -1,18 +0,0 @@
{
"name": "fguillot/json-rpc",
"description": "Simple Json-RPC client/server library that just works",
"homepage": "https://github.com/fguillot/JsonRPC",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Frédéric Guillot"
}
],
"require": {
"php": ">=5.3.4"
},
"autoload": {
"psr-0": {"JsonRPC": "src/"}
}
}

View File

@ -1,7 +0,0 @@
<phpunit bootstrap="./vendor/autoload.php" stopOnError="true" stopOnFailure="true" colors="true">
<testsuites>
<testsuite name="JsonRPC">
<directory>tests</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@ -262,7 +262,12 @@ class Client
case -32601:
throw new BadFunctionCallException('Procedure not found: '. $error['message']);
case -32602:
throw new InvalidArgumentException('Invalid arguments: '. $error['message']);
throw new ResponseException(
'Invalid arguments: '. $error['message'],
$error['code'],
null,
isset($error['data']) ? $error['data'] : null
);
default:
throw new RuntimeException('Invalid request/response: '. $error['message'], $error['code']);
}

View File

@ -0,0 +1,61 @@
<?php
namespace JsonRPC;
use Exception;
/**
* Class ResponseException
*
* @package JsonRPC
*/
class ResponseException extends Exception
{
/**
* A value that contains additional information about the error.
*
* @access protected
* @link http://www.jsonrpc.org/specification#error_object
* @var mixed
*/
protected $data;
/**
* Constructor
*
* @access public
* @param string $message [optional] The Exception message to throw.
* @param int $code [optional] The Exception code.
* @param Exception $previous [optional] The previous exception used for the exception chaining. Since 5.3.0
* @param mixed $data [optional] A value that contains additional information about the error.
*/
public function __construct($message = '', $code = 0, Exception $previous = null, $data = null)
{
parent::__construct($message, $code, $previous);
$this->setData($data);
}
/**
* Attach additional information
*
* @access public
* @param mixed $data [optional] A value that contains additional information about the error.
* @return \JsonRPC\ResponseException
*/
public function setData($data = null)
{
$this->data = $data;
return $this;
}
/**
* Get additional information
*
* @access public
* @return mixed|null
*/
public function getData()
{
return $this->data;
}
}

View File

@ -463,6 +463,16 @@ class Server
catch (AccessDeniedException $e) {
$this->sendForbiddenResponse();
}
catch (ResponseException $e) {
return $this->getResponse(array(
'error' => array(
'code' => $e->getCode(),
'message' => $e->getMessage(),
'data' => $e->getData(),
)),
$this->payload
);
}
catch (Exception $e) {
foreach ($this->exceptions as $class) {

View File

@ -1,157 +0,0 @@
<?php
use JsonRPC\Client;
class ClientTest extends PHPUnit_Framework_TestCase
{
public function testParseReponse()
{
$client = new Client('http://localhost/');
$this->assertEquals(
-19,
$client->parseResponse(json_decode('{"jsonrpc": "2.0", "result": -19, "id": 1}', true))
);
$this->assertEquals(
null,
$client->parseResponse(json_decode('{"jsonrpc": "2.0", "id": 1}', true))
);
}
/**
* @expectedException BadFunctionCallException
*/
public function testBadProcedure()
{
$client = new Client('http://localhost/');
$client->parseResponse(json_decode('{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}', true));
}
/**
* @expectedException InvalidArgumentException
*/
public function testInvalidArgs()
{
$client = new Client('http://localhost/');
$client->parseResponse(json_decode('{"jsonrpc": "2.0", "error": {"code": -32602, "message": "Invalid params"}, "id": "1"}', true));
}
/**
* @expectedException RuntimeException
*/
public function testInvalidRequest()
{
$client = new Client('http://localhost/');
$client->parseResponse(json_decode('{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}', true));
}
/**
* @expectedException RuntimeException
*/
public function testParseError()
{
$client = new Client('http://localhost/');
$client->parseResponse(json_decode('{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}', true));
}
/**
* @expectedException JsonRPC\ServerErrorException
*/
public function testServerError()
{
$client = new Client('http://localhost/');
$client->handleHttpErrors(array('HTTP/1.0 301 Moved Permantenly', 'Connection: close', 'HTTP/1.1 500 Internal Server Error'));
}
/**
* @expectedException JsonRPC\ConnectionFailureException
*/
public function testBadUrl()
{
$client = new Client('http://something_not_found/', 1);
$client->execute('plop');
}
/**
* @expectedException JsonRPC\ConnectionFailureException
*/
public function test404()
{
$client = new Client('http://localhost/');
$client->handleHttpErrors(array('HTTP/1.1 404 Not Found'));
}
/**
* @expectedException JsonRPC\AccessDeniedException
*/
public function testAccessForbiddenError()
{
$client = new Client('http://localhost/');
$client->handleHttpErrors(array('HTTP/1.0 301 Moved Permantenly', 'Connection: close', 'HTTP/1.1 403 Forbidden'));
}
/**
* @expectedException JsonRPC\AccessDeniedException
*/
public function testAccessNotAllowedError()
{
$client = new Client('http://localhost/');
$client->handleHttpErrors(array('HTTP/1.0 301 Moved Permantenly', 'Connection: close', 'HTTP/1.0 401 Unauthorized'));
}
public function testPrepareRequest()
{
$client = new Client('http://localhost/');
$payload = $client->prepareRequest('myProcedure');
$this->assertNotEmpty($payload);
$this->assertArrayHasKey('jsonrpc', $payload);
$this->assertEquals('2.0', $payload['jsonrpc']);
$this->assertArrayHasKey('method', $payload);
$this->assertEquals('myProcedure', $payload['method']);
$this->assertArrayHasKey('id', $payload);
$this->assertArrayNotHasKey('params', $payload);
$payload = $client->prepareRequest('myProcedure', array('p1' => 3));
$this->assertNotEmpty($payload);
$this->assertArrayHasKey('jsonrpc', $payload);
$this->assertEquals('2.0', $payload['jsonrpc']);
$this->assertArrayHasKey('method', $payload);
$this->assertEquals('myProcedure', $payload['method']);
$this->assertArrayHasKey('id', $payload);
$this->assertArrayHasKey('params', $payload);
$this->assertEquals(array('p1' => 3), $payload['params']);
}
public function testBatchRequest()
{
$client = new Client('http://localhost/');
$batch = $client->batch();
$this->assertInstanceOf('JsonRpc\Client', $batch);
$this->assertTrue($client->is_batch);
$batch->random(1, 30);
$batch->add(3, 5);
$batch->execute('foo', array('p1' => 42, 'p3' => 3));
$this->assertNotEmpty($client->batch);
$this->assertEquals(3, count($client->batch));
$this->assertEquals('random', $client->batch[0]['method']);
$this->assertEquals('add', $client->batch[1]['method']);
$this->assertEquals('foo', $client->batch[2]['method']);
$this->assertEquals(array(1, 30), $client->batch[0]['params']);
$this->assertEquals(array(3, 5), $client->batch[1]['params']);
$this->assertEquals(array('p1' => 42, 'p3' => 3), $client->batch[2]['params']);
$batch = $client->batch();
$this->assertInstanceOf('JsonRpc\Client', $batch);
$this->assertTrue($client->is_batch);
$this->assertEmpty($client->batch);
}
}

View File

@ -1,140 +0,0 @@
<?php
use JsonRPC\Server;
class A
{
public function getAll($p1, $p2, $p3 = 4)
{
return $p1 + $p2 + $p3;
}
}
class B
{
public function getAll($p1)
{
return $p1 + 2;
}
}
class ServerProcedureTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException BadFunctionCallException
*/
public function testProcedureNotFound()
{
$server = new Server;
$server->executeProcedure('a');
}
/**
* @expectedException BadFunctionCallException
*/
public function testCallbackNotFound()
{
$server = new Server;
$server->register('b', function() {});
$server->executeProcedure('a');
}
/**
* @expectedException BadFunctionCallException
*/
public function testClassNotFound()
{
$server = new Server;
$server->bind('getAllTasks', 'c', 'getAll');
$server->executeProcedure('getAllTasks');
}
/**
* @expectedException BadFunctionCallException
*/
public function testMethodNotFound()
{
$server = new Server;
$server->bind('getAllTasks', 'A', 'getNothing');
$server->executeProcedure('getAllTasks');
}
public function testIsPositionalArguments()
{
$server = new Server;
$this->assertFalse($server->isPositionalArguments(
array('a' => 'b', 'c' => 'd'),
array('a' => 'b', 'c' => 'd')
));
$server = new Server;
$this->assertTrue($server->isPositionalArguments(
array('a', 'b', 'c'),
array('a' => 'b', 'c' => 'd')
));
}
public function testBindNamedArguments()
{
$server = new Server;
$server->bind('getAllA', 'A', 'getAll');
$server->bind('getAllB', 'B', 'getAll');
$server->bind('getAllC', new B, 'getAll');
$this->assertEquals(6, $server->executeProcedure('getAllA', array('p2' => 4, 'p1' => -2)));
$this->assertEquals(10, $server->executeProcedure('getAllA', array('p2' => 4, 'p3' => 8, 'p1' => -2)));
$this->assertEquals(6, $server->executeProcedure('getAllB', array('p1' => 4)));
$this->assertEquals(5, $server->executeProcedure('getAllC', array('p1' => 3)));
}
public function testBindPositionalArguments()
{
$server = new Server;
$server->bind('getAllA', 'A', 'getAll');
$server->bind('getAllB', 'B', 'getAll');
$this->assertEquals(6, $server->executeProcedure('getAllA', array(4, -2)));
$this->assertEquals(2, $server->executeProcedure('getAllA', array(4, 0, -2)));
$this->assertEquals(4, $server->executeProcedure('getAllB', array(2)));
}
public function testRegisterNamedArguments()
{
$server = new Server;
$server->register('getAllA', function($p1, $p2, $p3 = 4) {
return $p1 + $p2 + $p3;
});
$this->assertEquals(6, $server->executeProcedure('getAllA', array('p2' => 4, 'p1' => -2)));
$this->assertEquals(10, $server->executeProcedure('getAllA', array('p2' => 4, 'p3' => 8, 'p1' => -2)));
}
public function testRegisterPositionalArguments()
{
$server = new Server;
$server->register('getAllA', function($p1, $p2, $p3 = 4) {
return $p1 + $p2 + $p3;
});
$this->assertEquals(6, $server->executeProcedure('getAllA', array(4, -2)));
$this->assertEquals(2, $server->executeProcedure('getAllA', array(4, 0, -2)));
}
/**
* @expectedException InvalidArgumentException
*/
public function testTooManyArguments()
{
$server = new Server;
$server->bind('getAllC', new B, 'getAll');
$server->executeProcedure('getAllC', array('p1' => 3, 'p2' => 5));
}
/**
* @expectedException InvalidArgumentException
*/
public function testNotEnoughArguments()
{
$server = new Server;
$server->bind('getAllC', new B, 'getAll');
$server->executeProcedure('getAllC');
}
}

View File

@ -1,231 +0,0 @@
<?php
use JsonRPC\Server;
class C
{
public function doSomething()
{
return 'something';
}
}
class ServerProtocolTest extends PHPUnit_Framework_TestCase
{
public function testPositionalParameters()
{
$subtract = function($minuend, $subtrahend) {
return $minuend - $subtrahend;
};
$server = new Server('{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}');
$server->register('subtract', $subtract);
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "result": 19, "id": 1}', true),
json_decode($server->execute(), true)
);
$server = new Server('{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 1}');
$server->register('subtract', $subtract);
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "result": -19, "id": 1}', true),
json_decode($server->execute(), true)
);
}
public function testNamedParameters()
{
$subtract = function($minuend, $subtrahend) {
return $minuend - $subtrahend;
};
$server = new Server('{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}');
$server->register('subtract', $subtract);
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "result": 19, "id": 3}', true),
json_decode($server->execute(), true)
);
$server = new Server('{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}');
$server->register('subtract', $subtract);
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "result": 19, "id": 4}', true),
json_decode($server->execute(), true)
);
}
public function testNotification()
{
$update = function($p1, $p2, $p3, $p4, $p5) {};
$foobar = function() {};
$server = new Server('{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}');
$server->register('update', $update);
$server->register('foobar', $foobar);
$this->assertEquals('', $server->execute());
$server = new Server('{"jsonrpc": "2.0", "method": "foobar"}');
$server->register('update', $update);
$server->register('foobar', $foobar);
$this->assertEquals('', $server->execute());
}
public function testNoMethod()
{
$server = new Server('{"jsonrpc": "2.0", "method": "foobar", "id": "1"}');
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}', true),
json_decode($server->execute(), true)
);
}
public function testInvalidJson()
{
$server = new Server('{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]');
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}', true),
json_decode($server->execute(), true)
);
}
public function testInvalidRequest()
{
$server = new Server('{"jsonrpc": "2.0", "method": 1, "params": "bar"}');
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}', true),
json_decode($server->execute(), true)
);
}
public function testBatchInvalidJson()
{
$server = new Server('[
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
{"jsonrpc": "2.0", "method"
]');
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}', true),
json_decode($server->execute(), true)
);
}
public function testBatchEmptyArray()
{
$server = new Server('[]');
$this->assertEquals(
json_decode('{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}', true),
json_decode($server->execute(), true)
);
}
public function testBatchNotEmptyButInvalid()
{
$server = new Server('[1]');
$this->assertEquals(
json_decode('[{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}]', true),
json_decode($server->execute(), true)
);
}
public function testBatchInvalid()
{
$server = new Server('[1,2,3]');
$this->assertEquals(
json_decode('[
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}
]', true),
json_decode($server->execute(), true)
);
}
public function testBatchOk()
{
$server = new Server('[
{"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
{"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
{"foo": "boo"},
{"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
{"jsonrpc": "2.0", "method": "get_data", "id": "9"},
{"jsonrpc": "2.0", "method": "doSomething", "id": 10},
{"jsonrpc": "2.0", "method": "doStuff", "id": 15}
]');
$server->register('sum', function($a, $b, $c) {
return $a + $b + $c;
});
$server->register('subtract', function($minuend, $subtrahend) {
return $minuend - $subtrahend;
});
$server->register('get_data', function() {
return array('hello', 5);
});
$server->attach(new C);
$server->bind('doStuff', 'C', 'doSomething');
$response = $server->execute();
$this->assertEquals(
json_decode('[
{"jsonrpc": "2.0", "result": 7, "id": "1"},
{"jsonrpc": "2.0", "result": 19, "id": "2"},
{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null},
{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "5"},
{"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"},
{"jsonrpc": "2.0", "result": "something", "id": "10"},
{"jsonrpc": "2.0", "result": "something", "id": "15"}
]', true),
json_decode($response, true)
);
}
public function testBatchNotifications()
{
$server = new Server('[
{"jsonrpc": "2.0", "method": "notify_sum", "params": [1,2,4]},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}
]');
$server->register('notify_sum', function($a, $b, $c) {
});
$server->register('notify_hello', function($id) {
});
$this->assertEquals('', $server->execute());
}
}

View File

@ -1,43 +0,0 @@
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
ehthumbs.db
Icon?
Thumbs.db
*.swp
*~
*.lock
# App specific #
################
example.php
vendor

View File

@ -1,19 +0,0 @@
language: php
php:
- 7.0
- 5.6
- 5.5
- 5.4
- 5.3
matrix:
fast_finish: true
allow_failures:
- php: 7.0
before_script:
- composer dump-autoload
script:
- phpunit

View File

@ -1,562 +0,0 @@
PicoDb
======
PicoDb is a minimalist database query builder for PHP.
[![Build Status](https://travis-ci.org/fguillot/picoDb.svg?branch=master)](https://travis-ci.org/fguillot/picoDb)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/fguillot/picoDb/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/fguillot/picoDb/?branch=master)
Features
--------
- Easy to use, easy to hack, fast and very lightweight
- Supported drivers: Sqlite, Mysql, Postgresql
- Requires only PDO
- Use prepared statements
- Handle schema migrations
- Fully unit tested on PHP 5.3, 5.4, 5.5, 5.6 and 7.0
- License: MIT
Requirements
------------
- PHP >= 5.3
- PDO extension
- Sqlite or Mysql or Postgresql
Author
------
Frédéric Guillot
Documentation
-------------
### Installation
```bash
composer require fguillot/picodb @stable
```
### Database connection
Sqlite:
```php
use PicoDb\Database;
// Sqlite driver
$db = new Database(['driver' => 'sqlite', 'filename' => ':memory:']);
```
The Sqlite driver enable foreign keys by default.
Mysql:
```php
// Optional attributes:
// "charset"
// "schema_table" (the default table name is "schema_version")
// "port"
$db = new Database([
'driver' => 'mysql',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'my_db_name',
]);
```
Postgres:
```php
// Optional attributes:
// "schema_table" (the default table name is "schema_version")
// "port"
$db = new Database([
'driver' => 'postgres',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'my_db_name',
]);
```
### Execute any SQL query
```php
$db->execute('CREATE TABLE mytable (column1 TEXT)');
```
- Returns a `PDOStatement` if successful
- Returns `false` if there is a duplicate key error
- Throws a `SQLException` for other errors
### Insertion
```php
$db->table('mytable')->save(['column1' => 'test']);
```
or
```php
$db->table('mytable')->insert(['column1' => 'test']);
```
### Fetch last inserted id
```php
$db->getLastId();
```
### Transactions
```php
$db->transaction(function ($db) {
$db->table('mytable')->save(['column1' => 'foo']);
$db->table('mytable')->save(['column1' => 'bar']);
});
```
- Returns `true` if the callback returns null
- Returns the callback return value otherwise
- Throws an SQLException if something is wrong
or
```php
$db->startTransaction();
// Do something...
$db->closeTransaction();
// Rollback
$db->cancelTransaction();
```
### Fetch all data
```php
$records = $db->table('mytable')->findAll();
foreach ($records as $record) {
var_dump($record['column1']);
}
```
### Updates
```php
$db->table('mytable')->eq('id', 1)->save(['column1' => 'hey']);
```
or
```php
$db->table('mytable')->eq('id', 1)->update(['column1' => 'hey']);
```
### Remove records
```php
$db->table('mytable')->lt('column1', 10)->remove();
```
### Sorting
```php
$db->table('mytable')->asc('column1')->findAll();
```
or
```php
$db->table('mytable')->desc('column1')->findAll();
```
or
```php
$db->table('mytable')->orderBy('column1', 'ASC')->findAll();
```
Multiple sorting:
```php
$db->table('mytable')->asc('column1')->desc('column2')->findAll();
```
### Limit and offset
```php
$db->table('mytable')->limit(10)->offset(5)->findAll();
```
### Fetch only some columns
```php
$db->table('mytable')->columns('column1', 'column2')->findAll();
```
### Fetch only one column
Many rows:
```php
$db->table('mytable')->findAllByColumn('column1');
```
One row:
```php
$db->table('mytable')->findOneColumn('column1');
```
### Custom select
```php
$db->table('mytable')->select(1)->eq('id', 42)->findOne();
```
### Distinct
```php
$db->table('mytable')->distinct('columnA')->findOne();
```
### Group by
```php
$db->table('mytable')->groupBy('columnA')->findAll();
```
### Count
```php
$db->table('mytable')->count();
```
### Sum
```php
$db->table('mytable')->sum('columnB');
```
### Sum column values during update
Add the value 42 to the existing value of the column "mycolumn":
```php
$db->table('mytable')->sumColumn('mycolumn', 42)->update();
```
### Exists
Returns true if a record exists otherwise false.
```php
$db->table('mytable')->eq('column1', 12)->exists();
```
### Left joins
```php
// SELECT * FROM mytable LEFT JOIN my_other_table AS t1 ON t1.id=mytable.foreign_key
$db->table('mytable')->left('my_other_table', 't1', 'id', 'mytable', 'foreign_key')->findAll();
```
or
```php
// SELECT * FROM mytable LEFT JOIN my_other_table ON my_other_table.id=mytable.foreign_key
$db->table('mytable')->join('my_other_table', 'id', 'foreign_key')->findAll();
```
### Equals condition
```php
$db->table('mytable')
->eq('column1', 'hey')
->findAll();
```
### IN condition
```php
$db->table('mytable')
->in('column1', ['hey', 'bla'])
->findAll();
```
### Like condition
Case-sensitive (only Mysql and Postgres):
```php
$db->table('mytable')
->like('column1', '%Foo%')
->findAll();
```
Not case-sensitive:
```php
$db->table('mytable')
->ilike('column1', '%foo%')
->findAll();
```
### Lower than condition
```php
$db->table('mytable')
->lt('column1', 2)
->findAll();
```
### Lower than or equal condition
```php
$db->table('mytable')
->lte('column1', 2)
->findAll();
```
### Greater than condition
```php
$db->table('mytable')
->gt('column1', 3)
->findAll();
```
### Greater than or equal condition
```php
$db->table('mytable')
->gte('column1', 3)
->findAll();
```
### IS NULL condition
```php
$db->table('mytable')
->isNull('column1')
->findAll();
```
### IS NOT NULL condition
```php
$db->table('mytable')
->notNull('column1')
->findAll();
```
### Multiple conditions
Add conditions are joined by a `AND`.
```php
$db->table('mytable')
->like('column2', '%mytable')
->gte('column1', 3)
->findAll();
```
How to make a OR condition:
```php
$db->table('mytable')
->beginOr()
->like('column2', '%mytable')
->gte('column1', 3)
->closeOr()
->eq('column5', 'titi')
->findAll();
```
### Debugging
Log generated queries:
```php
$db->logQueries = true;
```
Mesure each query time:
```php
$db->stopwatch = true;
```
Get the number of queries executed:
```php
echo $db->nbQueries;
```
Get log messages:
```php
print_r($db->getLogMessages());
```
### Hashtable (key/value store)
How to use a table as a key/value store:
```php
$db->execute(
'CREATE TABLE mytable (
column1 TEXT NOT NULL UNIQUE,
column2 TEXT default NULL
)'
);
$db->table('mytable')->insert(['column1' => 'option1', 'column2' => 'value1']);
```
Add/Replace some values:
```php
$db->hashtable('mytable')
->columnKey('column1')
->columnValue('column2')
->put(['option1' => 'new value', 'option2' => 'value2']));
```
Get all values:
```php
$result = $db->hashtable('mytable')->columnKey('column1')->columnValue('column2')->get();
print_r($result);
Array
(
[option2] => value2
[option1] => new value
)
```
or
```php
$result = $db->hashtable('mytable')->getAll('column1', 'column2');
```
Get a specific value:
```php
$db->hashtable('mytable')
->columnKey('column1')
->columnValue('column2')
->put(['option3' => 'value3']);
$result = $db->hashtable('mytable')
->columnKey('column1')
->columnValue('column2')
->get('option1', 'option3');
print_r($result);
Array
(
[option1] => new value
[option3] => value3
)
```
### Schema migrations
#### Define a migration
- Migrations are defined in simple functions inside a namespace named "Schema".
- An instance of PDO is passed to first argument of the function.
- Function names has the version number at the end.
Example:
```php
namespace Schema;
function version_1($pdo)
{
$pdo->exec('
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE,
email TEXT UNIQUE,
password TEXT
)
');
}
function version_2($pdo)
{
$pdo->exec('
CREATE TABLE tags (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE
)
');
}
```
#### Run schema update automatically
- The method `check()` execute all migrations until the version specified
- If an error occurs, the transaction is rollbacked
- Foreign keys checks are disabled if possible during the migration
Example:
```php
$last_schema_version = 5;
$db = new PicoDb\Database(array(
'driver' => 'sqlite',
'filename' => '/tmp/mydb.sqlite'
));
if ($db->schema()->check($last_schema_version)) {
// Do something...
}
else {
die('Unable to migrate database schema.');
}
```
### Use a singleton to handle database instances
Setup a new instance:
```php
PicoDb\Database::setInstance('myinstance', function() {
$db = new PicoDb\Database(array(
'driver' => 'sqlite',
'filename' => DB_FILENAME
));
if ($db->schema()->check(DB_VERSION)) {
return $db;
}
else {
die('Unable to migrate database schema.');
}
});
```
Get this instance anywhere in your code:
```php
PicoDb\Database::getInstance('myinstance')->table(...)
```

View File

@ -1,19 +0,0 @@
{
"name": "fguillot/picodb",
"description": "Minimalist database query builder",
"homepage": "https://github.com/fguillot/picoDb",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Frédéric Guillot",
"homepage": "http://fredericguillot.com"
}
],
"require": {
"php": ">=5.3.0"
},
"autoload": {
"psr-0": {"PicoDb": "lib/"}
}
}

View File

@ -1,15 +0,0 @@
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.5/phpunit.xsd"
colors="true"
stopOnError="true"
stopOnFailure="true">
<testsuites>
<testsuite name="Sqlite Test Suite">
<file>tests/SqliteDriverTest.php</file>
<file>tests/SqliteDatabaseTest.php</file>
<file>tests/SqliteSchemaTest.php</file>
<file>tests/SqliteTableTest.php</file>
</testsuite>
</testsuites>
</phpunit>

View File

@ -1,100 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Database;
class MysqlDatabaseTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new Database(array('driver' => 'mysql', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'picodb'));
$this->db->getConnection()->exec('CREATE DATABASE IF NOT EXISTS `picodb`');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS foobar');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
$this->db->logQueries = true;
}
public function testEscapeIdentifer()
{
$this->assertEquals('`a`', $this->db->escapeIdentifier('a'));
$this->assertEquals('a.b', $this->db->escapeIdentifier('a.b'));
$this->assertEquals('`c`.`a`', $this->db->escapeIdentifier('a', 'c'));
$this->assertEquals('a.b', $this->db->escapeIdentifier('a.b', 'c'));
$this->assertEquals('SELECT COUNT(*) FROM test', $this->db->escapeIdentifier('SELECT COUNT(*) FROM test'));
$this->assertEquals('SELECT COUNT(*) FROM test', $this->db->escapeIdentifier('SELECT COUNT(*) FROM test', 'b'));
}
public function testEscapeIdentiferList()
{
$this->assertEquals(array('`c`.`a`', '`c`.`b`'), $this->db->escapeIdentifierList(array('a', 'b'), 'c'));
$this->assertEquals(array('`a`', 'd.b'), $this->db->escapeIdentifierList(array('a', 'd.b')));
}
public function testThatPreparedStatementWorks()
{
$this->db->getConnection()->exec('CREATE TABLE foobar (id INT AUTO_INCREMENT NOT NULL, something TEXT, PRIMARY KEY (id)) ENGINE=InnoDB');
$this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
$this->assertEquals(1, $this->db->getLastId());
$this->assertEquals('a', $this->db->execute('SELECT something FROM foobar WHERE something=?', array('a'))->fetchColumn());
}
/**
* @expectedException PicoDb\SQLException
*/
public function testBadSQLQuery()
{
$this->db->execute('INSERT INTO foobar');
}
public function testDuplicateKey()
{
$this->db->getConnection()->exec('CREATE TABLE foobar (something CHAR(1) UNIQUE) ENGINE=InnoDB');
$this->assertNotFalse($this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a')));
$this->assertFalse($this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a')));
$this->assertEquals(1, $this->db->execute('SELECT COUNT(*) FROM foobar WHERE something=?', array('a'))->fetchColumn());
}
public function testThatTransactionReturnsAValue()
{
$this->assertEquals('a', $this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something CHAR(1) UNIQUE) ENGINE=InnoDB');
$db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
return $db->execute('SELECT something FROM foobar WHERE something=?', array('a'))->fetchColumn();
}));
}
public function testThatTransactionReturnsTrue()
{
$this->assertTrue($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something CHAR(1) UNIQUE) ENGINE=InnoDB');
$db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
}));
}
/**
* @expectedException PicoDb\SQLException
*/
public function testThatTransactionThrowExceptionWhenRollbacked()
{
$this->assertFalse($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABL');
}));
}
public function testThatTransactionReturnsFalseWhithDuplicateKey()
{
$this->assertFalse($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something CHAR(1) UNIQUE) ENGINE=InnoDB');
$r1 = $db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
$r2 = $db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
return $r1 && $r2;
}));
}
}

View File

@ -1,65 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Driver\Mysql;
class MysqlDriverTest extends PHPUnit_Framework_TestCase
{
private $driver;
public function setUp()
{
$this->driver = new Mysql(array('hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'picodb'));
$this->driver->getConnection()->exec('CREATE DATABASE IF NOT EXISTS `picodb`');
$this->driver->getConnection()->exec('DROP TABLE IF EXISTS foobar');
$this->driver->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
}
/**
* @expectedException LogicException
*/
public function testMissingRequiredParameter()
{
new Mysql(array());
}
public function testDuplicateKeyError()
{
$this->assertFalse($this->driver->isDuplicateKeyError(1234));
$this->assertTrue($this->driver->isDuplicateKeyError(23000));
}
public function testOperator()
{
$this->assertEquals('LIKE BINARY', $this->driver->getOperator('LIKE'));
$this->assertEquals('LIKE', $this->driver->getOperator('ILIKE'));
$this->assertEquals('', $this->driver->getOperator('FOO'));
}
public function testSchemaVersion()
{
$this->assertEquals(0, $this->driver->getSchemaVersion());
$this->driver->setSchemaVersion(1);
$this->assertEquals(1, $this->driver->getSchemaVersion());
$this->driver->setSchemaVersion(42);
$this->assertEquals(42, $this->driver->getSchemaVersion());
}
public function testLastInsertId()
{
$this->assertEquals(0, $this->driver->getLastId());
$this->driver->getConnection()->exec('CREATE TABLE foobar (id INT AUTO_INCREMENT NOT NULL, something TEXT, PRIMARY KEY (id)) ENGINE=InnoDB');
$this->driver->getConnection()->exec('INSERT INTO foobar (something) VALUES (1)');
$this->assertEquals(1, $this->driver->getLastId());
}
public function testEscape()
{
$this->assertEquals('`foobar`', $this->driver->escape('foobar'));
}
}

View File

@ -1,34 +0,0 @@
<?php
require_once 'vendor/autoload.php';
require_once __DIR__.'/SchemaFixture.php';
class MysqlSchemaTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new PicoDb\Database(array('driver' => 'mysql', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'picodb'));
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test1');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test2');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
}
public function testMigrations()
{
$this->assertTrue($this->db->schema()->check(2));
$this->assertEquals(2, $this->db->getDriver()->getSchemaVersion());
}
public function testFailedMigrations()
{
$this->assertEquals(0, $this->db->getDriver()->getSchemaVersion());
$this->assertFalse($this->db->schema()->check(3));
$this->assertEquals(0, $this->db->getDriver()->getSchemaVersion());
$logs = $this->db->getLogMessages();
$this->assertNotEmpty($logs);
$this->assertStringStartsWith('\Schema\version_3 => SQLSTATE[42000]: Syntax error or access violation', $logs[0]);
}
}

View File

@ -1,313 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Database;
use PicoDb\Table;
class MysqlTableTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new Database(array('driver' => 'mysql', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'picodb'));
$this->db->getConnection()->exec('CREATE DATABASE IF NOT EXISTS `picodb`');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test1');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test2');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS foobar');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
$this->db->logQueries = true;
}
public function testSelect()
{
$this->assertEquals('SELECT 1 FROM `test`', $this->db->table('test')->select(1)->buildSelectQuery());
}
public function testColumns()
{
$this->assertEquals('SELECT `a`, `b` FROM `test`', $this->db->table('test')->columns('a', 'b')->buildSelectQuery());
}
public function testDistinct()
{
$this->assertEquals('SELECT DISTINCT `a`, `b` FROM `test`', $this->db->table('test')->distinct('a', 'b')->buildSelectQuery());
}
public function testGroupBy()
{
$this->assertEquals('SELECT * FROM `test` GROUP BY `a`', $this->db->table('test')->groupBy('a')->buildSelectQuery());
}
public function testOrderBy()
{
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` ASC', $this->db->table('test')->asc('a')->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` ASC', $this->db->table('test')->orderBy('a', Table::SORT_ASC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` DESC', $this->db->table('test')->desc('a', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` DESC', $this->db->table('test')->orderBy('a', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` ASC, `b` ASC', $this->db->table('test')->asc('a')->asc('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` DESC, `b` DESC', $this->db->table('test')->desc('a')->desc('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` ASC, `b` ASC', $this->db->table('test')->orderBy('a')->orderBy('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` DESC, `b` DESC', $this->db->table('test')->orderBy('a', Table::SORT_DESC)->orderBy('b', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` ORDER BY `a` DESC, `b` ASC', $this->db->table('test')->desc('a')->asc('b')->buildSelectQuery());
}
public function testLimit()
{
$this->assertEquals('SELECT * FROM `test` LIMIT 10', $this->db->table('test')->limit(10)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test`', $this->db->table('test')->limit(null)->buildSelectQuery());
}
public function testOffset()
{
$this->assertEquals('SELECT * FROM `test` OFFSET 0', $this->db->table('test')->offset(0)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` OFFSET 10', $this->db->table('test')->offset(10)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test`', $this->db->table('test')->limit(null)->buildSelectQuery());
}
public function testLimitOffset()
{
$this->assertEquals('SELECT * FROM `test` LIMIT 2 OFFSET 0', $this->db->table('test')->offset(0)->limit(2)->buildSelectQuery());
$this->assertEquals('SELECT * FROM `test` LIMIT 5 OFFSET 10', $this->db->table('test')->offset(10)->limit(5)->buildSelectQuery());
}
public function testSubquery()
{
$this->assertEquals('SELECT (SELECT 1 FROM "foobar" WHERE 1=1) AS `b` FROM `test`', $this->db->table('test')->subquery('SELECT 1 FROM "foobar" WHERE 1=1', 'b')->buildSelectQuery());
}
public function testConditionEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` = ? AND `b` = ?', $table->eq('a', 2)->eq('b', 'foobar')->buildSelectQuery());
$this->assertEquals(array(2, 'foobar'), $table->condition->getValues());
}
public function testConditionNotEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` != ?', $table->neq('a', 2)->buildSelectQuery());
$this->assertEquals(array(2), $table->condition->getValues());
}
public function testConditionIn()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` IN (?, ?)', $table->in('a', array('b', 'c'))->buildSelectQuery());
$this->assertEquals(array('b', 'c'), $table->condition->getValues());
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test`', $table->in('a', array())->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testConditionNotIn()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` NOT IN (?, ?)', $table->notin('a', array('b', 'c'))->buildSelectQuery());
$this->assertEquals(array('b', 'c'), $table->condition->getValues());
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test`', $table->notin('a', array())->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testConditionLike()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` LIKE BINARY ?', $table->like('a', '%foobar%')->buildSelectQuery());
$this->assertEquals(array('%foobar%'), $table->condition->getValues());
}
public function testConditionILike()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` LIKE ?', $table->ilike('a', '%foobar%')->buildSelectQuery());
$this->assertEquals(array('%foobar%'), $table->condition->getValues());
}
public function testConditionGreaterThan()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` > ?', $table->gt('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionGreaterThanOrEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` >= ?', $table->gte('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionLowerThan()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` < ?', $table->lt('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionLowerThanOrEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` <= ?', $table->lte('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionIsNull()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` IS NOT NULL', $table->notNull('a')->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testCustomCondition()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE a=c AND `b` = ?', $table->addCondition('a=c')->eq('b', 4)->buildSelectQuery());
$this->assertEquals(array(4), $table->condition->getValues());
}
public function testOrConditions()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM `test` WHERE `a` IS NOT NULL AND (`b` = ? OR `c` >= ?)', $table->notNull('a')->beginOr()->eq('b', 2)->gte('c', 5)->closeOr()->buildSelectQuery());
$this->assertEquals(array(2, 5), $table->condition->getValues());
}
public function testInsertUpdate()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a TEXT)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'b')));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'c')));
$this->assertEquals(array(array('a' => 'b'), array('a' => 'c')), $this->db->table('foobar')->findAll());
$this->assertEquals(array('b', 'c'), $this->db->table('foobar')->findAllByColumn('a'));
$this->assertEquals(array('a' => 'b'), $this->db->table('foobar')->findOne());
$this->assertEquals('b', $this->db->table('foobar')->findOneColumn('a'));
$this->assertTrue($this->db->table('foobar')->exists());
$this->assertTrue($this->db->table('foobar')->eq('a', 'c')->exists());
$this->assertFalse($this->db->table('foobar')->eq('a', 'e')->exists());
$this->assertEquals(2, $this->db->table('foobar')->count());
$this->assertEquals(1, $this->db->table('foobar')->eq('a', 'c')->count());
$this->assertEquals(0, $this->db->table('foobar')->eq('a', 'e')->count());
$this->assertTrue($this->db->table('foobar')->eq('a', 'c')->remove());
$this->assertFalse($this->db->table('foobar')->eq('a', 'e')->remove());
$this->assertTrue($this->db->table('foobar')->eq('a', 'b')->update(array('a' => 'test')));
$this->assertTrue($this->db->table('foobar')->eq('a', 'lol')->update(array('a' => 'test')));
$this->assertNotEmpty($this->db->table('foobar')->eq('a', 'test')->findOne());
$this->assertNull($this->db->table('foobar')->eq('a', 'lol')->findOne());
$this->assertTrue($this->db->table('foobar')->eq('a', 'test')->save(array('a' => 'plop')));
$this->assertEquals(1, $this->db->table('foobar')->count());
}
public function testSumColumn()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (b FLOAT, c FLOAT)'));
$this->assertTrue($this->db->table('foobar')->insert(array('b' => 2, 'c' => 3.3)));
$this->assertTrue($this->db->table('foobar')->sumColumn('b', 2.5)->sumColumn('c', 3)->update());
$this->assertEquals(
array('b' => 4.5, 'c' => 6.3),
$this->db->table('foobar')->findOne()
);
}
public function testSum()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a INTEGER)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 2)));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 5)));
$this->assertEquals(7, $this->db->table('foobar')->sum('a'));
}
public function testLeftJoin()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE test1 (a INTEGER NOT NULL, foreign_key INTEGER NOT NULL)'));
$this->assertNotFalse($this->db->execute('CREATE TABLE test2 (id INTEGER NOT NULL, b INTEGER NOT NULL)'));
$this->assertTrue($this->db->table('test2')->insert(array('id' => 42, 'b' => 2)));
$this->assertTrue($this->db->table('test1')->insert(array('a' => 18, 'foreign_key' => 42)));
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test2')->columns('a', 'b')->eq('a', 18)->left('test1', 't1', 'foreign_key', 'test2', 'id')->findOne()
);
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test2')->columns('a', 'b')->eq('a', 18)->join('test1', 'foreign_key', 'id')->findOne()
);
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test1')->columns('a', 'b')->join('test2', 'id', 'foreign_key')->findOne()
);
}
public function testHashTable()
{
$this->assertNotFalse($this->db->execute(
'CREATE TABLE foobar (
column1 VARCHAR(20) NOT NULL UNIQUE,
column2 VARCHAR(20) default NULL
)'
));
$this->assertTrue($this->db->table('foobar')->insert(array('column1' => 'option1', 'column2' => 'value1')));
$this->assertTrue($this->db->table('foobar')->insert(array('column1' => 'option2', 'column2' => 'value2')));
$this->assertTrue($this->db->table('foobar')->insert(array('column1' => 'option3', 'column2' => 'value3')));
$values = array(
'option1' => 'hey',
'option4' => 'ho',
);
$this->assertTrue($this->db->hashtable('foobar')->columnKey('column1')->columnValue('column2')->put($values));
$this->assertEquals(
array('option2' => 'value2', 'option4' => 'ho'),
$this->db->hashtable('foobar')->columnKey('column1')->columnValue('column2')->get('option2', 'option4')
);
$this->assertEquals(
array('option2' => 'value2', 'option3' => 'value3', 'option1' => 'hey', 'option4' => 'ho'),
$this->db->hashtable('foobar')->columnKey('column1')->columnValue('column2')->get()
);
$this->assertEquals(
array('option2' => 'value2', 'option3' => 'value3', 'option1' => 'hey', 'option4' => 'ho'),
$this->db->hashtable('foobar')->getAll('column1', 'column2')
);
}
}

View File

@ -1,99 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Database;
class PostgresDatabaseTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new Database(array('driver' => 'postgres', 'hostname' => 'localhost', 'username' => 'postgres', 'password' => 'postgres', 'database' => 'picodb'));
$this->db->getConnection()->exec('DROP TABLE IF EXISTS foobar');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
$this->db->logQueries = true;
}
public function testEscapeIdentifer()
{
$this->assertEquals('"a"', $this->db->escapeIdentifier('a'));
$this->assertEquals('a.b', $this->db->escapeIdentifier('a.b'));
$this->assertEquals('"c"."a"', $this->db->escapeIdentifier('a', 'c'));
$this->assertEquals('a.b', $this->db->escapeIdentifier('a.b', 'c'));
$this->assertEquals('SELECT COUNT(*) FROM test', $this->db->escapeIdentifier('SELECT COUNT(*) FROM test'));
$this->assertEquals('SELECT COUNT(*) FROM test', $this->db->escapeIdentifier('SELECT COUNT(*) FROM test', 'b'));
}
public function testEscapeIdentiferList()
{
$this->assertEquals(array('"c"."a"', '"c"."b"'), $this->db->escapeIdentifierList(array('a', 'b'), 'c'));
$this->assertEquals(array('"a"', 'd.b'), $this->db->escapeIdentifierList(array('a', 'd.b')));
}
public function testThatPreparedStatementWorks()
{
$this->db->getConnection()->exec('CREATE TABLE foobar (id serial PRIMARY KEY, something TEXT)');
$this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
$this->assertEquals(1, $this->db->getLastId());
$this->assertEquals('a', $this->db->execute('SELECT something FROM foobar WHERE something=?', array('a'))->fetchColumn());
}
/**
* @expectedException PicoDb\SQLException
*/
public function testBadSQLQuery()
{
$this->db->execute('INSERT INTO foobar');
}
public function testDuplicateKey()
{
$this->db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$this->assertNotFalse($this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a')));
$this->assertFalse($this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a')));
$this->assertEquals(1, $this->db->execute('SELECT COUNT(*) FROM foobar WHERE something=?', array('a'))->fetchColumn());
}
public function testThatTransactionReturnsAValue()
{
$this->assertEquals('a', $this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
return $db->execute('SELECT something FROM foobar WHERE something=?', array('a'))->fetchColumn();
}));
}
public function testThatTransactionReturnsTrue()
{
$this->assertTrue($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
}));
}
/**
* @expectedException PicoDb\SQLException
*/
public function testThatTransactionThrowExceptionWhenRollbacked()
{
$this->assertFalse($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABL');
}));
}
public function testThatTransactionReturnsFalseWhithDuplicateKey()
{
$this->assertFalse($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$r1 = $db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
$r2 = $db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
return $r1 && $r2;
}));
}
}

View File

@ -1,70 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Driver\Postgres;
class PostgresDriverTest extends PHPUnit_Framework_TestCase
{
private $driver;
public function setUp()
{
$this->driver = new Postgres(array('hostname' => 'localhost', 'username' => 'postgres', 'password' => 'postgres', 'database' => 'picodb'));
$this->driver->getConnection()->exec('DROP TABLE IF EXISTS foobar');
$this->driver->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
}
public function tearDown()
{
$this->driver->closeConnection();
}
/**
* @expectedException LogicException
*/
public function testMissingRequiredParameter()
{
new Postgres(array());
}
public function testDuplicateKeyError()
{
$this->assertFalse($this->driver->isDuplicateKeyError(1234));
$this->assertTrue($this->driver->isDuplicateKeyError(23505));
$this->assertTrue($this->driver->isDuplicateKeyError(23503));
}
public function testOperator()
{
$this->assertEquals('LIKE', $this->driver->getOperator('LIKE'));
$this->assertEquals('ILIKE', $this->driver->getOperator('ILIKE'));
$this->assertEquals('', $this->driver->getOperator('FOO'));
}
public function testSchemaVersion()
{
$this->assertEquals(0, $this->driver->getSchemaVersion());
$this->driver->setSchemaVersion(1);
$this->assertEquals(1, $this->driver->getSchemaVersion());
$this->driver->setSchemaVersion(42);
$this->assertEquals(42, $this->driver->getSchemaVersion());
}
public function testLastInsertId()
{
$this->assertEquals(0, $this->driver->getLastId());
$this->driver->getConnection()->exec('CREATE TABLE foobar (id serial PRIMARY KEY, something TEXT)');
$this->driver->getConnection()->exec('INSERT INTO foobar (something) VALUES (1)');
$this->assertEquals(1, $this->driver->getLastId());
}
public function testEscape()
{
$this->assertEquals('"foobar"', $this->driver->escape('foobar'));
}
}

View File

@ -1,34 +0,0 @@
<?php
require_once 'vendor/autoload.php';
require_once __DIR__.'/SchemaFixture.php';
class PostgresSchemaTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new PicoDb\Database(array('driver' => 'postgres', 'hostname' => 'localhost', 'username' => 'postgres', 'password' => 'postgres', 'database' => 'picodb'));
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test1');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test2');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
}
public function testMigrations()
{
$this->assertTrue($this->db->schema()->check(2));
$this->assertEquals(2, $this->db->getDriver()->getSchemaVersion());
}
public function testFailedMigrations()
{
$this->assertEquals(0, $this->db->getDriver()->getSchemaVersion());
$this->assertFalse($this->db->schema()->check(3));
$this->assertEquals(0, $this->db->getDriver()->getSchemaVersion());
$logs = $this->db->getLogMessages();
$this->assertNotEmpty($logs);
$this->assertStringStartsWith('\Schema\version_3 => SQLSTATE[42601]: Syntax error', $logs[0]);
}
}

View File

@ -1,312 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Database;
use PicoDb\Table;
class PostgresTableTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new Database(array('driver' => 'postgres', 'hostname' => 'localhost', 'username' => 'postgres', 'password' => 'postgres', 'database' => 'picodb'));
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test1');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS test2');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS foobar');
$this->db->getConnection()->exec('DROP TABLE IF EXISTS schema_version');
$this->db->logQueries = true;
}
public function testSelect()
{
$this->assertEquals('SELECT 1 FROM "test"', $this->db->table('test')->select(1)->buildSelectQuery());
}
public function testColumns()
{
$this->assertEquals('SELECT "a", "b" FROM "test"', $this->db->table('test')->columns('a', 'b')->buildSelectQuery());
}
public function testDistinct()
{
$this->assertEquals('SELECT DISTINCT "a", "b" FROM "test"', $this->db->table('test')->distinct('a', 'b')->buildSelectQuery());
}
public function testGroupBy()
{
$this->assertEquals('SELECT * FROM "test" GROUP BY "a"', $this->db->table('test')->groupBy('a')->buildSelectQuery());
}
public function testOrderBy()
{
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC', $this->db->table('test')->asc('a')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC', $this->db->table('test')->orderBy('a', Table::SORT_ASC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC', $this->db->table('test')->desc('a', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC', $this->db->table('test')->orderBy('a', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC, "b" ASC', $this->db->table('test')->asc('a')->asc('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC, "b" DESC', $this->db->table('test')->desc('a')->desc('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC, "b" ASC', $this->db->table('test')->orderBy('a')->orderBy('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC, "b" DESC', $this->db->table('test')->orderBy('a', Table::SORT_DESC)->orderBy('b', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC, "b" ASC', $this->db->table('test')->desc('a')->asc('b')->buildSelectQuery());
}
public function testLimit()
{
$this->assertEquals('SELECT * FROM "test" LIMIT 10', $this->db->table('test')->limit(10)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test"', $this->db->table('test')->limit(null)->buildSelectQuery());
}
public function testOffset()
{
$this->assertEquals('SELECT * FROM "test" OFFSET 0', $this->db->table('test')->offset(0)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" OFFSET 10', $this->db->table('test')->offset(10)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test"', $this->db->table('test')->limit(null)->buildSelectQuery());
}
public function testLimitOffset()
{
$this->assertEquals('SELECT * FROM "test" LIMIT 2 OFFSET 0', $this->db->table('test')->offset(0)->limit(2)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" LIMIT 5 OFFSET 10', $this->db->table('test')->offset(10)->limit(5)->buildSelectQuery());
}
public function testSubquery()
{
$this->assertEquals('SELECT (SELECT 1 FROM "foobar" WHERE 1=1) AS "b" FROM "test"', $this->db->table('test')->subquery('SELECT 1 FROM "foobar" WHERE 1=1', 'b')->buildSelectQuery());
}
public function testConditionEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" = ? AND "b" = ?', $table->eq('a', 2)->eq('b', 'foobar')->buildSelectQuery());
$this->assertEquals(array(2, 'foobar'), $table->condition->getValues());
}
public function testConditionNotEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" != ?', $table->neq('a', 2)->buildSelectQuery());
$this->assertEquals(array(2), $table->condition->getValues());
}
public function testConditionIn()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" IN (?, ?)', $table->in('a', array('b', 'c'))->buildSelectQuery());
$this->assertEquals(array('b', 'c'), $table->condition->getValues());
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test"', $table->in('a', array())->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testConditionNotIn()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" NOT IN (?, ?)', $table->notin('a', array('b', 'c'))->buildSelectQuery());
$this->assertEquals(array('b', 'c'), $table->condition->getValues());
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test"', $table->notin('a', array())->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testConditionLike()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" LIKE ?', $table->like('a', '%foobar%')->buildSelectQuery());
$this->assertEquals(array('%foobar%'), $table->condition->getValues());
}
public function testConditionILike()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" ILIKE ?', $table->ilike('a', '%foobar%')->buildSelectQuery());
$this->assertEquals(array('%foobar%'), $table->condition->getValues());
}
public function testConditionGreaterThan()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" > ?', $table->gt('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionGreaterThanOrEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" >= ?', $table->gte('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionLowerThan()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" < ?', $table->lt('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionLowerThanOrEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" <= ?', $table->lte('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionIsNull()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" IS NOT NULL', $table->notNull('a')->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testCustomCondition()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE a=c AND "b" = ?', $table->addCondition('a=c')->eq('b', 4)->buildSelectQuery());
$this->assertEquals(array(4), $table->condition->getValues());
}
public function testOrConditions()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" IS NOT NULL AND ("b" = ? OR "c" >= ?)', $table->notNull('a')->beginOr()->eq('b', 2)->gte('c', 5)->closeOr()->buildSelectQuery());
$this->assertEquals(array(2, 5), $table->condition->getValues());
}
public function testInsertUpdate()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a TEXT)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'b')));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'c')));
$this->assertEquals(array(array('a' => 'b'), array('a' => 'c')), $this->db->table('foobar')->findAll());
$this->assertEquals(array('b', 'c'), $this->db->table('foobar')->findAllByColumn('a'));
$this->assertEquals(array('a' => 'b'), $this->db->table('foobar')->findOne());
$this->assertEquals('b', $this->db->table('foobar')->findOneColumn('a'));
$this->assertTrue($this->db->table('foobar')->exists());
$this->assertTrue($this->db->table('foobar')->eq('a', 'c')->exists());
$this->assertFalse($this->db->table('foobar')->eq('a', 'e')->exists());
$this->assertEquals(2, $this->db->table('foobar')->count());
$this->assertEquals(1, $this->db->table('foobar')->eq('a', 'c')->count());
$this->assertEquals(0, $this->db->table('foobar')->eq('a', 'e')->count());
$this->assertTrue($this->db->table('foobar')->eq('a', 'c')->remove());
$this->assertFalse($this->db->table('foobar')->eq('a', 'e')->remove());
$this->assertTrue($this->db->table('foobar')->eq('a', 'b')->update(array('a' => 'test')));
$this->assertTrue($this->db->table('foobar')->eq('a', 'lol')->update(array('a' => 'test')));
$this->assertNotEmpty($this->db->table('foobar')->eq('a', 'test')->findOne());
$this->assertNull($this->db->table('foobar')->eq('a', 'lol')->findOne());
$this->assertTrue($this->db->table('foobar')->eq('a', 'test')->save(array('a' => 'plop')));
$this->assertEquals(1, $this->db->table('foobar')->count());
}
public function testSumColumn()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (b REAL, c REAL)'));
$this->assertTrue($this->db->table('foobar')->insert(array('b' => 2, 'c' => 3.3)));
$this->assertTrue($this->db->table('foobar')->sumColumn('b', 2.5)->sumColumn('c', 3)->update());
$this->assertEquals(
array('b' => 4.5, 'c' => 6.3),
$this->db->table('foobar')->findOne()
);
}
public function testSum()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a INTEGER)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 2)));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 5)));
$this->assertEquals(7, $this->db->table('foobar')->sum('a'));
}
public function testLeftJoin()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE test1 (a INTEGER NOT NULL, foreign_key INTEGER NOT NULL)'));
$this->assertNotFalse($this->db->execute('CREATE TABLE test2 (id INTEGER NOT NULL, b INTEGER NOT NULL)'));
$this->assertTrue($this->db->table('test2')->insert(array('id' => 42, 'b' => 2)));
$this->assertTrue($this->db->table('test1')->insert(array('a' => 18, 'foreign_key' => 42)));
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test2')->columns('a', 'b')->eq('a', 18)->left('test1', 't1', 'foreign_key', 'test2', 'id')->findOne()
);
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test2')->columns('a', 'b')->eq('a', 18)->join('test1', 'foreign_key', 'id')->findOne()
);
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test1')->columns('a', 'b')->join('test2', 'id', 'foreign_key')->findOne()
);
}
public function testHashTable()
{
$this->assertNotFalse($this->db->execute(
'CREATE TABLE foobar (
column1 TEXT NOT NULL UNIQUE,
column2 TEXT default NULL
)'
));
$this->assertTrue($this->db->table('foobar')->insert(array('column1' => 'option1', 'column2' => 'value1')));
$this->assertTrue($this->db->table('foobar')->insert(array('column1' => 'option2', 'column2' => 'value2')));
$this->assertTrue($this->db->table('foobar')->insert(array('column1' => 'option3', 'column2' => 'value3')));
$values = array(
'option1' => 'hey',
'option4' => 'ho',
);
$this->assertTrue($this->db->hashtable('foobar')->columnKey('column1')->columnValue('column2')->put($values));
$this->assertEquals(
array('option2' => 'value2', 'option4' => 'ho'),
$this->db->hashtable('foobar')->columnKey('column1')->columnValue('column2')->get('option2', 'option4')
);
$this->assertEquals(
array('option2' => 'value2', 'option3' => 'value3', 'option1' => 'hey', 'option4' => 'ho'),
$this->db->hashtable('foobar')->columnKey('column1')->columnValue('column2')->get()
);
$this->assertEquals(
array('option2' => 'value2', 'option3' => 'value3', 'option1' => 'hey', 'option4' => 'ho'),
$this->db->hashtable('foobar')->getAll('column1', 'column2')
);
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace Schema;
function version_1($pdo)
{
$pdo->exec('CREATE TABLE test1 (column1 TEXT)');
}
function version_2($pdo)
{
$pdo->exec('CREATE TABLE test2 (column2 TEXT)');
}
function version_3($pdo)
{
// Simulate an error
$pdo->exec('CREATE TABL');
}

View File

@ -1,119 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Database;
class SqliteDatabaseTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new Database(array('driver' => 'sqlite', 'filename' => ':memory:'));
$this->db->logQueries = true;
}
public function testEscapeIdentifer()
{
$this->assertEquals('"a"', $this->db->escapeIdentifier('a'));
$this->assertEquals('a.b', $this->db->escapeIdentifier('a.b'));
$this->assertEquals('"c"."a"', $this->db->escapeIdentifier('a', 'c'));
$this->assertEquals('a.b', $this->db->escapeIdentifier('a.b', 'c'));
$this->assertEquals('SELECT COUNT(*) FROM test', $this->db->escapeIdentifier('SELECT COUNT(*) FROM test'));
$this->assertEquals('SELECT COUNT(*) FROM test', $this->db->escapeIdentifier('SELECT COUNT(*) FROM test', 'b'));
}
public function testEscapeIdentiferList()
{
$this->assertEquals(array('"c"."a"', '"c"."b"'), $this->db->escapeIdentifierList(array('a', 'b'), 'c'));
$this->assertEquals(array('"a"', 'd.b'), $this->db->escapeIdentifierList(array('a', 'd.b')));
}
public function testThatPreparedStatementWorks()
{
$this->db->getConnection()->exec('CREATE TABLE foobar (id INTEGER PRIMARY KEY, something TEXT)');
$this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
$this->assertEquals(1, $this->db->getLastId());
$this->assertEquals('a', $this->db->execute('SELECT something FROM foobar WHERE something=?', array('a'))->fetchColumn());
}
/**
* @expectedException PicoDb\SQLException
*/
public function testBadSQLQuery()
{
$this->db->execute('INSERT INTO foobar');
}
public function testDuplicateKey()
{
$this->db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$this->assertNotFalse($this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a')));
$this->assertFalse($this->db->execute('INSERT INTO foobar (something) VALUES (?)', array('a')));
$this->assertEquals(1, $this->db->execute('SELECT COUNT(*) FROM foobar WHERE something=?', array('a'))->fetchColumn());
}
public function testThatTransactionReturnsAValue()
{
$this->assertEquals('a', $this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
return $db->execute('SELECT something FROM foobar WHERE something=?', array('a'))->fetchColumn();
}));
}
public function testThatTransactionReturnsTrue()
{
$this->assertTrue($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
}));
}
/**
* @expectedException PicoDb\SQLException
*/
public function testThatTransactionThrowExceptionWhenRollbacked()
{
$this->assertFalse($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABL');
}));
}
public function testThatTransactionReturnsFalseWhithDuplicateKey()
{
$this->assertFalse($this->db->transaction(function ($db) {
$db->getConnection()->exec('CREATE TABLE foobar (something TEXT UNIQUE)');
$r1 = $db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
$r2 = $db->execute('INSERT INTO foobar (something) VALUES (?)', array('a'));
return $r1 && $r2;
}));
}
public function testGetInstance()
{
Database::setInstance('main', function () {
return new Database(array('driver' => 'sqlite', 'filename' => ':memory:'));
});
$instance1 = Database::getInstance('main');
$instance2 = Database::getInstance('main');
$this->assertInstanceOf('PicoDb\Database', $instance1);
$this->assertInstanceOf('PicoDb\Database', $instance2);
$this->assertTrue($instance1 === $instance2);
}
/**
* @expectedException LogicException
*/
public function testGetMissingInstance()
{
Database::getInstance('notfound');
}
}

View File

@ -1,62 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Driver\Sqlite;
class SqliteDriverTest extends PHPUnit_Framework_TestCase
{
private $driver;
public function setUp()
{
$this->driver = new Sqlite(array('filename' => ':memory:'));
}
/**
* @expectedException LogicException
*/
public function testMissingRequiredParameter()
{
new Sqlite(array());
}
public function testDuplicateKeyError()
{
$this->assertFalse($this->driver->isDuplicateKeyError(1234));
$this->assertTrue($this->driver->isDuplicateKeyError(23000));
}
public function testOperator()
{
$this->assertEquals('LIKE', $this->driver->getOperator('LIKE'));
$this->assertEquals('LIKE', $this->driver->getOperator('ILIKE'));
$this->assertEquals('', $this->driver->getOperator('FOO'));
}
public function testSchemaVersion()
{
$this->assertEquals(0, $this->driver->getSchemaVersion());
$this->driver->setSchemaVersion(1);
$this->assertEquals(1, $this->driver->getSchemaVersion());
$this->driver->setSchemaVersion(42);
$this->assertEquals(42, $this->driver->getSchemaVersion());
}
public function testLastInsertId()
{
$this->assertEquals(0, $this->driver->getLastId());
$this->driver->getConnection()->exec('CREATE TABLE foobar (id INTEGER PRIMARY KEY, something TEXT)');
$this->driver->getConnection()->exec('INSERT INTO foobar (something) VALUES (1)');
$this->assertEquals(1, $this->driver->getLastId());
}
public function testEscape()
{
$this->assertEquals('"foobar"', $this->driver->escape('foobar'));
}
}

View File

@ -1,30 +0,0 @@
<?php
require_once 'vendor/autoload.php';
require_once __DIR__.'/SchemaFixture.php';
class SqliteSchemaTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new PicoDb\Database(array('driver' => 'sqlite', 'filename' => ':memory:'));
}
public function testMigrations()
{
$this->assertTrue($this->db->schema()->check(2));
$this->assertEquals(2, $this->db->getDriver()->getSchemaVersion());
}
public function testFailedMigrations()
{
$this->assertFalse($this->db->schema()->check(3));
$this->assertEquals(0, $this->db->getDriver()->getSchemaVersion());
$logs = $this->db->getLogMessages();
$this->assertNotEmpty($logs);
$this->assertEquals('\Schema\version_3 => SQLSTATE[HY000]: General error: 1 near "TABL": syntax error', $logs[0]);
}
}

View File

@ -1,327 +0,0 @@
<?php
require_once 'vendor/autoload.php';
use PicoDb\Database;
use PicoDb\Table;
class SqliteTableTest extends PHPUnit_Framework_TestCase
{
private $db;
public function setUp()
{
$this->db = new Database(array('driver' => 'sqlite', 'filename' => ':memory:'));
}
public function testSelect()
{
$this->assertEquals('SELECT 1 FROM "test"', $this->db->table('test')->select(1)->buildSelectQuery());
}
public function testColumns()
{
$this->assertEquals('SELECT "a", "b" FROM "test"', $this->db->table('test')->columns('a', 'b')->buildSelectQuery());
}
public function testDistinct()
{
$this->assertEquals('SELECT DISTINCT "a", "b" FROM "test"', $this->db->table('test')->distinct('a', 'b')->buildSelectQuery());
}
public function testGroupBy()
{
$this->assertEquals('SELECT * FROM "test" GROUP BY "a"', $this->db->table('test')->groupBy('a')->buildSelectQuery());
}
public function testOrderBy()
{
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC', $this->db->table('test')->asc('a')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC', $this->db->table('test')->orderBy('a', Table::SORT_ASC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC', $this->db->table('test')->desc('a', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC', $this->db->table('test')->orderBy('a', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC, "b" ASC', $this->db->table('test')->asc('a')->asc('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC, "b" DESC', $this->db->table('test')->desc('a')->desc('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" ASC, "b" ASC', $this->db->table('test')->orderBy('a')->orderBy('b')->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC, "b" DESC', $this->db->table('test')->orderBy('a', Table::SORT_DESC)->orderBy('b', Table::SORT_DESC)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" ORDER BY "a" DESC, "b" ASC', $this->db->table('test')->desc('a')->asc('b')->buildSelectQuery());
}
public function testLimit()
{
$this->assertEquals('SELECT * FROM "test" LIMIT 10', $this->db->table('test')->limit(10)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test"', $this->db->table('test')->limit(null)->buildSelectQuery());
}
public function testOffset()
{
$this->assertEquals('SELECT * FROM "test" OFFSET 0', $this->db->table('test')->offset(0)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" OFFSET 10', $this->db->table('test')->offset(10)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test"', $this->db->table('test')->limit(null)->buildSelectQuery());
}
public function testLimitOffset()
{
$this->assertEquals('SELECT * FROM "test" LIMIT 2 OFFSET 0', $this->db->table('test')->offset(0)->limit(2)->buildSelectQuery());
$this->assertEquals('SELECT * FROM "test" LIMIT 5 OFFSET 10', $this->db->table('test')->offset(10)->limit(5)->buildSelectQuery());
}
public function testSubquery()
{
$this->assertEquals('SELECT (SELECT 1 FROM "foobar" WHERE 1=1) AS "b" FROM "test"', $this->db->table('test')->subquery('SELECT 1 FROM "foobar" WHERE 1=1', 'b')->buildSelectQuery());
}
public function testConditionEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" = ? AND "b" = ?', $table->eq('a', 2)->eq('b', 'foobar')->buildSelectQuery());
$this->assertEquals(array(2, 'foobar'), $table->condition->getValues());
}
public function testConditionNotEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" != ?', $table->neq('a', 2)->buildSelectQuery());
$this->assertEquals(array(2), $table->condition->getValues());
}
public function testConditionIn()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" IN (?, ?)', $table->in('a', array('b', 'c'))->buildSelectQuery());
$this->assertEquals(array('b', 'c'), $table->condition->getValues());
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test"', $table->in('a', array())->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testConditionNotIn()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" NOT IN (?, ?)', $table->notin('a', array('b', 'c'))->buildSelectQuery());
$this->assertEquals(array('b', 'c'), $table->condition->getValues());
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test"', $table->notin('a', array())->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testConditionLike()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" LIKE ?', $table->like('a', '%foobar%')->buildSelectQuery());
$this->assertEquals(array('%foobar%'), $table->condition->getValues());
}
public function testConditionILike()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" LIKE ?', $table->ilike('a', '%foobar%')->buildSelectQuery());
$this->assertEquals(array('%foobar%'), $table->condition->getValues());
}
public function testConditionGreaterThan()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" > ?', $table->gt('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionGreaterThanOrEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" >= ?', $table->gte('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionLowerThan()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" < ?', $table->lt('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionLowerThanOrEqual()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" <= ?', $table->lte('a', 5)->buildSelectQuery());
$this->assertEquals(array(5), $table->condition->getValues());
}
public function testConditionIsNull()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" IS NOT NULL', $table->notNull('a')->buildSelectQuery());
$this->assertEquals(array(), $table->condition->getValues());
}
public function testCustomCondition()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE a=c AND "b" = ?', $table->addCondition('a=c')->eq('b', 4)->buildSelectQuery());
$this->assertEquals(array(4), $table->condition->getValues());
}
public function testOrConditions()
{
$table = $this->db->table('test');
$this->assertEquals('SELECT * FROM "test" WHERE "a" IS NOT NULL AND ("b" = ? OR "c" >= ?)', $table->notNull('a')->beginOr()->eq('b', 2)->gte('c', 5)->closeOr()->buildSelectQuery());
$this->assertEquals(array(2, 5), $table->condition->getValues());
}
public function testInsertUpdate()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a TEXT)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'b')));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'c')));
$this->assertEquals(array(array('a' => 'b'), array('a' => 'c')), $this->db->table('foobar')->findAll());
$this->assertEquals(array('b', 'c'), $this->db->table('foobar')->findAllByColumn('a'));
$this->assertEquals(array('a' => 'b'), $this->db->table('foobar')->findOne());
$this->assertEquals('b', $this->db->table('foobar')->findOneColumn('a'));
$this->assertTrue($this->db->table('foobar')->exists());
$this->assertTrue($this->db->table('foobar')->eq('a', 'c')->exists());
$this->assertFalse($this->db->table('foobar')->eq('a', 'e')->exists());
$this->assertEquals(2, $this->db->table('foobar')->count());
$this->assertEquals(1, $this->db->table('foobar')->eq('a', 'c')->count());
$this->assertEquals(0, $this->db->table('foobar')->eq('a', 'e')->count());
$this->assertTrue($this->db->table('foobar')->eq('a', 'c')->remove());
$this->assertFalse($this->db->table('foobar')->eq('a', 'e')->remove());
$this->assertTrue($this->db->table('foobar')->eq('a', 'b')->update(array('a' => 'test')));
$this->assertTrue($this->db->table('foobar')->eq('a', 'lol')->update(array('a' => 'test')));
$this->assertNotEmpty($this->db->table('foobar')->eq('a', 'test')->findOne());
$this->assertNull($this->db->table('foobar')->eq('a', 'lol')->findOne());
$this->assertTrue($this->db->table('foobar')->eq('a', 'test')->save(array('a' => 'plop')));
$this->assertEquals(1, $this->db->table('foobar')->count());
}
public function testSumColumn()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (b REAL, c REAL)'));
$this->assertTrue($this->db->table('foobar')->insert(array('b' => 2, 'c' => 3.3)));
$this->assertTrue($this->db->table('foobar')->sumColumn('b', 2.5)->sumColumn('c', 3)->update());
$this->assertEquals(
array('b' => 4.5, 'c' => 6.3),
$this->db->table('foobar')->findOne()
);
}
public function testCallback()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a TEXT)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'b')));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 'c')));
$func = function (array $records) {
return array('test');
};
$this->assertEquals(array('test'), $this->db->table('foobar')->callback($func)->findAll());
$this->assertEquals(array('plop'), $this->db->table('foobar')->callback(array($this, 'myCallback'))->findAll());
}
public function myCallback(array $records)
{
$this->assertEquals(array(array('a' => 'b'), array('a' => 'c')), $records);
return array('plop');
}
public function testSum()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE foobar (a INTEGER)'));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 2)));
$this->assertTrue($this->db->table('foobar')->insert(array('a' => 5)));
$this->assertEquals(7, $this->db->table('foobar')->sum('a'));
}
public function testLeftJoin()
{
$this->assertNotFalse($this->db->execute('CREATE TABLE test1 (a INTEGER NOT NULL, foreign_key INTEGER NOT NULL)'));
$this->assertNotFalse($this->db->execute('CREATE TABLE test2 (id INTEGER NOT NULL, b INTEGER NOT NULL)'));
$this->assertTrue($this->db->table('test2')->insert(array('id' => 42, 'b' => 2)));
$this->assertTrue($this->db->table('test1')->insert(array('a' => 18, 'foreign_key' => 42)));
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test2')->columns('a', 'b')->eq('a', 18)->left('test1', 't1', 'foreign_key', 'test2', 'id')->findOne()
);
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test2')->columns('a', 'b')->eq('a', 18)->join('test1', 'foreign_key', 'id')->findOne()
);
$this->assertEquals(
array('a' => 18, 'b' => 2),
$this->db->table('test1')->columns('a', 'b')->join('test2', 'id', 'foreign_key')->findOne()
);
}
public function testHashTable()
{
$this->assertNotFalse($this->db->execute(
'CREATE TABLE toto (
column1 TEXT NOT NULL UNIQUE,
column2 TEXT default NULL
)'
));
$this->assertTrue($this->db->table('toto')->insert(array('column1' => 'option1', 'column2' => 'value1')));
$this->assertTrue($this->db->table('toto')->insert(array('column1' => 'option2', 'column2' => 'value2')));
$this->assertTrue($this->db->table('toto')->insert(array('column1' => 'option3', 'column2' => 'value3')));
$values = array(
'option1' => 'hey',
'option4' => 'ho',
);
$this->assertTrue($this->db->hashtable('toto')->columnKey('column1')->columnValue('column2')->put($values));
$this->assertEquals(
array('option2' => 'value2', 'option4' => 'ho'),
$this->db->hashtable('toto')->columnKey('column1')->columnValue('column2')->get('option2', 'option4')
);
$this->assertEquals(
array('option2' => 'value2', 'option3' => 'value3', 'option1' => 'hey', 'option4' => 'ho'),
$this->db->hashtable('toto')->columnKey('column1')->columnValue('column2')->get()
);
$this->assertEquals(
array('option2' => 'value2', 'option3' => 'value3', 'option1' => 'hey', 'option4' => 'ho'),
$this->db->hashtable('toto')->getAll('column1', 'column2')
);
}
}

View File

@ -79,7 +79,7 @@ class Attribute
'cite' => array(),
'time' => array('datetime'),
'abbr' => array('title'),
'iframe' => array('width', 'height', 'frameborder', 'src'),
'iframe' => array('width', 'height', 'frameborder', 'src', 'allowfullscreen'),
'q' => array('cite')
);
@ -227,7 +227,6 @@ class Attribute
* @var array
*/
private $filters = array(
'filterEmptyAttribute',
'filterAllowedAttribute',
'filterIntegerAttribute',
'rewriteAbsoluteUrl',
@ -280,20 +279,6 @@ class Attribute
return $attributes;
}
/**
* Return true if the value is not empty (remove empty attributes)
*
* @access public
* @param string $tag Tag name
* @param string $attribute Attribute name
* @param string $value Attribute value
* @return boolean
*/
public function filterEmptyAttribute($tag, $attribute, $value)
{
return $value !== '';
}
/**
* Return true if the value is allowed (remove not allowed attributes)
*

View File

@ -0,0 +1,17 @@
<?php
return array(
'grabber' => array(
'%.*%' => array(
'body' => array('//div[@id="comic"]',
'//div[contains(@class,"entry-content")]',
),
'strip' => array(),
'test_url' => 'http://mercworks.net/comicland/healthy-choice/',
)
),
'filter' => array(
'%.*%' => array(
'%title="(.+)" */>%' => "/><br/>$1"
)
)
);

View File

@ -2,7 +2,8 @@
return array(
'filter' => array(
'%.*%' => array(
'%alt="(.+)" */>%' => "/><br/>$1"
'%alt="(.+)" */>%' => "/><br/>$1",
'%\.png%' => "_rollover.png",
)
)
);

View File

@ -0,0 +1,10 @@
<?php
return array(
'grabber' => array(
'%.*%' => array(
'body' => array('//img[@id="cc-comic"]'),
'strip' => array(),
'test_url' => 'http://www.threepanelsoul.com/comic/subjective-tastes',
)
),
);