I have built a class which validates configuration data. Below is a very simplified version with only the code that's relevant to this question.
class configValidator
{
private $_errors = [];
public function validate()
{
$this->errorGenerator(1, 'fail');
if ($this->_errors) return $this->_errors;
$this->errorGenerator(2, 'pass');
if ($this->_errors) return $this->_errors;
$this->errorGenerator(3, 'fail');
if ($this->_errors) return $this->_errors;
$this->errorGenerator(4, 'fail');
if ($this->_errors) return $this->_errors;
}
private function errorGenerator($id, $string)
{
if ($string == 'fail') $this->_errors[] = 'an error occurred on ID ' . $id;
}
}
$configValidator = new ConfigValidator();
$errors = $configValidator->validate();
if (!empty($errors)) {
exit(json_encode($errors));
} else {
echo 'config validations passed';
}
In the validate()
method, it is important that errors are returned to the caller, if any exist, after each call to the errorGenerator()
method. This is because in the actual version there are arrays with keys and subsequent calls to errorGenerator()
are dependent on those array keys existing. If they don't exist, then PHP gives an "undefined index notice".
As written above, the code operates as expected - it displays ["an error occurred on ID 1"]
in the browser and does not get as far as executing the other calls to the errorGenerator()
method. This is the desired behavior.
However, looking at the validate()
method, it seems redundant to type this line 4 times
if ($this->_errors) return $this->_errors;
so I experimented with stripping it out of the validate()
method and putting that line into the errorGenerator()
method like so:
public function validate()
{
$this->errorGenerator(1, 'fail');
$this->errorGenerator(2, 'pass');
$this->errorGenerator(3, 'fail');
$this->errorGenerator(4, 'fail');
}
private function errorGenerator($id, $string)
{
if ($string == 'fail') $this->_errors[] = 'an error occurred on ID ' . $id;
if ($this->_errors) return $this->_errors;
}
This results in the browser displaying config validations passed
, which is not the desired outcome. It makes sense that is what's being displayed because moving that line into the errorGenerator()
method returns control to the validate()
method rather than to the code that called the validate()
method.
I'm wondering if there's a way to refactor this code such that it returns the errors to the caller of validate()
, yet does not repeat this line
if ($this->_errors) return $this->_errors;