/** * Creates a closure from a lambda expression. * * @param string $expr The expression. * @param bool $throwException Throw exception or return (false) instead. * * @return \Closure|bool The closure or (false) on error. * * @throws ArgumentException $expr is no valid expression. */ public static function toLambda($expr, bool $throwException = true) { $throwOrReturn = function () use($throwException) { if ($throwException) { throw new System\ArgumentException('expr', 'No lambda expression!', null, 0); } return false; }; if (!ClrString::canBeString($expr)) { return $throwOrReturn(); } $expr = trim(ClrString::valueToString($expr)); // check for lambda if (1 === preg_match("/^(\\s*)([\\(]?)([^\\)]*)([\\)]?)(\\s*)(=>)/m", $expr, $lambdaMatches)) { if (empty($lambdaMatches[2]) && !empty($lambdaMatches[4]) || !empty($lambdaMatches[2]) && empty($lambdaMatches[4])) { if ($throwException) { throw new System\ArgumentException('expr', 'Syntax error in lambda expression!', null, 1); } return false; } $lambdaBody = trim(substr($expr, strlen($lambdaMatches[0])), '{}' . " \t\n\r\v"); // remove surrounding {} if ('' !== $lambdaBody) { if (';' !== \substr($lambdaBody, -1)) { // auto add return statement $lambdaBody = 'return ' . $lambdaBody . ';'; } } return self::execGlobal('return function(' . $lambdaMatches[3] . ') { ' . $lambdaBody . ' };'); } return $throwOrReturn(); }
/** * Returns a value as stream. * * @param mixed $val The input value. * * @return IStream|null $val as stream or (null) if $val is also (null). * * @throws ArgumentException $val is invalid. */ public static function asStream($val) { if ($val instanceof IStream) { return $val; } if (null === $val) { return null; } if (\is_resource($val)) { return new self($val, false); } if (ClrString::canBeString($val)) { return new MemoryStream($val); } throw new ArgumentException('val'); }