Created
March 11, 2020 15:05
-
-
Save mikey179/b456093fe0c2ec73a31a61a862676079 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SpecializedValidator extends AbstractValidator | |
{ | |
private $somethingToCheck; | |
public function __construct($somethingToCheck) | |
{ | |
parent::__construct([$this, 'validate']); // sic! | |
$this->somethingToCheck = $somethingToCheck; | |
} | |
/** | |
* @return bool|string | |
*/ | |
protected function validate() | |
{ | |
if ($this->somethingToCheck === 'foo') { | |
return true; | |
} | |
return 'expected foo!'; | |
} | |
} | |
// sic! | |
class AbstractValidator | |
{ | |
/** | |
* @var callable | |
*/ | |
private $callback; | |
public function __construct(callable $callable, $customErrorCode = null) { | |
// store its callback | |
$this->callback = $callable; | |
// assure its callback | |
if (!is_callable($callable)) { | |
throw new \Exception('First argument has to be a valid callback!'); | |
} | |
} | |
public function isValid($value, &$messages = array()) | |
{ | |
$message = call_user_func_array($this->callback, func_get_args()); | |
// assure validity | |
if ($message === true) { | |
return true; | |
} | |
// set as invalid | |
$messages[] = $message; | |
// return | |
return false; | |
} | |
} | |
// let's see how this works | |
$msg = []; | |
$v = new SpecializedValidator('foo'); | |
var_dump($v->isValid('this value is completely irrelevant', $msg)); | |
var_dump($msg); | |
$v = new SpecializedValidator('bar'); | |
var_dump($v->isValid('this value is completely irrelevant', $msg)); | |
var_dump($msg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A WTF I found in some code today... abstracted and reduced to the minimum to highlight the WTFs. Lines from 60 are just to give you something to execute when you want to try running this.