Skip to content

Instantly share code, notes, and snippets.

@mikey179
Created March 11, 2020 15:05
Show Gist options
  • Save mikey179/b456093fe0c2ec73a31a61a862676079 to your computer and use it in GitHub Desktop.
Save mikey179/b456093fe0c2ec73a31a61a862676079 to your computer and use it in GitHub Desktop.
<?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);
@mikey179
Copy link
Author

mikey179 commented Mar 11, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment