code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function __construct(?StreamOut $output = null)
{
$this->_output = $output;
return;
} | Wraps an `Hoa\Stream\IStream\Out` stream. | __construct | php | bobthecow/psysh | src/Readline/Hoa/ConsoleOutput.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleOutput.php | MIT |
public function __construct(?StreamIn $input = null)
{
if (null === $input) {
if (\defined('STDIN') &&
false !== @\stream_get_meta_data(\STDIN)) {
$input = new FileRead('php://stdin');
} else {
$input = new FileRead('/dev/tty');
}
}
$this->_input = $input;
return;
} | Wraps an `Hoa\Stream\IStream\In` stream. | __construct | php | bobthecow/psysh | src/Readline/Hoa/ConsoleInput.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ConsoleInput.php | MIT |
protected function setAutocompleters(array $autocompleters)
{
$old = $this->_autocompleters;
$this->_autocompleters = new \ArrayObject($autocompleters);
return $old;
} | Set/initialize list of autocompleters. | setAutocompleters | php | bobthecow/psysh | src/Readline/Hoa/AutocompleterAggregate.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/AutocompleterAggregate.php | MIT |
public function __construct(
string $message,
int $code = 0,
$arguments = [],
?\Exception $previous = null
) {
$this->_tmpArguments = $arguments;
parent::__construct($message, $code, $previous);
$this->_rawMessage = $message;
$this->message = @\vsprintf($message, $this->getArguments());
return;
} | Allocates a new exception.
An exception is built with a formatted message, a code (an ID) and an
array that contains the list of formatted strings for the message. If
chaining, we can add a previous exception. | __construct | php | bobthecow/psysh | src/Readline/Hoa/ExceptionIdle.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ExceptionIdle.php | MIT |
public function getBacktrace()
{
if (null === $this->_trace) {
$this->_trace = $this->getTrace();
}
return $this->_trace;
} | Returns the backtrace.
Do not use `Exception::getTrace` any more. | getBacktrace | php | bobthecow/psysh | src/Readline/Hoa/ExceptionIdle.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ExceptionIdle.php | MIT |
public function getPreviousThrow()
{
if (null === $this->_previous) {
$this->_previous = $this->getPrevious();
}
return $this->_previous;
} | Returns the previous exception if any.
Do not use `Exception::getPrevious` any more. | getPreviousThrow | php | bobthecow/psysh | src/Readline/Hoa/ExceptionIdle.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ExceptionIdle.php | MIT |
public function getArguments()
{
if (null === $this->_arguments) {
$arguments = $this->_tmpArguments;
if (!\is_array($arguments)) {
$arguments = [$arguments];
}
foreach ($arguments as &$value) {
if (null === $value) {
$value = '(null)';
}
}
$this->_arguments = $arguments;
unset($this->_tmpArguments);
}
return $this->_arguments;
} | Returns the arguments of the message. | getArguments | php | bobthecow/psysh | src/Readline/Hoa/ExceptionIdle.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ExceptionIdle.php | MIT |
public static function uncaught(\Throwable $exception)
{
if (!($exception instanceof self)) {
throw $exception;
}
while (0 < \ob_get_level()) {
\ob_end_flush();
}
echo 'Uncaught exception ('.\get_class($exception).'):'."\n".
$exception->raise(true);
} | Catches uncaught exception (only `Hoa\Exception\Idle` and children). | uncaught | php | bobthecow/psysh | src/Readline/Hoa/ExceptionIdle.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ExceptionIdle.php | MIT |
public static function enableUncaughtHandler(bool $enable = true)
{
if (false === $enable) {
return \restore_exception_handler();
}
return \set_exception_handler(function ($exception) {
return self::uncaught($exception);
});
} | Enables uncaught exception handler.
This is restricted to Hoa's exceptions only. | enableUncaughtHandler | php | bobthecow/psysh | src/Readline/Hoa/ExceptionIdle.php | https://github.com/bobthecow/psysh/blob/master/src/Readline/Hoa/ExceptionIdle.php | MIT |
public function addMatcher(AbstractMatcher $matcher)
{
$this->matchers[] = $matcher;
} | Register a tab completion Matcher.
@param AbstractMatcher $matcher | addMatcher | php | bobthecow/psysh | src/TabCompletion/AutoCompleter.php | https://github.com/bobthecow/psysh/blob/master/src/TabCompletion/AutoCompleter.php | MIT |
public function activate()
{
\readline_completion_function([&$this, 'callback']);
} | Activate readline tab completion. | activate | php | bobthecow/psysh | src/TabCompletion/AutoCompleter.php | https://github.com/bobthecow/psysh/blob/master/src/TabCompletion/AutoCompleter.php | MIT |
public function __destruct()
{
// PHP didn't implement the whole readline API when they first switched
// to libedit. And they still haven't.
if (\function_exists('readline_callback_handler_remove')) {
\readline_callback_handler_remove();
}
} | Remove readline callback handler on destruct. | __destruct | php | bobthecow/psysh | src/TabCompletion/AutoCompleter.php | https://github.com/bobthecow/psysh/blob/master/src/TabCompletion/AutoCompleter.php | MIT |
protected function getVariable(string $var)
{
return $this->context->get($var);
} | Get a Context variable by name.
@param string $var Variable name
@return mixed | getVariable | php | bobthecow/psysh | src/TabCompletion/Matcher/AbstractContextAwareMatcher.php | https://github.com/bobthecow/psysh/blob/master/src/TabCompletion/Matcher/AbstractContextAwareMatcher.php | MIT |
protected function setComment(string $comment)
{
$this->desc = '';
$this->tags = [];
$this->comment = $comment;
$this->parseComment($comment);
} | Set and parse the docblock comment.
@param string $comment The docblock | setComment | php | bobthecow/psysh | src/Util/Docblock.php | https://github.com/bobthecow/psysh/blob/master/src/Util/Docblock.php | MIT |
public static function strTag(string $str)
{
if (\preg_match('/^@[a-z0-9_]+/', $str, $matches)) {
return $matches[0];
}
} | The tag at the beginning of a string.
@param string $str
@return string|null | strTag | php | bobthecow/psysh | src/Util/Docblock.php | https://github.com/bobthecow/psysh/blob/master/src/Util/Docblock.php | MIT |
private static function getClass($value)
{
if (\is_object($value)) {
return new \ReflectionObject($value);
}
if (!\is_string($value)) {
throw new \InvalidArgumentException('Mirror expects an object or class');
}
if (\class_exists($value) || \interface_exists($value) || \trait_exists($value)) {
return new \ReflectionClass($value);
}
$namespace = \preg_replace('/(^\\\\|\\\\$)/', '', $value);
if (self::namespaceExists($namespace)) {
return new ReflectionNamespace($namespace);
}
throw new \InvalidArgumentException('Unknown namespace, class or function: '.$value);
} | Get a ReflectionClass (or ReflectionObject, or ReflectionNamespace) if possible.
@throws \InvalidArgumentException if $value is not a namespace or class name or instance
@param mixed $value
@return \ReflectionClass|ReflectionNamespace | getClass | php | bobthecow/psysh | src/Util/Mirror.php | https://github.com/bobthecow/psysh/blob/master/src/Util/Mirror.php | MIT |
public function setDownloader(Downloader $downloader)
{
$this->downloader = $downloader;
} | Allow the downloader to be injected for testing.
@return void | setDownloader | php | bobthecow/psysh | src/VersionUpdater/SelfUpdate.php | https://github.com/bobthecow/psysh/blob/master/src/VersionUpdater/SelfUpdate.php | MIT |
public function fetchLatestRelease()
{
$context = \stream_context_create([
'http' => [
'user_agent' => 'PsySH/'.Shell::VERSION,
'timeout' => 1.0,
],
]);
\set_error_handler(function () {
// Just ignore all errors with this. The checker will throw an exception
// if it doesn't work :)
});
$result = @\file_get_contents(self::URL, false, $context);
\restore_error_handler();
return \json_decode($result);
} | Set to public to make testing easier.
@return mixed | fetchLatestRelease | php | bobthecow/psysh | src/VersionUpdater/GitHubChecker.php | https://github.com/bobthecow/psysh/blob/master/src/VersionUpdater/GitHubChecker.php | MIT |
public function close()
{
if (isset($this->pipe)) {
\fclose($this->pipe);
}
if (isset($this->proc)) {
$exit = \proc_close($this->proc);
if ($exit !== 0) {
throw new \RuntimeException('Error closing output stream');
}
}
$this->pipe = null;
$this->proc = null;
} | Close the current pager process. | close | php | bobthecow/psysh | src/Output/ProcOutputPager.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ProcOutputPager.php | MIT |
private function getPipe()
{
if (!isset($this->pipe) || !isset($this->proc)) {
$desc = [['pipe', 'r'], $this->stream, \fopen('php://stderr', 'w')];
$this->proc = \proc_open($this->cmd, $desc, $pipes);
if (!\is_resource($this->proc)) {
throw new \RuntimeException('Error opening output stream');
}
$this->pipe = $pipes[0];
}
return $this->pipe;
} | Get a pipe for paging output.
If no active pager process exists, fork one and return its input pipe. | getPipe | php | bobthecow/psysh | src/Output/ProcOutputPager.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ProcOutputPager.php | MIT |
public function setCompact(bool $compact)
{
$this->compact = $compact;
} | Enable or disable compact output. | setCompact | php | bobthecow/psysh | src/Output/Theme.php | https://github.com/bobthecow/psysh/blob/master/src/Output/Theme.php | MIT |
public function setBufferPrompt(string $bufferPrompt)
{
$this->bufferPrompt = $bufferPrompt;
} | Set the buffer prompt string (used for multi-line input continuation). | setBufferPrompt | php | bobthecow/psysh | src/Output/Theme.php | https://github.com/bobthecow/psysh/blob/master/src/Output/Theme.php | MIT |
public function setReplayPrompt(string $replayPrompt)
{
$this->replayPrompt = $replayPrompt;
} | Set the prompt string used when replaying history. | setReplayPrompt | php | bobthecow/psysh | src/Output/Theme.php | https://github.com/bobthecow/psysh/blob/master/src/Output/Theme.php | MIT |
public function setGrayFallback(string $grayFallback)
{
$this->grayFallback = $grayFallback;
} | Set the fallback color when "gray" is unavailable. | setGrayFallback | php | bobthecow/psysh | src/Output/Theme.php | https://github.com/bobthecow/psysh/blob/master/src/Output/Theme.php | MIT |
public function setStyles(array $styles)
{
foreach (\array_keys(static::DEFAULT_STYLES) as $name) {
$this->styles[$name] = $styles[$name] ?? static::DEFAULT_STYLES[$name];
}
} | Set the shell output formatter styles.
Accepts a map from style name to [fg, bg, options], for example:
[
'error' => ['white', 'red', ['bold']],
'warning' => ['black', 'yellow'],
]
Foreground, background or options can be null, or even omitted entirely. | setStyles | php | bobthecow/psysh | src/Output/Theme.php | https://github.com/bobthecow/psysh/blob/master/src/Output/Theme.php | MIT |
public function page($messages, int $type = 0)
{
if (\is_string($messages)) {
$messages = (array) $messages;
}
if (!\is_array($messages) && !\is_callable($messages)) {
throw new \InvalidArgumentException('Paged output requires a string, array or callback');
}
$this->startPaging();
if (\is_callable($messages)) {
$messages($this);
} else {
$this->write($messages, true, $type);
}
$this->stopPaging();
} | Page multiple lines of output.
The output pager is started
If $messages is callable, it will be called, passing this output instance
for rendering. Otherwise, all passed $messages are paged to output.
Upon completion, the output pager is flushed.
@param string|array|\Closure $messages A string, array of strings or a callback
@param int $type (default: 0) | page | php | bobthecow/psysh | src/Output/ShellOutput.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ShellOutput.php | MIT |
public function startPaging()
{
$this->paging++;
} | Start sending output to the output pager. | startPaging | php | bobthecow/psysh | src/Output/ShellOutput.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ShellOutput.php | MIT |
public function stopPaging()
{
$this->paging--;
$this->closePager();
} | Stop paging output and flush the output pager. | stopPaging | php | bobthecow/psysh | src/Output/ShellOutput.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ShellOutput.php | MIT |
private function closePager()
{
if ($this->paging <= 0) {
$this->pager->close();
}
} | Flush and close the output pager. | closePager | php | bobthecow/psysh | src/Output/ShellOutput.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ShellOutput.php | MIT |
private function initFormatters()
{
$useGrayFallback = !$this->grayExists();
$this->theme->applyStyles($this->getFormatter(), $useGrayFallback);
$this->theme->applyErrorStyles($this->getErrorOutput()->getFormatter(), $useGrayFallback);
} | Initialize output formatter styles. | initFormatters | php | bobthecow/psysh | src/Output/ShellOutput.php | https://github.com/bobthecow/psysh/blob/master/src/Output/ShellOutput.php | MIT |
public static function fromThrowable($throwable)
{
@\trigger_error('PsySH no longer wraps Throwables', \E_USER_DEPRECATED);
} | Create a ThrowUpException from a Throwable.
@deprecated PsySH no longer wraps Throwables
@param \Throwable $throwable | fromThrowable | php | bobthecow/psysh | src/Exception/ThrowUpException.php | https://github.com/bobthecow/psysh/blob/master/src/Exception/ThrowUpException.php | MIT |
public function __construct($message = '', $code = 0, $severity = 1, $filename = null, $lineno = null, ?\Throwable $previous = null)
{
$this->rawMessage = $message;
if (!empty($filename) && \preg_match('{Psy[/\\\\]ExecutionLoop}', $filename)) {
$filename = '';
}
switch ($severity) {
case \E_NOTICE:
case \E_USER_NOTICE:
$type = 'Notice';
break;
case \E_WARNING:
case \E_CORE_WARNING:
case \E_COMPILE_WARNING:
case \E_USER_WARNING:
$type = 'Warning';
break;
case \E_DEPRECATED:
case \E_USER_DEPRECATED:
$type = 'Deprecated';
break;
case \E_RECOVERABLE_ERROR:
$type = 'Recoverable fatal error';
break;
default:
if (\PHP_VERSION_ID < 80400 && $severity === \E_STRICT) {
$type = 'Strict error';
break;
}
$type = 'Error';
break;
}
$message = \sprintf('PHP %s: %s%s on line %d', $type, $message, $filename ? ' in '.$filename : '', $lineno);
parent::__construct($message, $code, $severity, $filename, $lineno, $previous);
} | Construct a Psy ErrorException.
@param string $message (default: "")
@param int $code (default: 0)
@param int $severity (default: 1)
@param string|null $filename (default: null)
@param int|null $lineno (default: null)
@param \Throwable|null $previous (default: null) | __construct | php | bobthecow/psysh | src/Exception/ErrorException.php | https://github.com/bobthecow/psysh/blob/master/src/Exception/ErrorException.php | MIT |
public static function fromError(\Error $e)
{
@\trigger_error('PsySH no longer wraps Errors', \E_USER_DEPRECATED);
} | Create an ErrorException from an Error.
@deprecated PsySH no longer wraps Errors
@param \Error $e | fromError | php | bobthecow/psysh | src/Exception/ErrorException.php | https://github.com/bobthecow/psysh/blob/master/src/Exception/ErrorException.php | MIT |
public static function exitShell()
{
throw new self('Goodbye');
} | Throws BreakException.
Since `throw` can not be inserted into arbitrary expressions, it wraps with function call.
@throws BreakException | exitShell | php | bobthecow/psysh | src/Exception/BreakException.php | https://github.com/bobthecow/psysh/blob/master/src/Exception/BreakException.php | MIT |
public function __construct(string $keyword)
{
if (!self::isLanguageConstruct($keyword)) {
throw new \InvalidArgumentException('Unknown language construct: '.$keyword);
}
$this->keyword = $keyword;
} | Construct a ReflectionLanguageConstruct object.
@param string $keyword | __construct | php | bobthecow/psysh | src/Reflection/ReflectionLanguageConstruct.php | https://github.com/bobthecow/psysh/blob/master/src/Reflection/ReflectionLanguageConstruct.php | MIT |
public static function export($name)
{
throw new \RuntimeException('Not yet implemented because it\'s unclear what I should do here :)');
} | This can't (and shouldn't) do anything :).
@throws \RuntimeException | export | php | bobthecow/psysh | src/Reflection/ReflectionLanguageConstruct.php | https://github.com/bobthecow/psysh/blob/master/src/Reflection/ReflectionLanguageConstruct.php | MIT |
public function getFileName()
{
return false;
} | Gets the file name from a language construct.
(Hint: it always returns false)
@todo remove \ReturnTypeWillChange attribute after dropping support for PHP 7.x (when we can use union types)
@return string|false (false) | getFileName | php | bobthecow/psysh | src/Reflection/ReflectionLanguageConstruct.php | https://github.com/bobthecow/psysh/blob/master/src/Reflection/ReflectionLanguageConstruct.php | MIT |
public function __construct(string $name)
{
$this->name = $name;
if (!\defined($name) && !self::isMagicConstant($name)) {
throw new \InvalidArgumentException('Unknown constant: '.$name);
}
if (!self::isMagicConstant($name)) {
$this->value = @\constant($name);
}
} | Construct a ReflectionConstant object.
@param string $name | __construct | php | bobthecow/psysh | src/Reflection/ReflectionConstant.php | https://github.com/bobthecow/psysh/blob/master/src/Reflection/ReflectionConstant.php | MIT |
public function getFileName()
{
return;
// return $this->class->getFileName();
} | Gets the constant's file name.
Currently returns null, because if it returns a file name the signature
formatter will barf. | getFileName | php | bobthecow/psysh | src/Reflection/ReflectionConstant.php | https://github.com/bobthecow/psysh/blob/master/src/Reflection/ReflectionConstant.php | MIT |
public function __construct(string $name)
{
$this->name = $name;
} | Construct a ReflectionNamespace object.
@param string $name | __construct | php | bobthecow/psysh | src/Reflection/ReflectionNamespace.php | https://github.com/bobthecow/psysh/blob/master/src/Reflection/ReflectionNamespace.php | MIT |
public static function markStart()
{
self::$start = \hrtime(true);
} | Internal method for marking the start of timeit execution.
A static call to this method will be injected at the start of the timeit
input code to instrument the call. We will use the saved start time to
more accurately calculate time elapsed during execution. | markStart | php | bobthecow/psysh | src/Command/TimeitCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/TimeitCommand.php | MIT |
public static function markEnd($ret = null)
{
self::$times[] = \hrtime(true) - self::$start;
self::$start = null;
return $ret;
} | Internal method for marking the end of timeit execution.
A static call to this method is injected by TimeitVisitor at the end
of the timeit input code to instrument the call.
Note that this accepts an optional $ret parameter, which is used to pass
the return value of the last statement back out of timeit. This saves us
a bunch of code rewriting shenanigans.
@param mixed $ret
@return mixed it just passes $ret right back | markEnd | php | bobthecow/psysh | src/Command/TimeitCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/TimeitCommand.php | MIT |
private function ensureEndMarked()
{
if (self::$start !== null) {
self::markEnd();
}
} | Ensure that the end of code execution was marked.
The end *should* be marked in the instrumented code, but just in case
we'll add a fallback here. | ensureEndMarked | php | bobthecow/psysh | src/Command/TimeitCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/TimeitCommand.php | MIT |
private function validateInput(InputInterface $input)
{
if (!$input->getArgument('target')) {
// if no target is passed, there can be no properties or methods
foreach (['properties', 'methods', 'no-inherit'] as $option) {
if ($input->getOption($option)) {
throw new RuntimeException('--'.$option.' does not make sense without a specified target');
}
}
foreach (['globals', 'vars', 'constants', 'functions', 'classes', 'interfaces', 'traits'] as $option) {
if ($input->getOption($option)) {
return;
}
}
// default to --vars if no other options are passed
$input->setOption('vars', true);
} else {
// if a target is passed, classes, functions, etc don't make sense
foreach (['vars', 'globals'] as $option) {
if ($input->getOption($option)) {
throw new RuntimeException('--'.$option.' does not make sense with a specified target');
}
}
// @todo ensure that 'functions', 'classes', 'interfaces', 'traits' only accept namespace target?
foreach (['constants', 'properties', 'methods', 'functions', 'classes', 'interfaces', 'traits'] as $option) {
if ($input->getOption($option)) {
return;
}
}
// default to --constants --properties --methods if no other options are passed
$input->setOption('constants', true);
$input->setOption('properties', true);
$input->setOption('methods', true);
}
} | Validate that input options make sense, provide defaults when called without options.
@throws RuntimeException if options are inconsistent
@param InputInterface $input | validateInput | php | bobthecow/psysh | src/Command/ListCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/ListCommand.php | MIT |
protected function resolveCode(string $code)
{
try {
// Add an implicit `sudo` to target resolution.
$nodes = $this->traverser->traverse($this->parser->parse($code));
$sudoCode = $this->printer->prettyPrint($nodes);
$value = $this->getShell()->execute($sudoCode, true);
} catch (\Throwable $e) {
// Swallow all exceptions?
}
if (!isset($value) || $value instanceof NoReturnValue) {
throw new RuntimeException('Unknown target: '.$code);
}
return $value;
} | Resolve code to a value in the current scope.
@throws RuntimeException when the code does not return a value in the current scope
@param string $code
@return mixed Variable value | resolveCode | php | bobthecow/psysh | src/Command/ReflectingCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/ReflectingCommand.php | MIT |
private function resolveObject(string $code)
{
$value = $this->resolveCode($code);
if (!\is_object($value)) {
throw new UnexpectedTargetException($value, 'Unable to inspect a non-object');
}
return $value;
} | Resolve code to an object in the current scope.
@throws UnexpectedTargetException when the code resolves to a non-object value
@param string $code
@return object Variable instance | resolveObject | php | bobthecow/psysh | src/Command/ReflectingCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/ReflectingCommand.php | MIT |
protected function getScopeVariable(string $name)
{
return $this->context->get($name);
} | Get a variable from the current shell scope.
@param string $name
@return mixed | getScopeVariable | php | bobthecow/psysh | src/Command/ReflectingCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/ReflectingCommand.php | MIT |
protected function setCommandScopeVariables(\Reflector $reflector)
{
$vars = [];
switch (\get_class($reflector)) {
case \ReflectionClass::class:
case \ReflectionObject::class:
$vars['__class'] = $reflector->name;
if ($reflector->inNamespace()) {
$vars['__namespace'] = $reflector->getNamespaceName();
}
break;
case \ReflectionMethod::class:
$vars['__method'] = \sprintf('%s::%s', $reflector->class, $reflector->name);
$vars['__class'] = $reflector->class;
$classReflector = $reflector->getDeclaringClass();
if ($classReflector->inNamespace()) {
$vars['__namespace'] = $classReflector->getNamespaceName();
}
break;
case \ReflectionFunction::class:
$vars['__function'] = $reflector->name;
if ($reflector->inNamespace()) {
$vars['__namespace'] = $reflector->getNamespaceName();
}
break;
case \ReflectionGenerator::class:
$funcReflector = $reflector->getFunction();
$vars['__function'] = $funcReflector->name;
if ($funcReflector->inNamespace()) {
$vars['__namespace'] = $funcReflector->getNamespaceName();
}
if ($fileName = $reflector->getExecutingFile()) {
$vars['__file'] = $fileName;
$vars['__line'] = $reflector->getExecutingLine();
$vars['__dir'] = \dirname($fileName);
}
break;
case \ReflectionProperty::class:
case \ReflectionClassConstant::class:
$classReflector = $reflector->getDeclaringClass();
$vars['__class'] = $classReflector->name;
if ($classReflector->inNamespace()) {
$vars['__namespace'] = $classReflector->getNamespaceName();
}
// no line for these, but this'll do
if ($fileName = $reflector->getDeclaringClass()->getFileName()) {
$vars['__file'] = $fileName;
$vars['__dir'] = \dirname($fileName);
}
break;
case ReflectionConstant::class:
if ($reflector->inNamespace()) {
$vars['__namespace'] = $reflector->getNamespaceName();
}
break;
}
if ($reflector instanceof \ReflectionClass || $reflector instanceof \ReflectionFunctionAbstract) {
if ($fileName = $reflector->getFileName()) {
$vars['__file'] = $fileName;
$vars['__line'] = $reflector->getStartLine();
$vars['__dir'] = \dirname($fileName);
}
}
$this->context->setCommandScopeVariables($vars);
} | Given a Reflector instance, set command-scope variables in the shell
execution context. This is used to inject magic $__class, $__method and
$__file variables (as well as a handful of others).
@param \Reflector $reflector | setCommandScopeVariables | php | bobthecow/psysh | src/Command/ReflectingCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/ReflectingCommand.php | MIT |
public function setCommand(Command $command)
{
$this->command = $command;
} | Helper for setting a subcommand to retrieve help for.
@param Command $command | setCommand | php | bobthecow/psysh | src/Command/HelpCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/HelpCommand.php | MIT |
public function setReadline(Readline $readline)
{
$this->readline = $readline;
} | Set the Shell's Readline service.
@param Readline $readline | setReadline | php | bobthecow/psysh | src/Command/SudoCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/SudoCommand.php | MIT |
private function validateOnlyOne(InputInterface $input, array $options)
{
$count = 0;
foreach ($options as $opt) {
if ($input->getOption($opt)) {
$count++;
}
}
if ($count > 1) {
throw new \InvalidArgumentException('Please specify only one of --'.\implode(', --', $options));
}
} | Validate that only one of the given $options is set.
@param InputInterface $input
@param array $options | validateOnlyOne | php | bobthecow/psysh | src/Command/HistoryCommand.php | https://github.com/bobthecow/psysh/blob/master/src/Command/HistoryCommand.php | MIT |
public function __construct(Presenter $presenter, Context $context)
{
$this->context = $context;
parent::__construct($presenter);
} | Variable Enumerator constructor.
Unlike most other enumerators, the Variable Enumerator needs access to
the current scope variables, so we need to pass it a Context instance.
@param Presenter $presenter
@param Context $context | __construct | php | bobthecow/psysh | src/Command/ListCommand/VariableEnumerator.php | https://github.com/bobthecow/psysh/blob/master/src/Command/ListCommand/VariableEnumerator.php | MIT |
private static function stripTags($code)
{
$tagRegex = '[a-z][^<>]*+';
$output = \preg_replace("#<(($tagRegex) | /($tagRegex)?)>#ix", '', $code);
return \str_replace('\\<', '<', $output);
} | Remove tags from formatted output. This is kind of ugly o_O. | stripTags | php | bobthecow/psysh | test/Formatter/CodeFormatterTest.php | https://github.com/bobthecow/psysh/blob/master/test/Formatter/CodeFormatterTest.php | MIT |
public function dataProviderExitStatement()
{
return [
['exit;', "{$this->expectedExceptionString};"],
['exit();', "{$this->expectedExceptionString};"],
['die;', "{$this->expectedExceptionString};"],
['exit(die(die));', "{$this->expectedExceptionString};"],
['if (true) { exit; }', "if (true) { {$this->expectedExceptionString}; }"],
['if (false) { exit; }', "if (false) { {$this->expectedExceptionString}; }"],
['1 and exit();', "1 and {$this->expectedExceptionString};"],
['foo() or die', "foo() or {$this->expectedExceptionString};"],
['exit and 1;', "{$this->expectedExceptionString} and 1;"],
['if (exit) { echo $wat; }', "if ({$this->expectedExceptionString}) { echo \$wat; }"],
['exit or die;', "{$this->expectedExceptionString} or {$this->expectedExceptionString};"],
['switch (die) { }', "switch ({$this->expectedExceptionString}) {}"],
['for ($i = 1; $i < 10; die) {}', "for (\$i = 1; \$i < 10; {$this->expectedExceptionString}) {}"],
];
} | Data provider for testExitStatement.
@return array | dataProviderExitStatement | php | bobthecow/psysh | test/CodeCleaner/ExitPassTest.php | https://github.com/bobthecow/psysh/blob/master/test/CodeCleaner/ExitPassTest.php | MIT |
public function classesInput()
{
return [
// input, must had, must not had
['T_OPE', ['T_OPEN_TAG'], []],
['st', ['stdClass'], []],
['DateT', ['DateTime', 'DateTimeImmutable', 'DateTimeInterface', 'DateTimeZone'], []],
['stdCla', ['stdClass'], []],
['new s', ['stdClass'], []],
[
'new ',
['stdClass', Context::class, Configuration::class],
['require', 'array_search', 'T_OPEN_TAG', '$foo'],
],
['new Psy\\C', ['Context'], ['CASE_LOWER']],
['\s', ['stdClass'], []],
['array_', ['array_search', 'array_map', 'array_merge'], []],
['$bar->', ['load'], []],
['$b', ['bar'], []],
['6 + $b', ['bar'], []],
['$f', ['foo'], []],
['l', ['ls'], []],
['ls ', [], ['ls']],
['sho', ['show'], []],
['12 + clone $', ['foo'], []],
// [
// '$foo ',
// ['+', 'clone'],
// ['$foo', 'DOMDocument', 'array_map']
// ], requires a operator matcher?
['$', ['foo', 'bar'], ['require', 'array_search', 'T_OPEN_TAG', 'Psy']],
[
'Psy\\',
['Context', 'TabCompletion\\Matcher\\AbstractMatcher'],
['require', 'array_search'],
],
[
'Psy\Test\TabCompletion\StaticSample::CO',
['StaticSample::CONSTANT_VALUE'],
[],
],
[
'Psy\Test\TabCompletion\StaticSample::',
['StaticSample::$staticVariable'],
[],
],
[
'Psy\Test\TabCompletion\StaticSample::',
['StaticSample::staticFunction'],
[],
],
];
} | @todo
====
draft, open to modifications
- [ ] if the variable is an array, return the square bracket for completion
- [ ] if the variable is a constructor or method, reflect to complete as a function call
- [ ] if the preceding token is a variable, call operators or keywords compatible for completion
- [X] a command always should be the second token after php_open_tag
- [X] keywords are never consecutive
- [X] namespacing completion should work just fine
- [X] after a new keyword, should always be a class constructor, never a function call or keyword, constant,
or variable that does not contain a existing class name.
- [X] on a namespaced constructor the completion must show the classes related, not constants.
@return array | classesInput | php | bobthecow/psysh | test/TabCompletion/AutoCompleterTest.php | https://github.com/bobthecow/psysh/blob/master/test/TabCompletion/AutoCompleterTest.php | MIT |
private function setMockMethods($mockBuilder, array $methods)
{
if (\method_exists($mockBuilder, 'onlyMethods')) {
$mockBuilder->onlyMethods($methods);
} else {
$mockBuilder->setMethods($methods);
}
} | Use the more strict onlyMethods if it's available, otherwise use the deprecated setMethods.
@return void | setMockMethods | php | bobthecow/psysh | test/VersionUpdater/SelfUpdateTest.php | https://github.com/bobthecow/psysh/blob/master/test/VersionUpdater/SelfUpdateTest.php | MIT |
public function __construct(UriInterface $host, array $config = [])
{
if ('' === $host->getHost()) {
throw new \LogicException('Host can not be empty');
}
$this->host = $host;
$resolver = new OptionsResolver();
$this->configureOptions($resolver);
$options = $resolver->resolve($config);
$this->replace = $options['replace'];
} | @param array{'replace'?: bool} $config
Configuration options:
- replace: True will replace all hosts, false will only add host when none is specified | __construct | php | php-http/client-common | src/Plugin/AddHostPlugin.php | https://github.com/php-http/client-common/blob/master/src/Plugin/AddHostPlugin.php | MIT |
public function __construct(array $config = [])
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'use_content_encoding' => true,
]);
$resolver->setAllowedTypes('use_content_encoding', 'bool');
$options = $resolver->resolve($config);
$this->useContentEncoding = $options['use_content_encoding'];
} | @param array{'use_content_encoding'?: bool} $config
Configuration options:
- use_content_encoding: Whether this plugin should look at the Content-Encoding header first or only at the Transfer-Encoding (defaults to true) | __construct | php | php-http/client-common | src/Plugin/DecoderPlugin.php | https://github.com/php-http/client-common/blob/master/src/Plugin/DecoderPlugin.php | MIT |
private function decorateStream(string $encoding, StreamInterface $stream)
{
if ('chunked' === strtolower($encoding)) {
return new Encoding\DechunkStream($stream);
}
if ('deflate' === strtolower($encoding)) {
return new Encoding\DecompressStream($stream);
}
if ('gzip' === strtolower($encoding)) {
return new Encoding\GzipDecodeStream($stream);
}
return false;
} | Decorate a stream given an encoding.
@return StreamInterface|false A new stream interface or false if encoding is not supported | decorateStream | php | php-http/client-common | src/Plugin/DecoderPlugin.php | https://github.com/php-http/client-common/blob/master/src/Plugin/DecoderPlugin.php | MIT |
public function __construct(array $config = [])
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'skip_detection' => false,
'size_limit' => 16000000,
]);
$resolver->setAllowedTypes('skip_detection', 'bool');
$resolver->setAllowedTypes('size_limit', 'int');
$options = $resolver->resolve($config);
$this->skipDetection = $options['skip_detection'];
$this->sizeLimit = $options['size_limit'];
} | @param array{'skip_detection'?: bool, 'size_limit'?: int} $config
Configuration options:
- skip_detection: true skip detection if stream size is bigger than $size_limit
- size_limit: size stream limit for which the detection as to be skipped | __construct | php | php-http/client-common | src/Plugin/ContentTypePlugin.php | https://github.com/php-http/client-common/blob/master/src/Plugin/ContentTypePlugin.php | MIT |
public function __construct(array $config = [])
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'only_server_exception' => false,
]);
$resolver->setAllowedTypes('only_server_exception', 'bool');
$options = $resolver->resolve($config);
$this->onlyServerException = $options['only_server_exception'];
} | @param array{'only_server_exception'?: bool} $config
Configuration options:
- only_server_exception: Whether this plugin should only throw 5XX Exceptions (default to false) | __construct | php | php-http/client-common | src/Plugin/ErrorPlugin.php | https://github.com/php-http/client-common/blob/master/src/Plugin/ErrorPlugin.php | MIT |
public function __construct(array $config = [])
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'use_file_buffer' => true,
'memory_buffer_size' => 2097152,
]);
$resolver->setAllowedTypes('use_file_buffer', 'bool');
$resolver->setAllowedTypes('memory_buffer_size', 'int');
$options = $resolver->resolve($config);
$this->useFileBuffer = $options['use_file_buffer'];
$this->memoryBufferSize = $options['memory_buffer_size'];
} | @param array{'use_file_buffer'?: bool, 'memory_boffer_size'?: int} $config
Configuration options:
- use_file_buffer: Whether this plugin should use a file as a buffer if the stream is too big, defaults to true
- memory_buffer_size: Max memory size in bytes to use for the buffer before it use a file, defaults to 2097152 (2 mb) | __construct | php | php-http/client-common | src/Plugin/SeekableBodyPlugin.php | https://github.com/php-http/client-common/blob/master/src/Plugin/SeekableBodyPlugin.php | MIT |
public function __destruct()
{
if ($this->isOn) {
$this->turnOff();
}
} | Turns off this videorecorder when instance is destroyed.
@codeCoverageIgnore | __destruct | php | php-vcr/php-vcr | src/VCR/Videorecorder.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Videorecorder.php | MIT |
public function getHash()
{
return md5(serialize($this->toArray()));
} | Generate a string representation of the request.
@return string | getHash | php | php-vcr/php-vcr | src/VCR/Request.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Request.php | MIT |
public function __construct(string $cassettePath, string $cassetteName, string $defaultContent = '[]')
{
Assertion::directory($cassettePath, "Cassette path '{$cassettePath}' is not existing or not a directory");
$this->filePath = rtrim($cassettePath, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR.$cassetteName;
if (!is_dir(\dirname($this->filePath))) {
mkdir(\dirname($this->filePath), 0777, true);
}
if (!file_exists($this->filePath) || 0 === filesize($this->filePath)) {
file_put_contents($this->filePath, $defaultContent);
$this->isNew = true;
}
Assertion::file($this->filePath, "Specified path '{$this->filePath}' is not a file.");
Assertion::readable($this->filePath, "Specified file '{$this->filePath}' must be readable.");
$handle = fopen($this->filePath, 'r+');
Assertion::isResource($handle);
$this->handle = $handle;
} | If the cassetteName contains PATH_SEPARATORs, subfolders of the
cassettePath are autocreated when not existing. | __construct | php | php-vcr/php-vcr | src/VCR/Storage/AbstractStorage.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Storage/AbstractStorage.php | MIT |
private static function callFunction($callback, \CurlHandle $curlHandle, $argument)
{
if (!\is_callable($callback) && \is_array($callback) && 2 === \count($callback)) {
// This is probably a private or protected method on an object. Try and
// make it accessible.
$method = new \ReflectionMethod($callback[0], $callback[1]);
$method->setAccessible(true);
return $method->invoke($callback[0], $curlHandle, $argument);
} else {
return \call_user_func($callback, $curlHandle, $argument);
}
} | A wrapper around call_user_func that attempts to properly handle private
and protected methods on objects.
@param mixed $callback The callable to pass to call_user_func
@param mixed $argument The third argument to pass to call_user_func
@return mixed value returned by the callback function | callFunction | php | php-vcr/php-vcr | src/VCR/Util/CurlHelper.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/CurlHelper.php | MIT |
public function stream_read(int $count)
{
if (false === $this->resource) {
return false;
}
return fread($this->resource, $count);
} | Read from stream.
@see http://www.php.net/manual/en/streamwrapper.stream-read.php
@param int $count how many bytes of data from the current position should be returned
@return string|false If there are less than count bytes available, return as many as are available.
If no more data is available, return either FALSE or an empty string. | stream_read | php | php-vcr/php-vcr | src/VCR/Util/StreamProcessor.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/StreamProcessor.php | MIT |
public function stream_stat()
{
if (false === $this->resource) {
return false;
}
if (!$this->shouldProcess(stream_get_meta_data($this->resource)['uri'])) {
return fstat($this->resource);
}
return false;
} | Retrieve information about a file resource.
Do not return the stat since we don't know the resulting size that the file will have
after having all transformations applied. When including files, PHP 7.4 and newer are sensitive
to file size reported by stat.
@see http://www.php.net/manual/en/streamwrapper.stream-stat.php
@return array<int|string, int>|false see stat() | stream_stat | php | php-vcr/php-vcr | src/VCR/Util/StreamProcessor.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/StreamProcessor.php | MIT |
public function stream_tell()
{
if (false === $this->resource) {
return false;
}
return ftell($this->resource);
} | Retrieve the current position of a stream.
This method is called in response to fseek() to determine the current position.
@see http://www.php.net/manual/en/streamwrapper.stream-tell.php
@return int|false should return the current position of the stream | stream_tell | php | php-vcr/php-vcr | src/VCR/Util/StreamProcessor.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/StreamProcessor.php | MIT |
public function url_stat(string $path, int $flags)
{
$this->restore();
if ($flags & \STREAM_URL_STAT_QUIET) {
set_error_handler(function () {
// Use native error handler
return false;
});
$result = @stat($path);
restore_error_handler();
} else {
$result = stat($path);
}
$this->intercept();
return $result;
} | Retrieve information about a file.
@see http://www.php.net/manual/en/streamwrapper.url-stat.php
@param string $path the file path or URL to stat
@param int $flags holds additional flags set by the streams API
@return array<int|string, int>|false should return as many elements as stat() does | url_stat | php | php-vcr/php-vcr | src/VCR/Util/StreamProcessor.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/StreamProcessor.php | MIT |
public function dir_readdir()
{
if (false === $this->resource) {
return false;
}
return readdir($this->resource);
} | Read entry from directory handle.
@see http://www.php.net/manual/en/streamwrapper.dir-readdir.php
@return mixed should return string representing the next filename, or FALSE if there is no next file | dir_readdir | php | php-vcr/php-vcr | src/VCR/Util/StreamProcessor.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/StreamProcessor.php | MIT |
public function stream_cast(int $cast_as)
{
return $this->resource;
} | Retrieve the underlaying resource.
@see http://www.php.net/manual/en/streamwrapper.stream-cast.php
@param int $cast_as can be STREAM_CAST_FOR_SELECT when stream_select() is calling stream_cast() or
STREAM_CAST_AS_STREAM when stream_cast() is called for other uses
@return resource|false should return the underlying stream resource used by the wrapper, or FALSE | stream_cast | php | php-vcr/php-vcr | src/VCR/Util/StreamProcessor.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/Util/StreamProcessor.php | MIT |
public static function __callStatic($method, array $args)
{
// Call original when disabled
if (self::DISABLED == static::$status) {
if ('curl_multi_exec' === $method) {
// curl_multi_exec expects to be called with args by reference
// which call_user_func_array doesn't do.
return curl_multi_exec($args[0], $args[1]);
}
return \call_user_func_array($method, $args);
}
if ('curl_multi_exec' === $method) {
// curl_multi_exec expects to be called with args by reference
// which call_user_func_array doesn't do.
return self::curlMultiExec($args[0], $args[1]);
}
$localMethod = TextUtil::underscoreToLowerCamelcase($method);
$callable = [__CLASS__, $localMethod];
Assertion::isCallable($callable);
return \call_user_func_array($callable, $args);
} | Calls the intercepted curl method if library hook is disabled, otherwise the real one.
@param callable&string $method cURL method to call, example: curl_info()
@param array<int,mixed> $args cURL arguments for this function
@return mixed cURL function return type | __callStatic | php | php-vcr/php-vcr | src/VCR/LibraryHooks/CurlHook.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/LibraryHooks/CurlHook.php | MIT |
public static function curlExec(\CurlHandle $curlHandle)
{
try {
$request = self::$requests[(int) $curlHandle];
CurlHelper::validateCurlPOSTBody($request, $curlHandle);
$requestCallback = self::$requestCallback;
Assertion::isCallable($requestCallback);
self::$responses[(int) $curlHandle] = $requestCallback($request);
return CurlHelper::handleOutput(
self::$responses[(int) $curlHandle],
self::$curlOptions[(int) $curlHandle],
$curlHandle
);
} catch (CurlException $e) {
self::$lastErrors[(int) $curlHandle] = $e;
return false;
}
} | Perform a cURL session.
@see http://www.php.net/manual/en/function.curl-exec.php
@return mixed Returns TRUE on success or FALSE on failure.
However, if the CURLOPT_RETURNTRANSFER option is set, it will return the
result on success, FALSE on failure. | curlExec | php | php-vcr/php-vcr | src/VCR/LibraryHooks/CurlHook.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/LibraryHooks/CurlHook.php | MIT |
public static function curlMultiInfoRead()
{
if (!empty(self::$multiExecLastChs)) {
$info = [
'msg' => \CURLMSG_DONE,
'handle' => array_pop(self::$multiExecLastChs),
'result' => \CURLE_OK,
];
return $info;
}
return false;
} | Get information about the current transfers.
@see http://www.php.net/manual/en/function.curl-multi-info-read.php
@return array<string,mixed>|bool on success, returns an associative array for the message, FALSE on failure | curlMultiInfoRead | php | php-vcr/php-vcr | src/VCR/LibraryHooks/CurlHook.php | https://github.com/php-vcr/php-vcr/blob/master/src/VCR/LibraryHooks/CurlHook.php | MIT |
private function getParameterFromContext(array $context, string $parameterName, mixed $default = null)
{
$filters = $context['filters'] ?? [];
return \array_key_exists($parameterName, $filters) ? $filters[$parameterName] : $default;
} | Gets the given pagination parameter name from the given context. | getParameterFromContext | php | api-platform/core | src/State/Pagination/Pagination.php | https://github.com/api-platform/core/blob/master/src/State/Pagination/Pagination.php | MIT |
public function __construct(private readonly ManagerRegistry $doctrine, private readonly mixed $passwordHasher)
{
$this->manager = $doctrine->getManager();
$this->schemaTool = $this->manager instanceof EntityManagerInterface ? new SchemaTool($this->manager) : null;
$this->schemaManager = $this->manager instanceof DocumentManager ? $this->manager->getSchemaManager() : null;
} | Initializes context.
Every scenario gets its own context instance.
You can also pass arbitrary arguments to the
context constructor through behat.yml. | __construct | php | api-platform/core | tests/Behat/DoctrineContext.php | https://github.com/api-platform/core/blob/master/tests/Behat/DoctrineContext.php | MIT |
public function blocking($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'blocker', 'blockers', 'blocker_id', 'blockable_id')
->withPivot('blockable_type')
->wherePivot('blockable_type', $modelClass)
->wherePivot('blocker_type', $this->getMorphClass())
->withTimestamps();
} | Relationship for models that this model is currently blocking.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | blocking | php | renoki-co/befriended | src/Traits/CanBlock.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanBlock.php | Apache-2.0 |
public function following($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'follower', 'followers', 'follower_id', 'followable_id')
->withPivot(['followable_type', 'accepted'])
->wherePivot('followable_type', $modelClass)
->wherePivot('follower_type', $this->getMorphClass())
->wherePivot('accepted', true)
->withTimestamps();
} | Relationship for models that this model is currently following.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | following | php | renoki-co/befriended | src/Traits/CanFollow.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanFollow.php | Apache-2.0 |
public function followRequests($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'follower', 'followers', 'follower_id', 'followable_id')
->withPivot(['followable_type', 'accepted'])
->wherePivot('followable_type', $modelClass)
->wherePivot('follower_type', $this->getMorphClass())
->wherePivot('accepted', false)
->withTimestamps();
} | Relationship for models that this model currently has requests for.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | followRequests | php | renoki-co/befriended | src/Traits/CanFollow.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanFollow.php | Apache-2.0 |
public function followers($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'followable', 'followers', 'followable_id', 'follower_id')
->withPivot(['follower_type', 'accepted'])
->wherePivot('follower_type', $modelClass)
->wherePivot('followable_type', $this->getMorphClass())
->wherePivot('accepted', true)
->withTimestamps();
} | Relationship for models that followed this model.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | followers | php | renoki-co/befriended | src/Traits/CanBeFollowed.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanBeFollowed.php | Apache-2.0 |
public function followerRequests($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'followable', 'followers', 'followable_id', 'follower_id')
->withPivot(['follower_type', 'accepted'])
->wherePivot('follower_type', $modelClass)
->wherePivot('followable_type', $this->getMorphClass())
->wherePivot('accepted', false)
->withTimestamps();
} | Relationship for models that has requested to follow this model.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | followerRequests | php | renoki-co/befriended | src/Traits/CanBeFollowed.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanBeFollowed.php | Apache-2.0 |
public function likers($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'likeable', 'likers', 'likeable_id', 'liker_id')
->withPivot('liker_type')
->wherePivot('liker_type', $modelClass)
->wherePivot('likeable_type', $this->getMorphClass())
->withTimestamps();
} | Relationship for models that liked this model.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | likers | php | renoki-co/befriended | src/Traits/CanBeLiked.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanBeLiked.php | Apache-2.0 |
public function blockers($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'blockable', 'blockers', 'blockable_id', 'blocker_id')
->withPivot('blocker_type')
->wherePivot('blocker_type', $modelClass)
->wherePivot('blockable_type', $this->getMorphClass())
->withTimestamps();
} | Relationship for models that blocked this model.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | blockers | php | renoki-co/befriended | src/Traits/CanBeBlocked.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanBeBlocked.php | Apache-2.0 |
protected function getModelMorphClass($model = null)
{
return $model
? (new $model)->getMorphClass()
: $this->getCurrentModelMorphClass();
} | Get the model's morph class to act as the main resource.
@param string|null $model
@return string | getModelMorphClass | php | renoki-co/befriended | src/Traits/HasCustomModelClass.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/HasCustomModelClass.php | Apache-2.0 |
protected function getCurrentModelMorphClass()
{
return $this->getMorphClass();
} | Get the current model's morph class.
@return string | getCurrentModelMorphClass | php | renoki-co/befriended | src/Traits/HasCustomModelClass.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/HasCustomModelClass.php | Apache-2.0 |
public function liking($model = null)
{
$modelClass = $this->getModelMorphClass($model);
return $this
->morphToMany($modelClass, 'liker', 'likers', 'liker_id', 'likeable_id')
->withPivot('likeable_type')
->wherePivot('likeable_type', $modelClass)
->wherePivot('liker_type', $this->getMorphClass())
->withTimestamps();
} | Relationship for models that this model is currently liking.
@param null|\Illuminate\Database\Eloquent\Model $model
@return mixed | liking | php | renoki-co/befriended | src/Traits/CanLike.php | https://github.com/renoki-co/befriended/blob/master/src/Traits/CanLike.php | Apache-2.0 |
public function scopeWithoutBlockingsOf($query, $model)
{
if (! $model instanceof Blocker && ! $model instanceof Blocking) {
return $query;
}
$blockingsIds = $model
->blocking($this->getMorphClass())
->get()
->pluck($model->getKeyName())
->toArray();
return $query->whereNotIn(
$this->getKeyName(), $blockingsIds
);
} | Evict any records that the model blocked.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Illuminate\Database\Eloquent\Builder | scopeWithoutBlockingsOf | php | renoki-co/befriended | src/Scopes/BlockFilterable.php | https://github.com/renoki-co/befriended/blob/master/src/Scopes/BlockFilterable.php | Apache-2.0 |
public function scopeFilterBlockingsOf($query, $model)
{
return $this->scopeWithoutBlockingsOf($query, $model);
} | Alias to scopeWithoutBlockingsOf.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Illuminate\Database\Eloquent\Builder | scopeFilterBlockingsOf | php | renoki-co/befriended | src/Scopes/BlockFilterable.php | https://github.com/renoki-co/befriended/blob/master/src/Scopes/BlockFilterable.php | Apache-2.0 |
public function scopeLikedBy($query, $model)
{
if (! $model instanceof Liker && ! $model instanceof Liking) {
return $query;
}
$likedIds = $model
->liking($this->getMorphClass())
->get()
->pluck($model->getKeyName())
->toArray();
return $query->whereIn($this->getKeyName(), $likedIds);
} | Filter only records that the model liked.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Illuminate\Database\Eloquent\Builder | scopeLikedBy | php | renoki-co/befriended | src/Scopes/LikeFilterable.php | https://github.com/renoki-co/befriended/blob/master/src/Scopes/LikeFilterable.php | Apache-2.0 |
public function scopeNotLikedBy($query, $model)
{
if (! $model instanceof Liker && ! $model instanceof Liking) {
return $query;
}
$likedIds = $model
->liking($this->getMorphClass())
->get()
->pluck($model->getKeyName())
->toArray();
return $query->whereNotIn($this->getKeyName(), $likedIds);
} | Filter only records that the model did not like.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Illuminate\Database\Eloquent\Builder | scopeNotLikedBy | php | renoki-co/befriended | src/Scopes/LikeFilterable.php | https://github.com/renoki-co/befriended/blob/master/src/Scopes/LikeFilterable.php | Apache-2.0 |
public function scopeFollowedBy($query, $model)
{
if (! $model instanceof Follower && ! $model instanceof Following) {
return $query;
}
$followingIds = $model
->following($this->getMorphClass())
->get()
->pluck($model->getKeyName())
->toArray();
return $query->whereIn($this->getKeyName(), $followingIds);
} | Filter only records that the model followed.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Illuminate\Database\Eloquent\Builder | scopeFollowedBy | php | renoki-co/befriended | src/Scopes/FollowFilterable.php | https://github.com/renoki-co/befriended/blob/master/src/Scopes/FollowFilterable.php | Apache-2.0 |
public function scopeUnfollowedBy($query, $model)
{
if (! $model instanceof Follower && ! $model instanceof Following) {
return $query;
}
$followingIds = $model
->following($this->getMorphClass())
->get()
->pluck($model->getKeyName())
->toArray();
return $query->whereNotIn($this->getKeyName(), $followingIds);
} | Filter only records that the model did not follow.
@param \Illuminate\Database\Eloquent\Builder $query
@param \Illuminate\Database\Eloquent\Model $model
@return \Illuminate\Database\Eloquent\Builder | scopeUnfollowedBy | php | renoki-co/befriended | src/Scopes/FollowFilterable.php | https://github.com/renoki-co/befriended/blob/master/src/Scopes/FollowFilterable.php | Apache-2.0 |
public function followable()
{
return $this->morphTo();
} | The relationship for models that are followed by this model.
@return mixed | followable | php | renoki-co/befriended | src/Models/FollowerModel.php | https://github.com/renoki-co/befriended/blob/master/src/Models/FollowerModel.php | Apache-2.0 |
public function follower()
{
return $this->morphTo();
} | The relationship for models that follow this model.
@return mixed | follower | php | renoki-co/befriended | src/Models/FollowerModel.php | https://github.com/renoki-co/befriended/blob/master/src/Models/FollowerModel.php | Apache-2.0 |
public function blockable()
{
return $this->morphTo();
} | The relationship for models that are blocked by this model.
@return mixed | blockable | php | renoki-co/befriended | src/Models/BlockerModel.php | https://github.com/renoki-co/befriended/blob/master/src/Models/BlockerModel.php | Apache-2.0 |
public function blocker()
{
return $this->morphTo();
} | The relationship for models that block this model.
@return mixed | blocker | php | renoki-co/befriended | src/Models/BlockerModel.php | https://github.com/renoki-co/befriended/blob/master/src/Models/BlockerModel.php | Apache-2.0 |
public function likeable()
{
return $this->morphTo();
} | The relationship for models that are liked by this model.
@return mixed | likeable | php | renoki-co/befriended | src/Models/LikerModel.php | https://github.com/renoki-co/befriended/blob/master/src/Models/LikerModel.php | Apache-2.0 |
public function liker()
{
return $this->morphTo();
} | The relationship for models that like this model.
@return mixed | liker | php | renoki-co/befriended | src/Models/LikerModel.php | https://github.com/renoki-co/befriended/blob/master/src/Models/LikerModel.php | Apache-2.0 |
protected function getPackageProviders($app)
{
return [
\Rennokki\Befriended\BefriendedServiceProvider::class,
];
} | Get the package providers for tests.
@param mixed $app
@return array | getPackageProviders | php | renoki-co/befriended | tests/TestCase.php | https://github.com/renoki-co/befriended/blob/master/tests/TestCase.php | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.