functional-php/src/functions.php
2018-07-16 21:47:06 +02:00

81 lines
1.9 KiB
PHP

<?php
namespace Kadet\Functional;
use Kadet\Functional\Predicate\AllOfPredicate;
use Kadet\Functional\Predicate\AnyOfPredicate;
use Kadet\Functional\Predicate\ClosurePredicate;
use Kadet\Functional\Predicate\ConstantPredicate;
use Kadet\Functional\Reflection\ReflectionPartiallyAppliedFunction;
use Kadet\Functional\Utils\PartiallyAppliedFunction;
require_once __DIR__.'/Utils/index.php';
/**
* @param $predicate
*
* @return \Kadet\Functional\Predicate
*/
function predicate($predicate): Predicate
{
switch (true) {
case $predicate instanceof Predicate:
return $predicate;
case is_callable($predicate):
return new ClosurePredicate(\Closure::fromCallable($predicate));
default:
throw new \InvalidArgumentException('$predicate is not valid predicate.');
}
}
function not($predicate)
{
return predicate($predicate)->not();
}
function always()
{
return ConstantPredicate::always();
}
function never()
{
return ConstantPredicate::never();
}
function unpack($arguments)
{
return count($arguments) === 1 && is_array(reset($arguments))
? reset($arguments)
: $arguments;
}
function all(...$predicates)
{
$predicates = unpack($predicates);
return new AllOfPredicate(...array_map(predicate::class, $predicates));
}
function any(...$predicates)
{
$predicates = unpack($predicates);
return new AnyOfPredicate(...array_map(predicate::class, $predicates));
}
function symbol($name = null)
{
$id = random_bytes(64);
return sprintf("%s(%s)", $name ?: 'symbol', $id);
}
function reflect(callable $callable): \ReflectionFunctionAbstract
{
switch (true) {
case $callable instanceof PartiallyAppliedFunction:
return new ReflectionPartiallyAppliedFunction($callable);
default:
return new \ReflectionFunction($callable);
}
}
define(__NAMESPACE__.'\\_', symbol('placeholder'));