Skip to content

Commit

Permalink
dev
Browse files Browse the repository at this point in the history
  • Loading branch information
mvkasatkin committed Sep 13, 2017
1 parent 0c6a63c commit 86c48f9
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 18 deletions.
46 changes: 34 additions & 12 deletions src/utils/traits/TraitErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ trait TraitErrors
protected $_errors = [];

/**
* @param $error
* @param string $code
* @param $error
*/
public function addError($error, $code = '_')
public function addError($code, $error)
{
if(!isset($this->_errors[$code])) {
$this->_errors[$code] = [];
Expand All @@ -23,31 +23,53 @@ public function addError($error, $code = '_')
}

/**
* @param string $code
* @param null|string $code
* @return bool
*/
public function hasErrors($code = '_')
public function hasErrors($code = null)
{
return count($this->getErrors($code)) > 0;
}

/**
* @param string $code
* @param null|string $code
* @return array
*/
public function getErrors($code = '_')
public function getErrors($code = null)
{
return isset($this->_errors[$code])
? $this->_errors[$code]
: [];
if($code) {
return isset($this->_errors[$code])
? $this->_errors[$code]
: [];
}
return $this->_errors;
}

/**
* @param string $code
* @return array
*/
public function resetErrors($code = '_')
public function getFirstErrors()
{
unset($this->_errors[$code]);
$result = [];
foreach ($this->getErrors() as $field => $errors) {
if($errors) {
$result[$field] = reset($errors);
}
}
return $result;
}

/**
* @param null|string $code
*/
public function resetErrors($code = null)
{
if($code) {
unset($this->_errors[$code]);
}
else {
$this->_errors = [];
}
}

}
6 changes: 0 additions & 6 deletions tests/form/FormTest.php

This file was deleted.

41 changes: 41 additions & 0 deletions tests/utils/traits/TraitErrorsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,45 @@
class TraitErrorsTest extends \PHPUnit\Framework\TestCase
{

public function test()
{
$o = new TraitErrorsTestC();
$this->assertFalse($o->hasErrors());

$o->addError('a', 'a1');
$o->addError('a', 'a2');
$o->addError('b', 'b1');
$this->assertTrue($o->hasErrors());
$this->assertTrue($o->hasErrors('a'));
$this->assertTrue($o->hasErrors('b'));
$this->assertFalse($o->hasErrors('c'));

$this->assertEquals([
'a' => ['a1', 'a2'],
'b' => ['b1']
],$o->getErrors());

$this->assertEquals(['b1'], $o->getErrors('b'));

$this->assertEquals([
'a' => 'a1',
'b' => 'b1'
],$o->getFirstErrors());

$o->resetErrors('a');
$this->assertFalse($o->hasErrors('a'));
$this->assertTrue($o->hasErrors());

$o->resetErrors();
$o->addError('c', 'c1');
$this->assertTrue($o->hasErrors());

$o->resetErrors('c');
$this->assertFalse($o->hasErrors());
}

}

class TraitErrorsTestC {
use \WebComplete\core\utils\traits\TraitErrors;
}

0 comments on commit 86c48f9

Please sign in to comment.