From 51444ec44c184612396bb915901882281e74490d Mon Sep 17 00:00:00 2001 From: Thach Nguyen Date: Fri, 23 Feb 2018 04:55:42 +0700 Subject: [PATCH 1/2] * Make source code compatible with PHP 5.4 * Use PHPUnit mock instead of Mockery * Add more unit-tests to coverage all source code --- README.md | 6 +- composer.json | 5 +- phpunit.xml | 18 ++- .../Laravalid/converter/Base/Converter.php | 2 +- .../converter/JqueryValidation/Rule.php | 2 +- tests/Bllim/Laravalid/FormBuilderTest.php | 47 ++++---- tests/Bllim/Laravalid/ServiceProviderTest.php | 105 ++++++++++++++++++ .../Laravalid/converter/ConverterTest.php | 70 +++++------- .../Bllim/Laravalid/converter/MessageTest.php | 58 ++++------ tests/Bllim/Laravalid/converter/RouteTest.php | 53 ++++----- tests/Bllim/Laravalid/converter/RuleTest.php | 18 +-- 11 files changed, 221 insertions(+), 163 deletions(-) create mode 100644 tests/Bllim/Laravalid/ServiceProviderTest.php diff --git a/README.md b/README.md index bdb1977..b00ea80 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ class UserController extends Controller { if ($validator->fails()) { - // actually withErrors is not really neccessary because we already show errors at client side for normal users + // actually withErrors is not really necessary because we already show errors at client side for normal users return Redirect::back()->withErrors($validator); } @@ -187,7 +187,7 @@ Form::converter()->route()->extend('someotherrule', function($name, $parameters) }); ``` -Second, you can create your own converter (which extends baseconverter or any current plugin converter) in `Bllim\Laravalid\Converter\` namespace and change plugin configuration in config file with your own plugin name. +Second, you can create your own converter (which extends `Base\Converter` or any current plugin converter) in `Bllim\Laravalid\Converter\` namespace and change plugin configuration in config file with your own plugin name. > **Note:** If you are creating a converter for some existed html/js plugin please create it in `converter` folder and send a pull-request. @@ -244,7 +244,7 @@ To use Jquery Validation, change plugin to `JqueryValidation` in config file and ### Contribution You can fork and contribute to development of the package. All pull requests is welcome. -**Convertion Logic** +**Conversion Logic** Package converts rules by using converters (in `src/Bllim/Laravalid/converter`). It uses `Converter` class of chosen plugin which extends `Converter/Base/Converter` class. You can look at existed methods and plugins to understand how it works. Explanation will be ready, soon. diff --git a/composer.json b/composer.json index 17dcc64..080a6c8 100644 --- a/composer.json +++ b/composer.json @@ -10,7 +10,7 @@ } ], "require": { - "php": ">=5.3.0", + "php": ">=5.4.0", "illuminate/config": "~4.2", "illuminate/html": "~4.2", "illuminate/support": "~4.2", @@ -19,8 +19,7 @@ "illuminate/translation": "~4.0" }, "require-dev": { - "phpunit/phpunit": "~4.0", - "mockery/mockery": "~0.9" + "phpunit/phpunit": "~4.0" }, "autoload": { "psr-0": { diff --git a/phpunit.xml b/phpunit.xml index 3347b75..fc765ff 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,5 +1,7 @@ - ./tests/ + + + + ./src/ + + ./vendor/ + + + + + + + diff --git a/src/Bllim/Laravalid/converter/Base/Converter.php b/src/Bllim/Laravalid/converter/Base/Converter.php index ff255d2..942837e 100644 --- a/src/Bllim/Laravalid/converter/Base/Converter.php +++ b/src/Bllim/Laravalid/converter/Base/Converter.php @@ -75,7 +75,7 @@ public function __construct($app) $config = $app['config']; $routeUrl = $app['url']->to($config->get('laravalid::route', 'laravalid')); - $ns = substr(static::class, 0, -9) ?: '\\'; + $ns = substr($class = get_class($this), 0, strrpos($class, '\\')) . '\\'; ($class = $ns . 'Rule') and static::$rule = new $class($routeUrl, $app['encrypter']); ($class = $ns . 'Message') and static::$message = new $class($app['translator']); ($class = $ns . 'Route') and static::$route = new $class($app['validator'], $app['encrypter']); diff --git a/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php b/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php index 0ffcef3..8004901 100644 --- a/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php +++ b/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php @@ -210,7 +210,7 @@ public function mergeOutputAttributes(array $outputAttributes, array &$ruleAttri } } - $outputAttributes += $ruleAttributes; + $outputAttributes = parent::mergeOutputAttributes($outputAttributes, $ruleAttributes, $inputType); // remove duplicated rule attributes if (!empty($inputType) && isset($ruleAttributes[$k = 'data-rule-' . $inputType]) && strcasecmp('true', $ruleAttributes[$k]) == 0) diff --git a/tests/Bllim/Laravalid/FormBuilderTest.php b/tests/Bllim/Laravalid/FormBuilderTest.php index df68a5b..0ca05ed 100644 --- a/tests/Bllim/Laravalid/FormBuilderTest.php +++ b/tests/Bllim/Laravalid/FormBuilderTest.php @@ -4,9 +4,8 @@ class FormBuilderTest extends \PHPUnit_Framework_TestCase { - /** - * @var \Mockery\MockInterface|Converter\Base\Converter + * @var \PHPUnit_Framework_MockObject_MockObject|Converter\Base\Converter */ protected $converter; @@ -19,18 +18,14 @@ protected function setUp() { parent::setUp(); - $app = Converter\ConverterTest::initApplicationMock(); - $this->converter = \Mockery::mock(new Converter\JqueryValidation\Converter($app)); + $app = Converter\ConverterTest::initApplicationMock($this); + $this->converter = ($this->getName(false) == 'testIntegration') + ? new Converter\JqueryValidation\Converter($app) + : $this->getMock(__NAMESPACE__ . '\Converter\Base\Converter', ['set', 'reset', 'convert'], [], '', false); $this->form = new FormBuilder(new HtmlBuilder($url = $app['url']), $url, '_csrf_token', $this->converter); } - protected function tearDown() - { - parent::tearDown(); - \Mockery::close(); - } - /** * @param string $paramValue * @param string $expectedValue @@ -38,9 +33,7 @@ protected function tearDown() */ public function testRawAttributeName($paramValue, $expectedValue) { - $this->converter->shouldReceive('convert')->once()->andReturnUsing(function ($name) { - return $name; - }); + $this->converter->expects($this->once())->method('convert')->willReturnArgument(0); $value = Converter\ConverterTest::invokeMethod($this->form, 'getValidationAttributes', $paramValue); $this->assertEquals($expectedValue, $value); @@ -62,16 +55,16 @@ public function dataForTestRawAttributeName() public function testSetValidation() { - $this->converter->shouldReceive('set')->with(null)->once(); + $this->converter->expects($this->once())->method('set')->with(null); $this->form->setValidation(null); - $this->converter->shouldReceive('reset')->once(); + $this->converter->expects($this->once())->method('reset'); $this->form->resetValidation(); } public function testOpen() { - $this->converter->shouldReceive('set')->with($rules = ['bar'])->once(); + $this->converter->expects($this->once())->method('set')->with($rules = ['bar']); $html = $this->form->open(['url' => '/', 'method' => 'get'], $rules); $this->assertEquals('
', $html); @@ -79,8 +72,8 @@ public function testOpen() public function testModel() { - $this->converter->shouldReceive('set')->with($rules = ['foo' => true])->once(); - $this->converter->shouldReceive('set')->with(null)->once(); + $this->converter->expects($this->exactly(2))->method('set') + ->withConsecutive([$rules = ['foo' => true]], [null]); $html = $this->form->model(new \stdClass(), ['url' => '/', 'method' => 'get'], $rules); @@ -89,22 +82,21 @@ public function testModel() public function testClose() { - $this->converter->shouldReceive('reset')->once(); + $this->converter->expects($this->once())->method('reset'); $this->assertEquals('
', $this->form->close()); } public function testInput() { - $this->converter->shouldReceive('convert')->once()->andReturnUsing(function ($name, $type = null) { - return [$name => $type]; - }); + $this->converter->expects($this->exactly(2))->method('convert') + ->withConsecutive(['foo', 'date'], ['bar', 'url']) + ->willReturnOnConsecutiveCalls(['foo' => 'date'], []); $html = $this->form->input('date', 'foo[]'); $this->assertStringEndsWith('>', $html); $this->assertStringStartsWith('assertContains(' foo="date"', $html); - $this->converter->shouldReceive('convert')->with('bar', 'url')->once()->andReturn([]); $html = $this->form->url('bar[]'); $this->assertStringEndsWith('>', $html); @@ -115,7 +107,7 @@ public function testInput() public function testTextArea() { - $this->converter->shouldReceive('convert')->with('bar', null)->once()->andReturn([]); + $this->converter->expects($this->once())->method('convert')->with('bar', null)->willReturn([]); $html = $this->form->textarea('bar[]'); $this->assertStringEndsWith('>', $html); @@ -125,7 +117,7 @@ public function testTextArea() public function testSelect() { - $this->converter->shouldReceive('convert')->with('bar_foo', null)->once()->andReturn([]); + $this->converter->expects($this->once())->method('convert')->with('bar_foo', null)->willReturn([]); $html = $this->form->select('bar_foo'); $this->assertStringEndsWith('>', $html); @@ -135,7 +127,8 @@ public function testSelect() public function testCheckbox() { - $this->converter->shouldReceive('convert')->with('foo', 'checkbox')->once()->andReturn([]); + $this->converter->expects($this->exactly(2))->method('convert') + ->withConsecutive(['foo', 'checkbox'], ['bar', 'radio'])->willReturn([]); $html = $this->form->checkbox('foo[]'); $this->assertStringEndsWith('>', $html); @@ -143,7 +136,6 @@ public function testCheckbox() $this->assertContains(' name="foo[]"', $html); $this->assertContains(' type="checkbox"', $html); - $this->converter->shouldReceive('convert')->with('bar', 'radio')->once()->andReturn([]); $html = $this->form->radio('bar[]'); $this->assertStringEndsWith('>', $html); @@ -333,5 +325,4 @@ public function testIntegration() $this->assertEquals('', $this->form->close()); $this->assertEquals([], $this->converter->getValidationRules()); } - } diff --git a/tests/Bllim/Laravalid/ServiceProviderTest.php b/tests/Bllim/Laravalid/ServiceProviderTest.php new file mode 100644 index 0000000..6787026 --- /dev/null +++ b/tests/Bllim/Laravalid/ServiceProviderTest.php @@ -0,0 +1,105 @@ +assertAttributeSame(null, 'app', $provider); + $this->assertFalse($provider->isDeferred()); + } + + public function testProvides() + { + $provider = new LaravalidServiceProvider(null); + $this->assertEquals(array('laravalid'), $provider->provides()); + } + + public function testRegister() + { + $app = $this->getMock('Illuminate\Container\Container', array('bound', 'bind', 'make')); + + $app->expects($this->once())->method('bound')->with('html')->willReturn(false); + $app->expects($this->exactly(2))->method('bind') + ->withConsecutive( + array('html', $this->callback(function ($closure) use ($app, &$html) { + $html = $closure($app); + return ($html instanceof HtmlBuilder); + }), $this->isTrue()), + array('laravalid', $this->callback(function ($closure) use ($app) { + $form = $closure($app); + return ($form instanceof FormBuilder); + }), $this->isTrue()) + ); + + $url = $this->getMock('Illuminate\Routing\UrlGenerator', array('to'), array(), '', false); + $config = $this->getMock('Illuminate\Config\Repository', array('get'), array(), '', false); + $session = $this->getMock('Illuminate\Session\Store', array('getToken'), array(), '', false); + + $app->expects($this->atLeast(4))->method('make')->withConsecutive(['url'], ['config'])->willReturnMap(array( + array('url', array(), $url), + array('config', array(), $config), + array('session.store', array(), $session), + array('html', array(), &$html), + )); + + $config->expects($this->once())->method('get')->with('laravalid::plugin')->willReturn('\MyTestPlugin'); + $session->expects($this->once())->method('getToken')->willReturn(uniqid()); + + if (!class_exists('MyTestPlugin\Converter')) + eval('namespace MyTestPlugin { class Converter extends \\' . __NAMESPACE__ . '\Converter\Base\Converter { public function __construct() { echo __CLASS__; } } }'); + + $this->expectOutputString('MyTestPlugin\Converter'); + /** @noinspection PhpParamsInspection */ + $provider = new LaravalidServiceProvider($app); + $provider->register(); + } + + public function testBoot() + { + $app = $this->getMock('Illuminate\Container\Container', array('make')); + + $files = $this->getMock('Illuminate\Filesystem\Filesystem', null); + $config = $this->getMock('Illuminate\Config\Repository', array('get', 'package'), array(), '', false); + $router = $this->getMock('Illuminate\Routing\Router', array('any'), array(), '', false); + $route = $this->getMock('Illuminate\Routing\Route', array('where'), array(), '', false); + + $form = $this->getMock(__NAMESPACE__ . '\FormBuilder', array('converter'), array(), '', false); + $converter = $this->getMock(__NAMESPACE__ . '\Converter\Base\Converter', array('route'), array(), '', false); + $valid = $this->getMock(__NAMESPACE__ . '\Converter\Base\Route', array('convert'), array(), '', false); + $request = $this->getMock('Illuminate\Http\Request', array('all'), array(), '', false); + + $app->expects($this->atLeast(5))->method('make')->withConsecutive(['files'], ['config'])->willReturnMap(array( + array('files', array(), $files), + array('config', array(), $config), + array('router', array(), $router), + array('laravalid', array(), $form), + array('request', array(), $request), + )); + + $path = realpath(__DIR__ . '/../../../src'); + $config->expects($this->once())->method('package')->with('bllim/laravalid', $path . '/config', 'laravalid'); + $config->expects($this->once())->method('get')->with('laravalid::route', 'laravalid')->willReturnArgument(1); + + $router->expects($this->once())->method('any')->willReturnCallback(function ($url, $action) use ($route) { + static::assertEquals('laravalid/{rule}', $url); + static::assertEquals('["exists",[{"params":"~"}]]', $action('exists')); + return $route; + }); + $route->expects($this->once())->method('where')->with('rule', '[\w-]+'); + + $form->expects($this->once())->method('converter')->willReturn($converter); + $converter->expects($this->once())->method('route')->willReturn($valid); + $valid->expects($this->once())->method('convert')->willReturnCallback(function () { + return json_encode(func_get_args()); + }); + $request->expects($this->once())->method('all')->willReturn(array('params' => '~')); + + /** @noinspection PhpParamsInspection */ + $provider = new LaravalidServiceProvider($app); + $provider->boot(); + } +} diff --git a/tests/Bllim/Laravalid/converter/ConverterTest.php b/tests/Bllim/Laravalid/converter/ConverterTest.php index 2ca7db2..025e2ed 100644 --- a/tests/Bllim/Laravalid/converter/ConverterTest.php +++ b/tests/Bllim/Laravalid/converter/ConverterTest.php @@ -1,18 +1,11 @@ shouldReceive('get')->zeroOrMoreTimes()->andReturnUsing(function ($key, $default = null) { + $config = $test->getMock('Illuminate\Config\Repository', ['get'], [], '', false); + $config->expects($test->any())->method('get')->willReturnCallback(function ($key, $default = null) { return isset($default) ? $default : ($key == 'laravalid::plugin' ? 'JqueryValidation' : null); }); - $url = \Mockery::mock(UrlGenerator::class); - $url->shouldReceive('to')->andReturnUsing(function ($path) { + $url = $test->getMock('Illuminate\Routing\UrlGenerator', ['to'], [], '', false); + $url->expects($test->any())->method('to')->willReturnCallback(function ($path) { return '/' . ltrim($path, '/'); }); - /* @var $encrypter \Mockery\MockInterface|Encrypter */ - $encrypter = \Mockery::mock(Encrypter::class); - $encrypter->shouldReceive('encrypt')->andReturnUsing(function ($data) { + $encrypter = $test->getMock('Illuminate\Encryption\Encrypter', ['encrypt'], [], '', false); + $encrypter->expects($test->any())->method('encrypt')->willReturnCallback(function ($data) { return str_replace(['/', '+', '='], ['_', '-', ''], base64_encode($data)); }); - /* @var $loader \Mockery\MockInterface|LoaderInterface */ - $loader = \Mockery::mock(LoaderInterface::class); - $loader->shouldReceive('load')->with('en', 'validation', '*')->andReturn(static::$messages); + $loader = $test->getMock('Illuminate\Translation\LoaderInterface'); + $loader->expects($test->any())->method('load')->with('en', 'validation', '*')->willReturn(static::$messages); // - $translator = \Mockery::mock(new Translator($loader, 'en')); - $translator->shouldReceive('has')->zeroOrMoreTimes()->andReturn(false); + $translator = $test->getMock('Illuminate\Translation\Translator', !$trans ? ['has'] : ['has', 'get'], [$loader, 'en']); + $translator->expects($test->any())->method('has')->willReturn(false); - $mocks = compact('config', 'url', 'encrypter', 'translator'); - /* @var $app \Mockery\MockInterface|Container */ - $app = \Mockery::mock(Container::class);// Illuminate\Foundation\Application - - $app->shouldReceive('make')->andReturnUsing($func = function ($key) use ($mocks) { - return isset($mocks[$key]) ? $mocks[$key] : null; - }); - $app->shouldReceive('offsetGet')->zeroOrMoreTimes()->andReturnUsing($func); + $app = $test->getMock('Illuminate\Container\Container', ['make']);// Illuminate\Foundation\Application + $app->expects($test->any())->method('make')->willReturnMap([ + ['config', [], $config], + ['url', [], $url], + ['encrypter', [], $encrypter], + ['translator', [], $translator], + ]); return $app; } @@ -62,16 +57,10 @@ protected function setUp() { parent::setUp(); - $this->app = $this->initApplicationMock(); + $this->app = $this->initApplicationMock($this, $this->getName(false) == 'testDefaultErrorMessage'); $this->converter = new JqueryValidation\Converter($this->app); } - protected function tearDown() - { - parent::tearDown(); - \Mockery::close(); - } - static function invokeMethod($object, $methodName, $parameters = array()) { $method = new \ReflectionMethod(get_class($object), $methodName); @@ -82,9 +71,9 @@ static function invokeMethod($object, $methodName, $parameters = array()) public function testConstructor() { - $this->assertEquals(JqueryValidation\Rule::class, get_class($this->converter->rule())); - $this->assertEquals(JqueryValidation\Message::class, get_class($this->converter->message())); - $this->assertEquals(JqueryValidation\Route::class, get_class($this->converter->route())); + $this->assertInstanceOf(__NAMESPACE__ . '\JqueryValidation\Rule', $this->converter->rule()); + $this->assertInstanceOf(__NAMESPACE__ . '\JqueryValidation\Message', $this->converter->message()); + $this->assertInstanceOf(__NAMESPACE__ . '\JqueryValidation\Route', $this->converter->route()); $this->assertAttributeEquals($this->converter->rule(), 'rule', $this->converter); $this->assertAttributeEquals($this->converter->message(), 'message', $this->converter); @@ -178,7 +167,7 @@ public function dataForGetTypeOfInput() */ public function testDefaultErrorMessage($params = [], $expected = []) { - $this->app['translator']->shouldReceive('get')->times(2)->andReturnUsing(function ($key, $data = []) { + $this->app['translator']->expects($this->exactly(2))->method('get')->willReturnCallback(function ($key, $data = []) { return $key . (empty($data) ? '' : json_encode($data)); }); @@ -369,5 +358,4 @@ public function dataForTestConvert() ]], ); } - } diff --git a/tests/Bllim/Laravalid/converter/MessageTest.php b/tests/Bllim/Laravalid/converter/MessageTest.php index f8d5f23..df8a688 100644 --- a/tests/Bllim/Laravalid/converter/MessageTest.php +++ b/tests/Bllim/Laravalid/converter/MessageTest.php @@ -1,12 +1,9 @@ translator = \Mockery::mock(Translator::class); + $this->translator = $this->getMock('Illuminate\Translation\Translator', ['has', 'get'], [], '', false); $this->message = new JqueryValidation\Message($this->translator); } - protected function tearDown() - { - parent::tearDown(); - \Mockery::close(); - } - public function testExtend() { $this->assertNull($this->message->convert('foo')); @@ -44,38 +35,28 @@ public function testExtend() public function testGetValidationMessage() { - $this->translator->shouldReceive('has')->once()->andReturn(false); - $this->translator->shouldReceive('get')->with('validation.attributes.first_name')->once()->andReturnUsing(function ($key) { - return $key; - }); - $this->translator->shouldReceive('get') - ->with('validation.active_url', ['other' => 'old_name', 'attribute' => 'first name'])->once() - ->andReturnUsing(function ($key, $data) { - return ($key == 'validation.active_url') ? $data['attribute'] . ' === ' . $data['other'] : $key; - }); + $this->translator->expects($this->exactly(3))->method('has') + ->withConsecutive([$this->anything()], ['validation.custom.lastName.email'], [$this->anything()]) + ->willReturnOnConsecutiveCalls(false, true, false); + // + $this->translator->expects($this->exactly(6))->method('get') + ->withConsecutive( + ['validation.attributes.first_name'], ['validation.active_url', ['other' => 'old_name', 'attribute' => 'first name']], + ['validation.attributes.lastName'], ['validation.custom.lastName.email', ['max' => '100', 'attribute' => 'Last name']], + ['validation.attributes.foo'], ['validation.max.numeric', ['attribute' => 'Bar']] + ) + ->willReturnOnConsecutiveCalls( + 'validation.attributes.first_name', 'first name === old_name', + 'Last name', 'Last name <= 100', + 'Bar', 'validation.max.numeric' + ); $value = $this->message->getValidationMessage('first_name', 'activeUrl', ['other' => 'old_name']); $this->assertEquals('first name === old_name', $value); - // - $this->translator->shouldReceive('has')->with('validation.custom.lastName.email')->once()->andReturn(true); - $this->translator->shouldReceive('get')->with('validation.attributes.lastName')->once()->andReturn('Last name'); - $this->translator->shouldReceive('get') - ->with('validation.custom.lastName.email', ['max' => '100', 'attribute' => 'Last name'])->once() - ->andReturnUsing(function ($key, $data) { - return ($key == 'validation.custom.lastName.email') ? $data['attribute'] . ' <= ' . $data['max'] : $key; - }); - $value = $this->message->getValidationMessage('lastName', 'email', ['max' => '100']); $this->assertEquals('Last name <= 100', $value); - // - $this->translator->shouldReceive('has')->once()->andReturn(false); - $this->translator->shouldReceive('get')->with('validation.attributes.foo')->once()->andReturn('Bar'); - $this->translator->shouldReceive('get')->with('validation.max.numeric', ['attribute' => 'Bar'])->once()->andReturnUsing(function ($key) { - return $key; - }); - $value = $this->message->getValidationMessage('foo', 'max', [], 'numeric'); $this->assertEquals('validation.max.numeric', $value); } @@ -88,8 +69,8 @@ public function testGetValidationMessage() */ public function testAllRules($name = '', $params = [], $expected = []) { - $this->translator->shouldReceive('has')->times(2)->andReturn(preg_match('/^[A-Z]/', $name)); - $this->translator->shouldReceive('get')->atLeast()->times(4)->andReturnUsing(function ($key, $data = null) { + $this->translator->expects($this->exactly(2))->method('has')->willReturn(preg_match('/^[A-Z]/', $name)); + $this->translator->expects($this->atLeast(4))->method('get')->willReturnCallback(function ($key, $data = null) { return $key . (empty($data) ? '' : json_encode($data)); }); @@ -147,5 +128,4 @@ public function dataForTestAllRules() ['active_Url', [['name' => 'ActiveUrl', 'parameters' => ['anon']], 'barFoo'], ['data-msg-remote' => 'validation.active_url{"attribute":"bar foo"}']], ); } - } diff --git a/tests/Bllim/Laravalid/converter/RouteTest.php b/tests/Bllim/Laravalid/converter/RouteTest.php index 7be3da3..821d0e0 100644 --- a/tests/Bllim/Laravalid/converter/RouteTest.php +++ b/tests/Bllim/Laravalid/converter/RouteTest.php @@ -1,21 +1,16 @@ validator = \Mockery::mock(Factory::class); - $this->encrypter = \Mockery::mock(Encrypter::class); + $this->validator = $this->getMock('Illuminate\Validation\Factory', ['make'], [], '', false); + $this->encrypter = $this->getMock('Illuminate\Encryption\Encrypter', ['decrypt'], [], '', false); $this->route = new JqueryValidation\Route($this->validator, $this->encrypter); } - protected function tearDown() - { - parent::tearDown(); - \Mockery::close(); - } - public function testActiveUrl() { - $this->validator->shouldReceive('make')->with(['Bar' => 'foo'], ['Bar' => ['active_url']])->once() - ->andReturn($validator = \Mockery::mock(Validator::class)); - $validator->shouldReceive('fails')->once()->andReturn(true); - $validator->shouldReceive('messages')->once()->andReturn(new MessageBag(['Bar' => $msg = 'Inactive URL'])); + $validator = $this->getMock('Illuminate\Validation\Validator', ['fails', 'messages'], [], '', false); + $this->validator->expects($this->once())->method('make') + ->with(['Bar' => 'foo'], ['Bar' => ['active_url']])->willReturn($validator); + $validator->expects($this->once())->method('fails')->willReturn(true); + $validator->expects($this->once())->method('messages')->willReturn(new MessageBag(['Bar' => $msg = 'Inactive URL'])); $response = $this->route->convert('active_url', [['Bar' => 'foo', '_' => time()]]); - $this->assertEquals(JsonResponse::class, get_class($response)); + $this->assertInstanceOf('Illuminate\Http\JsonResponse', $response); $this->assertEquals($msg, $response->getData()); } public function testExists() { - $this->encrypter->shouldReceive('decrypt')->once()->andReturnUsing(function ($data) { + $this->encrypter->expects($this->once())->method('decrypt')->willReturnCallback(function ($data) { return substr($data, 1); }); - $this->validator->shouldReceive('make')->with(['foo' => 'Bar'], ['foo' => ['exists:Tbl,field,ID']])->once() - ->andReturn($validator = \Mockery::mock(Validator::class)); - $validator->shouldReceive('fails')->once()->andReturn(false); + $validator = $this->getMock('Illuminate\Validation\Validator', ['fails'], [], '', false); + $this->validator->expects($this->once())->method('make') + ->with(['foo' => 'Bar'], ['foo' => ['exists:Tbl,field,ID']])->willReturn($validator); + $validator->expects($this->once())->method('fails')->willReturn(false); $response = $this->route->convert('exists', [['foo' => 'Bar', 'params' => '~Tbl,field,ID', '_' => time()]]); - $this->assertEquals(JsonResponse::class, get_class($response)); + $this->assertInstanceOf('Illuminate\Http\JsonResponse', $response); $this->assertTrue($response->getData()); } public function testUnique() { - $this->encrypter->shouldReceive('decrypt')->times(2)->andReturnUsing(function ($data) { + $this->encrypter->expects($this->exactly(2))->method('decrypt')->willReturnCallback(function ($data) { return empty($data) ? $data : substr($data, 1); }); - $this->validator->shouldReceive('make')->with(['Foo' => 'Bar'], ['Foo' => ['unique:Tbl,field,Id,#Bar', 'active_url:anon']])->once() - ->andReturn($validator = \Mockery::mock(Validator::class)); - $validator->shouldReceive('fails')->once()->andReturn(false); + $validator = $this->getMock('Illuminate\Validation\Validator', ['fails'], [], '', false); + $this->validator->expects($this->once())->method('make') + ->with(['Foo' => 'Bar'], ['Foo' => ['unique:Tbl,field,Id,#Bar', 'active_url:anon']])->willReturn($validator); + $validator->expects($this->once())->method('fails')->willReturn(false); $response = $this->route->convert('unique-active_url', [['Foo' => 'Bar', 'params' => ['~Tbl,field,Id,#Bar', '+anon'], '_' => time()]]); - $this->assertEquals(JsonResponse::class, get_class($response)); + $this->assertInstanceOf('Illuminate\Http\JsonResponse', $response); $this->assertTrue($response->getData()); } @@ -88,5 +80,4 @@ public function testExtend() }); $this->assertEquals($params = ['foo' => '?', 'params' => '~'], $this->route->convert('Unique', [$params])); } - } diff --git a/tests/Bllim/Laravalid/converter/RuleTest.php b/tests/Bllim/Laravalid/converter/RuleTest.php index b551e96..b91239c 100644 --- a/tests/Bllim/Laravalid/converter/RuleTest.php +++ b/tests/Bllim/Laravalid/converter/RuleTest.php @@ -1,12 +1,9 @@ encrypter = \Mockery::mock(Encrypter::class); + $this->encrypter = $this->getMock('Illuminate\Encryption\Encrypter', ['encrypt'], [], '', false); $this->rule = new JqueryValidation\Rule(static::routeUrl(), $this->encrypter); } - protected function tearDown() - { - parent::tearDown(); - \Mockery::close(); - } - protected static function routeUrl() { static $url; if (!isset($url)) - $url = ['http://localhost:8000/laravalid', '/laravalid'][mt_rand(0, 1)]; + $url = array_rand(array_flip(['http://localhost:8000/laravalid', '/laravalid'])); return $url; } @@ -117,7 +108,7 @@ public function dataForTestGenericRules() */ public function testRemoteRules($name = '', $params = [], $expected = []) { - $this->encrypter->shouldReceive('encrypt')->andReturnUsing(function ($data) { + $this->encrypter->expects($this->any())->method('encrypt')->willReturnCallback(function ($data) { return '~' . $data; }); $value = call_user_func_array([$this->rule, strtolower($name)], $params); @@ -207,5 +198,4 @@ public function dataForMergeOutputAttributes() ], ); } - } From c7473787ecb7b422696ac203da155e58a499b767 Mon Sep 17 00:00:00 2001 From: Thach Nguyen Date: Sat, 24 Feb 2018 04:59:26 +0700 Subject: [PATCH 2/2] Make source code compatible with PHP 5.3 / Laravel 4.0 --- .travis.yml | 15 +- composer.json | 8 +- src/Bllim/Laravalid/FormBuilder.php | 6 +- .../Laravalid/LaravalidServiceProvider.php | 10 +- .../Laravalid/converter/Base/Container.php | 6 +- .../Laravalid/converter/Base/Converter.php | 22 +-- .../Laravalid/converter/Base/Message.php | 4 +- src/Bllim/Laravalid/converter/Base/Route.php | 8 +- .../converter/JqueryValidation/Message.php | 48 ++--- .../converter/JqueryValidation/Rule.php | 52 ++--- src/config/config.php | 4 +- tests/Bllim/Laravalid/FormBuilderTest.php | 58 +++--- tests/Bllim/Laravalid/ServiceProviderTest.php | 29 ++- .../Laravalid/converter/ConverterTest.php | 184 +++++++++--------- .../Bllim/Laravalid/converter/MessageTest.php | 92 ++++----- tests/Bllim/Laravalid/converter/RouteTest.php | 34 ++-- tests/Bllim/Laravalid/converter/RuleTest.php | 176 ++++++++--------- 17 files changed, 386 insertions(+), 370 deletions(-) diff --git a/.travis.yml b/.travis.yml index f60bbe0..cb469fc 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,8 +6,21 @@ php: - 5.6 - hhvm +matrix: + include: + - php: 5.3 + dist: precise + allow_failures: + - php: hhvm + fast_finish: true + +cache: + directories: + - vendor + - $HOME/.composer/cache + before_script: - travis_retry composer self-update - - travis_retry composer install --prefer-source --no-interaction --dev + - travis_retry composer install --no-interaction --no-progress script: phpunit diff --git a/composer.json b/composer.json index 080a6c8..ac82e0d 100644 --- a/composer.json +++ b/composer.json @@ -10,10 +10,10 @@ } ], "require": { - "php": ">=5.4.0", - "illuminate/config": "~4.2", - "illuminate/html": "~4.2", - "illuminate/support": "~4.2", + "php": ">=5.3.0", + "illuminate/config": "~4.0", + "illuminate/html": "~4.0", + "illuminate/support": "~4.0", "illuminate/validation": "~4.0", "illuminate/routing": "~4.0", "illuminate/translation": "~4.0" diff --git a/src/Bllim/Laravalid/FormBuilder.php b/src/Bllim/Laravalid/FormBuilder.php index da82b30..019ea71 100644 --- a/src/Bllim/Laravalid/FormBuilder.php +++ b/src/Bllim/Laravalid/FormBuilder.php @@ -88,7 +88,7 @@ public function model($model, array $options = array(), $rules = null) /** * {@inheritdoc} */ - public function input($type, $name, $value = null, $options = []) + public function input($type, $name, $value = null, $options = array()) { $options += $this->getValidationAttributes($name, $type); return parent::input($type, $name, $value, $options); @@ -97,7 +97,7 @@ public function input($type, $name, $value = null, $options = []) /** * {@inheritdoc} */ - public function textarea($name, $value = null, $options = []) + public function textarea($name, $value = null, $options = array()) { $options += $this->getValidationAttributes($name); return parent::textarea($name, $value, $options); @@ -106,7 +106,7 @@ public function textarea($name, $value = null, $options = []) /** * {@inheritdoc} */ - public function select($name, $list = [], $selected = null, $options = []) + public function select($name, $list = array(), $selected = null, $options = array()) { $options += $this->getValidationAttributes($name); return parent::select($name, $list, $selected, $options); diff --git a/src/Bllim/Laravalid/LaravalidServiceProvider.php b/src/Bllim/Laravalid/LaravalidServiceProvider.php index 709a65c..aed4555 100644 --- a/src/Bllim/Laravalid/LaravalidServiceProvider.php +++ b/src/Bllim/Laravalid/LaravalidServiceProvider.php @@ -24,7 +24,7 @@ public function boot() $routeName = $app['config']->get('laravalid::route', 'laravalid'); $app['router']->any($routeName . '/{rule}', function ($rule) use ($app) { - return $app['laravalid']->converter()->route()->convert($rule, [$app['request']->all()]); + return $app['laravalid']->converter()->route()->convert($rule, array($app['request']->all())); })->where('rule', '[\w-]+'); } @@ -35,14 +35,14 @@ public function register() { // try to register the HTML builder instance if (!$this->app->bound('html')) { - $this->app->bindShared('html', function($app) + $this->app->singleton('html', $this->app->share(function($app) { return new \Illuminate\Html\HtmlBuilder($app['url']); - }); + })); } // register the new form builder instance - $this->app->bindShared('laravalid', function ($app) { + $this->app->singleton('laravalid', $this->app->share(function ($app) { /* @var $app \Illuminate\Container\Container */ $plugin = $app['config']->get('laravalid::plugin'); $converterClass = (strpos($plugin, '\\') === false ? 'Bllim\Laravalid\Converter\\' : '') . $plugin . '\Converter'; @@ -52,7 +52,7 @@ public function register() $form = new FormBuilder($app['html'], $app['url'], $session->getToken(), new $converterClass($app)); return $form->setSessionStore($session); - }); + })); } /** diff --git a/src/Bllim/Laravalid/converter/Base/Container.php b/src/Bllim/Laravalid/converter/Base/Container.php index 098f006..92211bf 100644 --- a/src/Bllim/Laravalid/converter/Base/Container.php +++ b/src/Bllim/Laravalid/converter/Base/Container.php @@ -11,9 +11,9 @@ abstract class Container { - protected $customMethods = []; + protected $customMethods = array(); - public function convert($name, $parameters = []) + public function convert($name, $parameters = array()) { $methodName = strtolower($name); @@ -24,7 +24,7 @@ public function convert($name, $parameters = []) if (method_exists($this, $methodName)) { - return call_user_func_array([$this, $methodName], $parameters); + return call_user_func_array(array($this, $methodName), $parameters); } return null; diff --git a/src/Bllim/Laravalid/converter/Base/Converter.php b/src/Bllim/Laravalid/converter/Base/Converter.php index 942837e..eedcc92 100644 --- a/src/Bllim/Laravalid/converter/Base/Converter.php +++ b/src/Bllim/Laravalid/converter/Base/Converter.php @@ -37,29 +37,29 @@ abstract class Converter { * * @var array */ - protected $validationRules = []; + protected $validationRules = array(); - protected static $multiParamRules = [ + protected static $multiParamRules = array( 'between', 'digits_between', 'in', 'not_in', 'mimes', 'required_if', 'required_with', 'required_with_all', 'required_without', 'required_without_all', 'exists', 'unique', - ]; + ); /** * Rules which specify input type is file * * @var array */ - protected static $fileRules = ['image', 'mimes']; + protected static $fileRules = array('image', 'mimes'); /** * Rules which specify input type is numeric * * @var array */ - protected static $numericRules = ['integer', 'numeric', 'digits', 'digits_between']; + protected static $numericRules = array('integer', 'numeric', 'digits', 'digits_between'); /** * @var bool @@ -114,7 +114,7 @@ public function set($rules) */ public function reset() { - $this->validationRules = []; + $this->validationRules = array(); } /** @@ -154,18 +154,18 @@ protected function checkValidationRule($inputName) public function convert($inputName, $inputType = null) { if (!$this->checkValidationRule($inputName)) { - return []; + return array(); } $rules = $this->getValidationRule($inputName); $type = $this->getTypeOfInput($rules); - $outputAttributes = []; + $outputAttributes = array(); foreach ($rules as $rule) { $parsedRule = $this->parseValidationRule($rule); - $ruleAttributes = $this->rule()->convert($parsedRule['name'], [$parsedRule, $inputName, $type]); + $ruleAttributes = $this->rule()->convert($parsedRule['name'], array($parsedRule, $inputName, $type)); if (!empty($ruleAttributes)) { $outputAttributes = $this->rule()->mergeOutputAttributes($outputAttributes, $ruleAttributes, $inputType); @@ -174,7 +174,7 @@ public function convert($inputName, $inputType = null) if ($this->useLaravelMessages) { - $messageAttributes = $this->message()->convert($parsedRule['name'], [$parsedRule, $inputName, $type]); + $messageAttributes = $this->message()->convert($parsedRule['name'], array($parsedRule, $inputName, $type)); // if empty message attributes if (empty($messageAttributes) && !empty($ruleAttributes)) @@ -251,7 +251,7 @@ protected function getDefaultErrorMessage($laravelRule, $attribute) { // getting user friendly validation message $message = $this->message()->getValidationMessage($attribute, $laravelRule); - return ['data-msg-' . $laravelRule => $message]; + return array('data-msg-' . $laravelRule => $message); } } \ No newline at end of file diff --git a/src/Bllim/Laravalid/converter/Base/Message.php b/src/Bllim/Laravalid/converter/Base/Message.php index a1fc457..c1cc6dd 100644 --- a/src/Bllim/Laravalid/converter/Base/Message.php +++ b/src/Bllim/Laravalid/converter/Base/Message.php @@ -34,7 +34,7 @@ public function __construct($translator) * @return string * @see Illuminate\Validation\Validator::getMessage() */ - public function getValidationMessage($attribute, $rule, $data = [], $type = null) + public function getValidationMessage($attribute, $rule, $data = array(), $type = null) { $path = Str::snake($rule); if ($type !== null) @@ -49,7 +49,7 @@ public function getValidationMessage($attribute, $rule, $data = [], $type = null $niceName = $this->getValidationAttribute($attribute); - return $this->translator->get('validation.' . $path, $data + ['attribute' => $niceName]); + return $this->translator->get('validation.' . $path, $data + array('attribute' => $niceName)); } protected function getValidationAttribute($attribute) diff --git a/src/Bllim/Laravalid/converter/Base/Route.php b/src/Bllim/Laravalid/converter/Base/Route.php index a204753..05b3d2b 100644 --- a/src/Bllim/Laravalid/converter/Base/Route.php +++ b/src/Bllim/Laravalid/converter/Base/Route.php @@ -30,15 +30,15 @@ public function __construct($validatorFactory, $encrypter) $this->encrypter = $encrypter; } - public function convert($name, $parameters = []) + public function convert($name, $parameters = array()) { if (!is_null($result = parent::convert($name, $parameters))) return $result; - return $this->defaultRoute($name, reset($parameters) ?: []); + return $this->defaultRoute($name, reset($parameters) ?: array()); } - protected function defaultRoute($name, $parameters = []) + protected function defaultRoute($name, $parameters = array()) { $params = $this->decryptParameters($parameters); @@ -60,7 +60,7 @@ protected function defaultRoute($name, $parameters = []) protected function decryptParameters(array &$parameters) { - $params = empty($parameters['params']) ? [] + $params = empty($parameters['params']) ? array() : (is_array($parameters['params']) ? $parameters['params'] : array($parameters['params'])); unset($parameters['params'], $parameters['_']); diff --git a/src/Bllim/Laravalid/converter/JqueryValidation/Message.php b/src/Bllim/Laravalid/converter/JqueryValidation/Message.php index c84cc2e..f6c8d93 100644 --- a/src/Bllim/Laravalid/converter/JqueryValidation/Message.php +++ b/src/Bllim/Laravalid/converter/JqueryValidation/Message.php @@ -5,21 +5,21 @@ class Message extends \Bllim\Laravalid\Converter\Base\Message { public function ip($parsedRule, $attribute) { $message = $this->getValidationMessage($attribute, $parsedRule['name']); - return ['data-msg-ipv4' => $message]; + return array('data-msg-ipv4' => $message); } public function same($parsedRule, $attribute) { $other = $this->getValidationAttribute(reset($parsedRule['parameters'])); $message = $this->getValidationMessage($attribute, $parsedRule['name'], compact('other')); - return ['data-msg-equalto' => $message]; + return array('data-msg-equalto' => $message); } public function different($parsedRule, $attribute) { $other = $this->getValidationAttribute(reset($parsedRule['parameters'])); $message = $this->getValidationMessage($attribute, $parsedRule['name'], compact('other')); - return ['data-msg-notequalto' => $message]; + return array('data-msg-notequalto' => $message); } public function alpha($parsedRule, $attribute) @@ -35,71 +35,71 @@ public function alpha_num($parsedRule, $attribute) public function regex($parsedRule, $attribute) { $message = $this->getValidationMessage($attribute, $parsedRule['name']); - return ['data-msg-pattern' => $message]; + return array('data-msg-pattern' => $message); } public function image($parsedRule, $attribute) { $message = $this->getValidationMessage($attribute, $parsedRule['name']); - return ['data-msg-accept' => $message]; + return array('data-msg-accept' => $message); } public function before($parsedRule, $attribute) { - $message = $this->getValidationMessage($attribute, $parsedRule['name'], ['date' => '{0}']); - return ['data-msg-max' => $message]; + $message = $this->getValidationMessage($attribute, $parsedRule['name'], array('date' => '{0}')); + return array('data-msg-max' => $message); } public function after($parsedRule, $attribute) { - $message = $this->getValidationMessage($attribute, $parsedRule['name'], ['date' => '{0}']); - return ['data-msg-min' => $message]; + $message = $this->getValidationMessage($attribute, $parsedRule['name'], array('date' => '{0}')); + return array('data-msg-min' => $message); } public function numeric($parsedRule, $attribute) { $message = $this->getValidationMessage($attribute, $parsedRule['name']); - return ['data-msg-number' => $message]; + return array('data-msg-number' => $message); } public function max($parsedRule, $attribute, $type) { - $message = $this->getValidationMessage($attribute, $parsedRule['name'], ['max' => '{0}'], $type); + $message = $this->getValidationMessage($attribute, $parsedRule['name'], array('max' => '{0}'), $type); switch ($type) { case 'numeric': - return ['data-msg-max' => $message]; + return array('data-msg-max' => $message); break; default: - return ['data-msg-maxlength' => $message]; + return array('data-msg-maxlength' => $message); break; } } public function min($parsedRule, $attribute, $type) { - $message = $this->getValidationMessage($attribute, $parsedRule['name'], ['min' => '{0}'], $type); + $message = $this->getValidationMessage($attribute, $parsedRule['name'], array('min' => '{0}'), $type); switch ($type) { case 'numeric': - return ['data-msg-min' => $message]; + return array('data-msg-min' => $message); break; default: - return ['data-msg-minlength' => $message]; + return array('data-msg-minlength' => $message); break; } } public function between($parsedRule, $attribute, $type) { - $message = $this->getValidationMessage($attribute, $parsedRule['name'], ['min' => '{0}', 'max' => '{1}'], $type); + $message = $this->getValidationMessage($attribute, $parsedRule['name'], array('min' => '{0}', 'max' => '{1}'), $type); switch ($type) { case 'numeric': - return ['data-msg-range' => $message]; + return array('data-msg-range' => $message); break; default: - return ['data-msg-rangelength' => $message/*, 'data-msg-maxlength' => $message*/]; + return array('data-msg-rangelength' => $message/*, 'data-msg-maxlength' => $message*/); break; } } @@ -107,7 +107,7 @@ public function between($parsedRule, $attribute, $type) public function unique($parsedRule, $attribute) { $message = $this->getValidationMessage($attribute, $parsedRule['name']); - return ['data-msg-remote' => $message]; + return array('data-msg-remote' => $message); } public function exists($parsedRule, $attribute) @@ -117,9 +117,9 @@ public function exists($parsedRule, $attribute) public function required_with($parsedRule, $attribute) { - $values = implode(', ', array_map([$this, 'getValidationAttribute'], $parsedRule['parameters'])); + $values = implode(', ', array_map(array($this, 'getValidationAttribute'), $parsedRule['parameters'])); $message = $this->getValidationMessage($attribute, $parsedRule['name'], compact('values')); - return ['data-msg-required' => $message]; + return array('data-msg-required' => $message); } public function required_without($parsedRule, $attribute) @@ -134,8 +134,8 @@ public function active_url($parsedRule, $attribute) public function mimes($parsedRule, $attribute) { - $message = $this->getValidationMessage($attribute, $parsedRule['name'], ['values' => implode(', ', $parsedRule['parameters'])]); - return ['data-msg-accept' => $message]; + $message = $this->getValidationMessage($attribute, $parsedRule['name'], array('values' => implode(', ', $parsedRule['parameters']))); + return array('data-msg-accept' => $message); } } diff --git a/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php b/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php index 8004901..d1a5de4 100644 --- a/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php +++ b/src/Bllim/Laravalid/converter/JqueryValidation/Rule.php @@ -4,44 +4,44 @@ class Rule extends \Bllim\Laravalid\Converter\Base\Rule { public function email() { - return ['data-rule-email' => 'true']; + return array('data-rule-email' => 'true'); } public function required() { - return ['required' => 'required']; + return array('required' => 'required'); } public function url() { - return ['data-rule-url' => 'true']; + return array('data-rule-url' => 'true'); } public function integer() { - return ['data-rule-integer' => 'true']; + return array('data-rule-integer' => 'true'); } public function numeric() { - return ['data-rule-number' => 'true']; + return array('data-rule-number' => 'true'); } public function ip() { - return ['data-rule-ipv4' => 'true']; + return array('data-rule-ipv4' => 'true'); } public function same($parsedRule) { $value = vsprintf(':input[name=\'%1$s\']', $parsedRule['parameters']); - return ['data-rule-equalto' => $value]; + return array('data-rule-equalto' => $value); } public function different($parsedRule) { $value = vsprintf(':input[name=\'%1$s\']', $parsedRule['parameters']); - return ['data-rule-notequalto' => $value]; + return array('data-rule-notequalto' => $value); } public function regex($parsedRule) @@ -52,37 +52,37 @@ public function regex($parsedRule) $rule = substr($rule, 1, -1); } - return ['pattern' => $rule]; + return array('pattern' => $rule); } public function alpha() { - return ['pattern' => '^[A-Za-z_.-]+$']; + return array('pattern' => '^[A-Za-z_.-]+$'); } public function alpha_num() { - return ['pattern' => '^[A-Za-z0-9_.-]+$']; + return array('pattern' => '^[A-Za-z0-9_.-]+$'); } public function image() { - return ['accept' => 'image/*']; + return array('accept' => 'image/*'); } public function date() { - return ['data-rule-date' => 'true']; + return array('data-rule-date' => 'true'); } public function before($parsedRule) { - return ['max' => reset($parsedRule['parameters'])]; + return array('max' => reset($parsedRule['parameters'])); } public function after($parsedRule) { - return ['min' => reset($parsedRule['parameters'])]; + return array('min' => reset($parsedRule['parameters'])); } /** @@ -98,11 +98,11 @@ public function min($parsedRule, $attribute, $type) switch ($type) { case 'numeric': - return ['min' => reset($parsedRule['parameters'])]; + return array('min' => reset($parsedRule['parameters'])); break; default: - return ['minlength' => reset($parsedRule['parameters'])]; + return array('minlength' => reset($parsedRule['parameters'])); break; } } @@ -112,11 +112,11 @@ public function max($parsedRule, $attribute, $type) switch ($type) { case 'numeric': - return ['max' => reset($parsedRule['parameters'])]; + return array('max' => reset($parsedRule['parameters'])); break; default: - return ['maxlength' => reset($parsedRule['parameters'])]; + return array('maxlength' => reset($parsedRule['parameters'])); break; } } @@ -126,11 +126,11 @@ public function between($parsedRule, $attribute, $type) switch ($type) { case 'numeric': - return ['data-rule-range' => vsprintf('%1$s,%2$s', $parsedRule['parameters'])]; + return array('data-rule-range' => vsprintf('%1$s,%2$s', $parsedRule['parameters'])); break; default: - return ['data-rule-rangelength' => vsprintf('%1$s,%2$s', $parsedRule['parameters']), 'maxlength' => vsprintf('%2$s', $parsedRule['parameters'])]; + return array('data-rule-rangelength' => vsprintf('%1$s,%2$s', $parsedRule['parameters']), 'maxlength' => vsprintf('%2$s', $parsedRule['parameters'])); break; } } @@ -140,7 +140,7 @@ protected function remote($method, $parsedRule) $param = implode(',', $parsedRule['parameters']); $encryptedParam = empty($param) ? '' : $this->encrypter->encrypt($param); - return ['data-rule-remote' => $this->routeUrl . '/' . $method . '?params=' . $encryptedParam]; + return array('data-rule-remote' => $this->routeUrl . '/' . $method . '?params=' . $encryptedParam); } public function unique($parsedRule) @@ -160,7 +160,7 @@ public function required_with($parsedRule) . '\']:not(:checkbox):not(:radio):filled,input:enabled[name=\'' . implode('\']:checked,input:enabled[name=\'', $parsedRule['parameters']) . '\']:checked'; - return ['data-rule-required' => $value]; + return array('data-rule-required' => $value); } public function required_without($parsedRule) @@ -170,7 +170,7 @@ public function required_without($parsedRule) . '\']:not(:checkbox):not(:radio):blank,input:enabled[name=\'' . implode('\']:unchecked,input:enabled[name=\'', $parsedRule['parameters']) . '\']:unchecked'; - return ['data-rule-required' => $value]; + return array('data-rule-required' => $value); } public function active_url($parsedRule) @@ -181,7 +181,7 @@ public function active_url($parsedRule) public function mimes($parsedRule) { // TODO: detect mime-type from extensions then sort and group by - return ['accept' => '.' . implode(',.', $parsedRule['parameters'])]; + return array('accept' => '.' . implode(',.', $parsedRule['parameters'])); } public function mergeOutputAttributes(array $outputAttributes, array &$ruleAttributes, $inputType = null) @@ -205,7 +205,7 @@ public function mergeOutputAttributes(array $outputAttributes, array &$ruleAttri if (isset($mRule['data'])) $rule['data'] = isset($rule['data']) ? ($rule['data'] + $mRule['data']) : $mRule['data']; - $outputAttributes['data-rule-remote'] = empty($rule['data']) ? $rule['url'] : json_encode($rule, JSON_UNESCAPED_SLASHES); + $outputAttributes['data-rule-remote'] = empty($rule['data']) ? $rule['url'] : str_replace('\/', '/', json_encode($rule)); unset($outputAttributes['data-msg-remote'], $ruleAttributes['data-rule-remote']); } } diff --git a/src/config/config.php b/src/config/config.php index 22fd887..54f26ed 100644 --- a/src/config/config.php +++ b/src/config/config.php @@ -1,7 +1,7 @@ true, 'plugin' => 'JqueryValidation', 'route' => 'laravalid' -]; \ No newline at end of file +); \ No newline at end of file diff --git a/tests/Bllim/Laravalid/FormBuilderTest.php b/tests/Bllim/Laravalid/FormBuilderTest.php index 0ca05ed..0ac68df 100644 --- a/tests/Bllim/Laravalid/FormBuilderTest.php +++ b/tests/Bllim/Laravalid/FormBuilderTest.php @@ -21,9 +21,13 @@ protected function setUp() $app = Converter\ConverterTest::initApplicationMock($this); $this->converter = ($this->getName(false) == 'testIntegration') ? new Converter\JqueryValidation\Converter($app) - : $this->getMock(__NAMESPACE__ . '\Converter\Base\Converter', ['set', 'reset', 'convert'], [], '', false); + : $this->getMock(__NAMESPACE__ . '\Converter\Base\Converter', array('set', 'reset', 'convert'), array(), '', false); $this->form = new FormBuilder(new HtmlBuilder($url = $app['url']), $url, '_csrf_token', $this->converter); + + $session = $this->getMock('Illuminate\Session\Store', array('get'), array(), '', false); + $this->form->setSessionStore($session); + $session->expects($this->any())->method('get')->willReturnArgument(1); } /** @@ -45,11 +49,11 @@ public function testRawAttributeName($paramValue, $expectedValue) public function dataForTestRawAttributeName() { return array( - ['Bar', 'Bar'], - ['bar_Foo[]', 'bar_Foo'], - ['Foo[][1]', 'Foo'], - ['foo[1][]', 'foo'], - ['Foo[Bar][0]', 'Foo'], + array('Bar', 'Bar'), + array('bar_Foo[]', 'bar_Foo'), + array('Foo[][1]', 'Foo'), + array('foo[1][]', 'foo'), + array('Foo[Bar][0]', 'Foo'), ); } @@ -64,8 +68,8 @@ public function testSetValidation() public function testOpen() { - $this->converter->expects($this->once())->method('set')->with($rules = ['bar']); - $html = $this->form->open(['url' => '/', 'method' => 'get'], $rules); + $this->converter->expects($this->once())->method('set')->with($rules = array('bar')); + $html = $this->form->open(array('url' => '/', 'method' => 'get'), $rules); $this->assertEquals('
', $html); } @@ -73,9 +77,9 @@ public function testOpen() public function testModel() { $this->converter->expects($this->exactly(2))->method('set') - ->withConsecutive([$rules = ['foo' => true]], [null]); + ->withConsecutive(array($rules = array('foo' => true)), array(null)); - $html = $this->form->model(new \stdClass(), ['url' => '/', 'method' => 'get'], $rules); + $html = $this->form->model(new \stdClass(), array('url' => '/', 'method' => 'get'), $rules); $this->assertEquals('', $html); } @@ -89,8 +93,8 @@ public function testClose() public function testInput() { $this->converter->expects($this->exactly(2))->method('convert') - ->withConsecutive(['foo', 'date'], ['bar', 'url']) - ->willReturnOnConsecutiveCalls(['foo' => 'date'], []); + ->withConsecutive(array('foo', 'date'), array('bar', 'url')) + ->willReturnOnConsecutiveCalls(array('foo' => 'date'), array()); $html = $this->form->input('date', 'foo[]'); $this->assertStringEndsWith('>', $html); @@ -107,7 +111,7 @@ public function testInput() public function testTextArea() { - $this->converter->expects($this->once())->method('convert')->with('bar', null)->willReturn([]); + $this->converter->expects($this->once())->method('convert')->with('bar', null)->willReturn(array()); $html = $this->form->textarea('bar[]'); $this->assertStringEndsWith('>', $html); @@ -117,7 +121,7 @@ public function testTextArea() public function testSelect() { - $this->converter->expects($this->once())->method('convert')->with('bar_foo', null)->willReturn([]); + $this->converter->expects($this->once())->method('convert')->with('bar_foo', null)->willReturn(array()); $html = $this->form->select('bar_foo'); $this->assertStringEndsWith('>', $html); @@ -128,7 +132,7 @@ public function testSelect() public function testCheckbox() { $this->converter->expects($this->exactly(2))->method('convert') - ->withConsecutive(['foo', 'checkbox'], ['bar', 'radio'])->willReturn([]); + ->withConsecutive(array('foo', 'checkbox'), array('bar', 'radio'))->willReturn(array()); $html = $this->form->checkbox('foo[]'); $this->assertStringEndsWith('>', $html); @@ -145,12 +149,12 @@ public function testCheckbox() } static $validationRules = array( - 'uid' => ['required', 'min:3', 'max:30', 'alpha_num', 'exists:users,uid'], + 'uid' => array('required', 'min:3', 'max:30', 'alpha_num', 'exists:users,uid'), 'email' => 'required|max:255|email|unique:users,email', - 'url' => ['required', 'max:255', 'url', 'unique:users,url', 'active_url'], + 'url' => array('required', 'max:255', 'url', 'unique:users,url', 'active_url'), 'name' => 'max:255|alpha', // - 'pwd' => ['min:6', 'max:15', 'regex:/^[0-9]+[xX][0-9]+$/'], + 'pwd' => array('min:6', 'max:15', 'regex:/^[0-9]+[xX][0-9]+$/'), 'confirm_pwd' => 'min:6|max:15|same:pwd', // 'first_name' => 'required_with:name|max:100|different:name', @@ -176,7 +180,7 @@ public function testCheckbox() public function testIntegration() { - $html = $this->form->model(new \stdClass(), ['url' => '/'], static::$validationRules); + $html = $this->form->model(new \stdClass(), array('url' => '/'), static::$validationRules); $this->assertEquals('', $html); $this->assertEquals(static::$validationRules, $this->converter->getValidationRules()); @@ -189,7 +193,7 @@ public function testIntegration() $this->assertContains(' pattern="^[A-Za-z0-9_.-]+$" data-msg-pattern="The UID may only contain letters and numbers."', $html); $this->assertContains(' data-rule-remote="/laravalid/exists?params=dXNlcnMsdWlk" data-msg-remote="The UID did not exist."', $html); - $html = $this->form->email('email', null, ['placeholder' => 'Email']); + $html = $this->form->email('email', null, array('placeholder' => 'Email')); $this->assertStringEndsWith(' name="email" type="email">', $html); $this->assertStringStartsWith('assertContains(' required="required" data-msg-required="The email field is required."', $html); @@ -252,7 +256,7 @@ public function testIntegration() $this->assertContains(' data-rule-url="true" data-msg-url="The photo format is invalid."', $html); $this->assertContains(' data-rule-remote="/laravalid/active_url?params=YW5vbg" data-msg-remote="The photo is not a valid URL."', $html); - $html = $this->form->select('gender', ['Female', 'Male']);// unsupported: boolean + $html = $this->form->select('gender', array('Female', 'Male'));// unsupported: boolean $this->assertEquals('', $html); $html = $this->form->input('date', 'birthdate'); @@ -268,10 +272,10 @@ public function testIntegration() $this->assertStringStartsWith('assertContains(' data-rule-rangelength="20,30" maxlength="30" data-msg-rangelength="The phone must be between {0} and {1} characters."', $html); - $html = $this->form->select('country', ['US' => 'US', 'VN' => 'VN']);// unsupported: in + $html = $this->form->select('country', array('US' => 'US', 'VN' => 'VN'));// unsupported: in $this->assertEquals('', $html); - $html = $this->form->number('rating'); + $html = method_exists($this->form, 'number') ? $this->form->number('rating') : $this->form->input('number', 'rating'); $this->assertStringEndsWith(' name="rating" type="number">', $html); $this->assertStringStartsWith('assertNotContains(' data-rule-numeric=', $html); @@ -279,14 +283,14 @@ public function testIntegration() $this->assertContains(' data-msg-number="The rating must be a number."', $html); $this->assertContains(' data-rule-range="0,100" data-msg-range="The rating must be between {0} and {1}."', $html); - $html = $this->form->number('duration'); + $html = method_exists($this->form, 'number') ? $this->form->number('duration') : $this->form->input('number', 'duration'); $this->assertStringEndsWith(' name="duration" type="number">', $html); $this->assertStringStartsWith('assertContains(' data-rule-integer="true" data-msg-integer="The length must be an integer."', $html); $this->assertContains(' min="0" data-msg-min="The length must be at least {0}."', $html); $this->assertContains(' max="18000" data-msg-max="The length may not be greater than {0}."', $html); - $html = $this->form->textarea('description', null, ['rows' => 5]); + $html = $this->form->textarea('description', null, array('rows' => 5)); $this->assertStringEndsWith(' name="description" cols="50">', $html); $this->assertStringStartsWith('