Browse Source

Merge branch 'master' into mongo

master
Anton Grebnev 12 years ago
parent
commit
c090634c19
  1. 2
      app/AjaxAction.php
  2. 2
      logger/CliLogger.php
  3. 14
      logger/Logger.php
  4. 75
      model/MongoDbCommand.php
  5. 9
      model/MongoDriver.php
  6. 6
      redis/RedisDebug.php
  7. 50
      redis/redis.php
  8. 1
      tests/LoadTest.php
  9. 1
      tests/logger/FileLoggerTest.php
  10. 40
      tests/model/MongoDbCommandTest.php
  11. 2
      tests/redis/RedisDebugTest.php
  12. 15
      tests/util/AutoloadBuilderTest.php
  13. 1
      tests/view/PHPViewTest.php
  14. 42
      util/AutoloadBuilder.php

2
app/AjaxAction.php

@ -4,7 +4,7 @@
*
* @copyright NetMonsters <team@netmonsters.ru>
* @link
* @package Kuperauto
* @package Majestic
* @subpackage face
* @since
* @version SVN: $Id$

2
logger/CliLogger.php

@ -13,7 +13,7 @@ class CliLogger extends Logger
protected function concreteLog($message)
{
// Заменяем окончания строк на их символы
$message = str_replace(array("\r\n"), array(PHP_EOL), $message);
$message = str_replace(array("\r", "\n"), array('\r', '\n'), $message);
$out = microtime(true) . " \t: " . $this->pid . trim($message) . PHP_EOL;
print($out);
}

14
logger/Logger.php

@ -12,24 +12,31 @@ abstract class Logger
{
protected static $_instance = null;
/**
* pid текущего процесса
* @var string
*/
protected $pid = '';
protected function __construct() {}
protected function __construct()
{
}
/**
* @static
* @return Logger
*/
public static function getInstance()
{
if(static::$_instance === null) {
if (static::$_instance === null) {
//$class = get_called_class();
$class = Config::get('Logger')->logger;
static::$_instance = new $class();
}
return static::$_instance;
}
/**
* Вывод лога
* @param string $message Сообщение
@ -53,5 +60,4 @@ abstract class Logger
}
abstract protected function concreteLog($message);
}

75
model/MongoDbCommand.php

@ -12,6 +12,8 @@ class MongoCommandBuilder
const FIND = 'Find';
const COUNT = 'Count';
const INSERT = 'Insert';
const UPDATE = 'Update';
@ -68,9 +70,9 @@ abstract class MongoDbCommand
class FindMongoCommand extends MongoDbCommand
{
protected $condition;
protected $condition = array();
protected $fields;
protected $fields = array();
protected $multiple = true;
@ -95,11 +97,12 @@ class FindMongoCommand extends MongoDbCommand
public function __toString()
{
if ($this->checkParams()) {
$result = 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
ob_start();
var_dump($this->condition);
$condition = ob_get_clean();
$result .= 'Condition: ' . $condition . PHP_EOL;
$result .= 'Condition: ' . $condition;
$result .= 'Type: FIND' . PHP_EOL;
ob_start();
var_dump($this->fields);
$fields = ob_get_clean();
@ -113,6 +116,48 @@ class FindMongoCommand extends MongoDbCommand
}
}
class CountMongoCommand extends MongoDbCommand
{
protected $condition = array();
protected $limit = 0;
protected $skip = 0;
protected $multiple = true;
protected function concreteExecute()
{
return $this->collection->count($this->condition, $this->limit, $this->skip);
}
protected function checkParams()
{
if (isset($this->collection) && isset($this->condition) && isset($this->limit) && isset($this->skip)) {
return true;
} else {
return false;
}
}
public function __toString()
{
if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result .= 'Type: COUNT' . PHP_EOL;
ob_start();
var_dump($this->condition);
$condition = ob_get_clean();
$result .= 'Condition: ' . $condition;
$result .= 'Limit: ' . $this->limit . PHP_EOL;
$result .= 'Skip: ' . $this->skip . PHP_EOL;
return $result;
} else {
return 'Command properties not set';
}
}
}
class InsertMongoCommand extends MongoDbCommand
{
protected $data;
@ -154,11 +199,12 @@ class InsertMongoCommand extends MongoDbCommand
public function __toString()
{
if ($this->checkParams()) {
$result = 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result .= 'Type: INSERT' . PHP_EOL;
ob_start();
var_dump($this->data);
$data = ob_get_clean();
$result .= 'Data: ' . $data . PHP_EOL;
$result .= 'Data: ' . $data;
$mult = $this->multiple ? 'TRUE' : 'FALSE';
$result .= 'Bulk insert: ' . $mult . PHP_EOL;
$safe = $this->safe ? 'TRUE' : 'FALSE';
@ -202,15 +248,16 @@ class UpdateMongoCommand extends MongoDbCommand
public function __toString()
{
if ($this->checkParams()) {
$result = 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result .= 'Type: UPDATE' . PHP_EOL;
ob_start();
var_dump($this->condition);
$condition = ob_get_clean();
$result .= 'Condition: ' . $condition . PHP_EOL;
$result .= 'Condition: ' . $condition;
ob_start();
var_dump($this->data);
$data = ob_get_clean();
$result .= 'Data: ' . $data . PHP_EOL;
$result .= 'Data: ' . $data;
$mult = $this->multiple ? 'TRUE' : 'FALSE';
$result .= 'Multiple fields: ' . $mult . PHP_EOL;
$upsert = $this->upsert ? 'TRUE' : 'FALSE';
@ -247,11 +294,12 @@ class RemoveMongoCommand extends MongoDbCommand
public function __toString()
{
if ($this->checkParams()) {
$result = 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result .= 'Type: REMOVE' . PHP_EOL;
ob_start();
var_dump($this->condition);
$condition = ob_get_clean();
$result .= 'Condition: ' . $condition . PHP_EOL;
$result .= 'Condition: ' . $condition;
$safe = $this->safe ? 'TRUE' : 'FALSE';
$result .= 'Safe operation: ' . $safe . PHP_EOL;
return $result;
@ -287,11 +335,12 @@ class CommandMongoCommand extends MongoDbCommand
public function __toString()
{
if ($this->checkParams()) {
$result = 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result .= 'Type: COMMAND' . PHP_EOL;
ob_start();
var_dump($this->command);
$command = ob_get_clean();
$result .= 'Command: ' . $command . PHP_EOL;
$result .= 'Command: ' . $command;
return $result;
} else {
return 'Command properties not set';

9
model/MongoDriver.php

@ -28,7 +28,14 @@ class MongoDriver extends NoSqlDbDriver
public function count($collection, $query = array(), $limit = 0, $skip = 0)
{
return $this->getCollection($collection)->count($query, $limit, $skip);
$command = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT, $this->getCollection($collection));
$params = array(
'condition' => $query,
'limit' => $limit,
'skip' => $skip
);
return $this->query($command, $params)->affectedRows();
}
public function find($collection, $condition = array(), $fields = array())

6
redis/RedisDebug.php

@ -25,12 +25,6 @@ class RedisDebug
{
$command = $this->r_implode(', ', $arguments);
$profiler = Profiler::getInstance()->profilerCommand('Redis->' . $name, $command);
$search = array_search($name, get_class_methods($this->redis));
if (empty($search)) {
throw new GeneralException('undefined method:'.$name);
}
$data = call_user_func_array(array($this->redis, $name), $arguments);
$profiler->end();
return $data;

50
redis/redis.php

@ -0,0 +1,50 @@
<?php
/**
*
*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage Redis
* @since 2011-05-17
*/
/**
* Redis stub for https://github.com/nicolasff/phpredis
* @author aterekhov
* @see https://github.com/nicolasff/phpredis
*
* @method bool connect() connect(string $host, int $port = 6379, float $timeout = 0) Connect to redis
* @method bool pconnect() connect(string $host, int $port = 6379, float $timeout = 0, string $persistent_id) Connect to redis with reusing connection
* @method void close() Close connection to redis
* @method bool setOption() setOption(mixed $name, mixed $value) Set client option
* @method mixed getOption() getOption(mixed $name) Get client option
* @method string ping() ping() Check the current connection status
* @method string|bool get() get(string $key) Get the value related to the specified key
* @method bool set() set(string $key, mixed $value, int $timeout = null) Set the string value in argument as value of the key
* @method bool setex() setex(string $key, int $ttl, mixed $value) Set the string value in argument as value of the key, with a time to live
* @method bool setnx() setnx(string $key, int $ttl) Set the string value in argument as value of the key if the key doesn't already exist in the database
* @method float delete() delete(mixed $key) Remove specified keys
* @method Redis multi() multi(mixed $mode = 1) Enter and exit transactional mode
* @method bool exec() exec() Enter and exit transactional mode
* @method void watch() watch(mixed $keys) Watches a key for modifications by another client
* @method void unwatch() unwatch(mixed $keys) Watches a key for modifications by another client
* @method void subscribe() subscribe(array $channels, mixed $callback) Subscribe to channels. Warning: this function will probably change in the future
* @method void publish() publish(string $channel, string $message) Publish messages to channels. Warning: this function will probably change in the future
* @method bool exists() exists(string $key) Verify if the specified key exists
* @method int incr() incr(string $key) Increment the number stored at key by one
* @method int incrBy() incrBy(string $key, int $value) Increment the number stored at key by $value
*
* @method bool expire() expire(string $key, int $ttl) Sets an expiration date (a timeout) on an item
*
* @method float zAdd() zAdd(string $key, float $score, string $value) Adds the specified member with a given score to the sorted set stored at key
* @method array zRange() zRange(string $key, float $start, float $end, bool $with_scores = false) Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end]
* @method array zRevRange() zRevRange(string $key, float $start, float $end, bool $with_scores = false) Returns a range of elements from the ordered set stored at the specified key, with values in the range [start, end]
* @method float zCard() zCard(string $key) Returns the cardinality of an ordered set
* @method float zUnionStore() zUnionStore(string $destination, array $keys, array $weights = array(), string $aggregate = 'sum') Creates an union of sorted sets given in second argument and store in in first argument
* @method float zInterStore() zInterStore(string $destination, array $keys, array $weights = array(), string $aggregate = 'sum') Creates an intersection of sorted sets given in second argument and store in in first argument
*/
class Redis
{
}

1
tests/LoadTest.php

@ -42,6 +42,7 @@ class LoadTest extends PHPUnit_Framework_TestCase
self::$autoload_array = array('Db' => '/lib/core/model/Db.php', 'DbDriver' => '/lib/core/model/DbDriver.php');
vfsStreamWrapper::register();
vfsStream::setup();
$this->root = vfsStream::create(
array(
'lib' => array(

1
tests/logger/FileLoggerTest.php

@ -30,6 +30,7 @@ class FileLoggerTest extends PHPUnit_Framework_TestCase
public function setUp()
{
vfsStreamWrapper::register();
vfsStream::setup();
$root = vfsStream::create(array());
vfsStreamWrapper::setRoot($root);
$this->conf = array('logger' => 'FileLogger', 'filepath' => vfsStream::url('root/log.txt'));

40
tests/model/MongoDbCommandTest.php

@ -99,12 +99,34 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
/**
* @group Mongo
*/
public function testFindCommandNotAllParamsBinded()
public function testCountCommand()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'bread'));
$this->setExpectedException('GeneralException', 'FindMongoCommand error. Bind all required params first');
$count_cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT, $this->collection);
$count_cmd->bindParam('condition', array('name' => 'bread'));
$count_result = $count_cmd->execute();
$find_cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$find_cmd->bindParam('condition', array('name' => 'bread'))->bindParam('fields', array());
$find_result = $find_cmd->execute();
$this->assertEquals(0, $count_result);
$this->assertEquals($count_result, $find_result->count());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$cmd->execute();
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$cmd->execute();
$count_cmd->bindParam('condition', array('name' => 'insert'));
$this->assertEquals(2, $count_cmd->execute());
$find_cmd->bindParam('condition', array('name' => 'insert'));
$this->assertEquals($find_cmd->execute()->count(), $count_cmd->execute());
}
/**
@ -305,6 +327,14 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
*/
public function testToString()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT, new CollectionMock());
$cmd->bindParam('condition', array());
$this->assertStringStartsWith('Collection: CollectionMock', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, new CollectionMock());
$cmd->bindParam('condition', array());
$this->assertStringStartsWith('Collection: CollectionMock', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, new CollectionMock());
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('command', array());
@ -326,8 +356,6 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
->bindParam('safe', true);
$this->assertContains('Bulk insert: TRUE', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$this->assertStringStartsWith('Collection: ', $cmd->__toString());

2
tests/redis/RedisDebugTest.php

@ -103,7 +103,7 @@ class RedisDebugTest extends PHPUnit_Framework_TestCase
$mock = $this->getMock('Redis', array('connect'));
$redisDebug = new RedisDebug($mock);
$this->setExpectedException('GeneralException');
$this->setExpectedException('PHPUnit_Framework_Error', 'call_user_func_array() expects parameter 1 to be a valid callback, class \'Mock_Redis_');
$this->assertNull($redisDebug->nothing('localhost', 4322));
}

15
tests/util/AutoloadBuilderTest.php

@ -77,6 +77,7 @@ class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
$this->setConstants();
$builder = new AutoloadBuilder(self::$file, array(self::$path . '/' . self::$app . '/src', self::$path . '/' . self::$app . '/cache', self::$path . '/lib'));
$this->assertFileNotExists(self::$file);
$builder->build();
$this->assertFileExists(self::$file);
@ -84,6 +85,8 @@ class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
$array = require self::$file;
$this->assertInternalType('array', $array);
$this->assertNotEmpty($array);
$this->assertArrayHasKey('AutoloadBuilder', $array);
$this->assertArrayHasKey('Load', $array);
}
/**
@ -94,7 +97,10 @@ class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
$this->setConstants();
$this->setExpectedException('PHPUnit_Framework_Error');
$this->assertFileNotExists(self::$file);
touch(self::$file);
$this->assertFileExists(self::$file);
chmod(self::$file, 0400);
$builder = new AutoloadBuilder(self::$file, array(self::$path . '/' . self::$app . '/src', self::$path . '/' . self::$app . '/cache', self::$path . '/lib'));
@ -102,15 +108,6 @@ class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
chmod(self::$file, 0777);
}
public function tearDown()
{
// if (defined('PATH')) {
// echo PHP_EOL . __CLASS__ . ' ' . PATH . PHP_EOL;
// } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'PATH NOT DEFINED' . PHP_EOL;
// }
}
public static function tearDownAfterClass()
{
if (file_exists(self::$file)) {

1
tests/view/PHPViewTest.php

@ -28,6 +28,7 @@ class PHPViewTest extends PHPUnit_Framework_TestCase
public function setUp()
{
vfsStreamWrapper::register();
vfsStream::setup();
$root = vfsStream::create(array());
vfsStreamWrapper::setRoot($root);
$views_dir = vfsStream::newDirectory('views');

42
util/AutoloadBuilder.php

@ -35,7 +35,7 @@ class AutoloadBuilder
public function build()
{
$this->openAutoload();
$array_string = "<?php\n// This file is autogenerated by \n// " . __FILE__ . " script.\nreturn array(\n";
// for dublicates check
$classes = array();
foreach ($this->dirs as $dir) {
@ -65,47 +65,39 @@ class AutoloadBuilder
if (array_key_exists($match[2], $classes)) {
continue;
}
$string = "'{$match[2]}'=>'" . $relative_path . "',\n";
$this->write($string);
$array_string .= "'{$match[2]}'=>'" . $relative_path . "',\n";
$classes[$match[2]] = $file->getRealPath();
}
}
}
}
$this->closeAutoload();
$array_string .= ');';
$this->writeAutoload($array_string);
$this->isFileConsistent();
}
protected function isExcluded($file)
{
foreach ($this->exclude as $dir) {
if (stripos($file, PATH . $dir) === 0) {
return true;
}
}
return false;
}
protected function openAutoload()
protected function writeAutoload($string)
{
$this->write("<?php\n// This file is autogenerated by \n// " . __FILE__ . " script.\nreturn array(\n");
file_put_contents($this->autoload, $string);
}
protected function closeAutoload()
protected function isFileConsistent()
{
if ($this->write(');')) {
fclose($this->handler);
$autoload_array = include($this->autoload);
if(!is_array($autoload_array)) {
unlink($this->autoload);
trigger_error("Error while generating autoload file.", E_USER_ERROR);
}
}
protected function write($string)
protected function isExcluded($file)
{
if (!$this->handler) {
if (!$this->handler = fopen($this->autoload, 'w')) {
trigger_error("{$this->autoload} is not writable", E_USER_ERROR);
foreach ($this->exclude as $dir) {
if (stripos($file, PATH . $dir) === 0) {
return true;
}
}
return (bool) fwrite($this->handler, $string);
return false;
}
protected function rightSubstr($string, $nchars)

Loading…
Cancel
Save