code
stringlengths 31
1.39M
| docstring
stringlengths 23
16.8k
| func_name
stringlengths 1
126
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
166
| url
stringlengths 50
220
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
protected function configureAndRegisterClient(): void
{
$this->app->bind(ClientBuilder::class, function () {
$basePath = base_path();
$userConfig = $this->getUserConfig();
foreach (static::LARAVEL_SPECIFIC_OPTIONS as $laravelSpecificOptionName) {
unset($userConfig[$laravelSpecificOptionName]);
}
$options = \array_merge(
[
'prefixes' => [$basePath],
'in_app_exclude' => [
"{$basePath}/vendor",
"{$basePath}/artisan",
],
],
$userConfig
);
// When we get no environment from the (user) configuration we default to the Laravel environment
if (empty($options['environment'])) {
$options['environment'] = $this->app->environment();
}
if ($this->app instanceof Lumen) {
$wrapBeforeSend = function (?callable $userBeforeSend) {
return function (Event $event, ?EventHint $eventHint) use ($userBeforeSend) {
$request = $this->app->make(Request::class);
if ($request !== null) {
$route = $request->route();
if ($route !== null) {
[$routeName, $transactionSource] = Integration::extractNameAndSourceForLumenRoute($request->route(), $request->path());
$event->setTransaction($routeName);
$transactionMetadata = $event->getSdkMetadata('transaction_metadata');
if ($transactionMetadata instanceof TransactionMetadata) {
$transactionMetadata->setSource($transactionSource);
}
}
}
if ($userBeforeSend !== null) {
return $userBeforeSend($event, $eventHint);
}
return $event;
};
};
$options['before_send'] = $wrapBeforeSend($options['before_send'] ?? null);
$options['before_send_transaction'] = $wrapBeforeSend($options['before_send_transaction'] ?? null);
}
foreach (self::OPTIONS_TO_RESOLVE_FROM_CONTAINER as $option) {
if (isset($options[$option]) && is_string($options[$option])) {
$options[$option] = $this->app->make($options[$option]);
}
}
$clientBuilder = ClientBuilder::create($options);
// Set the Laravel SDK identifier and version
$clientBuilder->setSdkIdentifier(Version::SDK_IDENTIFIER);
$clientBuilder->setSdkVersion(Version::SDK_VERSION);
return $clientBuilder;
});
$this->app->singleton(HubInterface::class, function () {
/** @var \Sentry\ClientBuilder $clientBuilder */
$clientBuilder = $this->app->make(ClientBuilder::class);
$options = $clientBuilder->getOptions();
$userConfig = $this->getUserConfig();
/** @var array<array-key, class-string>|callable $userConfig */
$userIntegrationOption = $userConfig['integrations'] ?? [];
$userIntegrations = $this->resolveIntegrationsFromUserConfig(
\is_array($userIntegrationOption)
? $userIntegrationOption
: [],
$userConfig['tracing']['default_integrations'] ?? true
);
$options->setIntegrations(static function (array $integrations) use ($options, $userIntegrations, $userIntegrationOption): array {
if ($options->hasDefaultIntegrations()) {
// Remove the default error and fatal exception listeners to let Laravel handle those
// itself. These event are still bubbling up through the documented changes in the users
// `ExceptionHandler` of their application or through the log channel integration to Sentry
$integrations = array_filter($integrations, static function (SdkIntegration\IntegrationInterface $integration): bool {
if ($integration instanceof SdkIntegration\ErrorListenerIntegration) {
return false;
}
if ($integration instanceof SdkIntegration\ExceptionListenerIntegration) {
return false;
}
if ($integration instanceof SdkIntegration\FatalErrorListenerIntegration) {
return false;
}
// We also remove the default request integration so it can be readded
// after with a Laravel specific request fetcher. This way we can resolve
// the request from Laravel instead of constructing it from the global state
if ($integration instanceof SdkIntegration\RequestIntegration) {
return false;
}
return true;
});
$integrations[] = new SdkIntegration\RequestIntegration(
new LaravelRequestFetcher
);
}
$integrations = array_merge(
$integrations,
[
new Integration,
new Integration\LaravelContextIntegration,
new Integration\ExceptionContextIntegration,
],
$userIntegrations
);
if (\is_callable($userIntegrationOption)) {
return $userIntegrationOption($integrations);
}
return $integrations;
});
$hub = new Hub($clientBuilder->getClient());
SentrySdk::setCurrentHub($hub);
return $hub;
});
$this->app->alias(HubInterface::class, static::$abstract);
$this->app->singleton(BacktraceHelper::class, function () {
$sentry = $this->app->make(HubInterface::class);
$options = $sentry->getClient()->getOptions();
return new BacktraceHelper($options, new RepresentationSerializer($options));
});
} | Configure and register the Sentry client with the container. | configureAndRegisterClient | php | getsentry/sentry-laravel | src/Sentry/Laravel/ServiceProvider.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/ServiceProvider.php | MIT |
private function resolveIntegrationsFromUserConfig(array $userIntegrations, bool $enableDefaultTracingIntegrations): array
{
$integrationsToResolve = $userIntegrations;
if ($enableDefaultTracingIntegrations) {
$integrationsToResolve = array_merge($integrationsToResolve, TracingServiceProvider::DEFAULT_INTEGRATIONS);
}
$integrations = [];
foreach ($integrationsToResolve as $userIntegration) {
if ($userIntegration instanceof SdkIntegration\IntegrationInterface) {
$integrations[] = $userIntegration;
} elseif (\is_string($userIntegration)) {
$resolvedIntegration = $this->app->make($userIntegration);
if (!$resolvedIntegration instanceof SdkIntegration\IntegrationInterface) {
throw new RuntimeException(
sprintf(
'Sentry integrations must be an instance of `%s` got `%s`.',
SdkIntegration\IntegrationInterface::class,
get_class($resolvedIntegration)
)
);
}
$integrations[] = $resolvedIntegration;
} else {
throw new RuntimeException(
sprintf(
'Sentry integrations must either be a valid container reference or an instance of `%s`.',
SdkIntegration\IntegrationInterface::class
)
);
}
}
return $integrations;
} | Resolve the integrations from the user configuration with the container. | resolveIntegrationsFromUserConfig | php | getsentry/sentry-laravel | src/Sentry/Laravel/ServiceProvider.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/ServiceProvider.php | MIT |
public function provides()
{
return [static::$abstract];
} | Get the services provided by the provider.
@return array | provides | php | getsentry/sentry-laravel | src/Sentry/Laravel/ServiceProvider.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/ServiceProvider.php | MIT |
public function handle(): int
{
if (!\extension_loaded('curl')) {
$this->error('You need to enable the PHP cURL extension (ext-curl).');
return 1;
}
/**
* Maximize error reporting.
* 2048 is \E_STRICT which has been deprecated in PHP 8.4
*/
$old_error_reporting = error_reporting(E_ALL | 2048);
$dsn = $this->option('dsn');
$laravelClient = null;
try {
$laravelClient = app(HubInterface::class)->getClient();
} catch (Throwable $e) {
// Ignore any errors related to getting the client from the Laravel container
// These errors will surface later in the process but we should not crash here
}
// If the DSN was not passed as option to the command we use the registered client to get the DSN from the Laravel config
if ($dsn === null) {
$dsnObject = $laravelClient === null
? null
: $laravelClient->getOptions()->getDsn();
if ($dsnObject !== null) {
$dsn = (string)$dsnObject;
$this->info('DSN discovered from Laravel config or `.env` file!');
}
}
// No DSN found from the command line or config
if (!$dsn) {
$this->error('Could not discover DSN!');
$this->printDebugTips();
return 1;
}
$options = [
'dsn' => $dsn,
'before_send' => static function (Event $event): ?Event {
foreach ($event->getExceptions() as $exception) {
$stacktrace = $exception->getStacktrace();
if ($stacktrace === null) {
continue;
}
foreach ($stacktrace->getFrames() as $frame) {
if (str_starts_with($frame->getAbsoluteFilePath(), __DIR__)) {
$frame->setIsInApp(true);
}
}
}
return $event;
},
// We include this file as "in-app" so that the events generated have something to show
'in_app_include' => [__DIR__],
'in_app_exclude' => [base_path('artisan'), base_path('vendor')],
'traces_sample_rate' => 1.0,
];
if ($laravelClient !== null) {
// Some options are taken from the client as configured by the user
$options = array_merge($options, [
'release' => $laravelClient->getOptions()->getRelease(),
'environment' => $laravelClient->getOptions()->getEnvironment(),
'http_client' => $laravelClient->getOptions()->getHttpClient(),
'http_proxy' => $laravelClient->getOptions()->getHttpProxy(),
'http_proxy_authentication' => $laravelClient->getOptions()->getHttpProxyAuthentication(),
'http_connect_timeout' => $laravelClient->getOptions()->getHttpConnectTimeout(),
'http_timeout' => $laravelClient->getOptions()->getHttpTimeout(),
'http_ssl_verify_peer' => $laravelClient->getOptions()->getHttpSslVerifyPeer(),
'http_compression' => $laravelClient->getOptions()->isHttpCompressionEnabled(),
]);
}
try {
$clientBuilder = ClientBuilder::create($options);
} catch (Exception $e) {
$this->error($e->getMessage());
return 1;
}
// Set the Laravel SDK identifier and version
$clientBuilder->setSdkIdentifier(Version::SDK_IDENTIFIER);
$clientBuilder->setSdkVersion(Version::SDK_VERSION);
// We set a logger so we can surface errors thrown internally by the SDK
$clientBuilder->setLogger(new class($this) extends AbstractLogger {
private $command;
public function __construct(TestCommand $command)
{
$this->command = $command;
}
public function log($level, $message, array $context = []): void
{
// Only show debug, info and notice messages in verbose mode
$verbosity = in_array($level, ['debug', 'info', 'notice'], true)
? OutputInterface::VERBOSITY_VERBOSE
: OutputInterface::VERBOSITY_NORMAL;
$this->command->info("SDK({$level}): {$message}", $verbosity);
if (in_array($level, ['error', 'critical'], true)) {
$this->command->logErrorMessageFromSDK($message);
}
}
});
// We create a new Hub and Client to prevent user configuration from affecting the test command
$hub = new Hub($clientBuilder->getClient());
$this->info('Sending test event...');
$exception = $this->generateTestException($this->name, ['foo' => 'bar']);
$eventId = $hub->captureException($exception);
if (!$eventId) {
$this->error('There was an error sending the event.');
$this->printDebugTips();
return 1;
}
$this->info("Test event sent with ID: {$eventId}");
if ($this->option('transaction')) {
$this->clearErrorMessagesFromSDK();
$transaction = $hub->startTransaction(
TransactionContext::make()
->setOp('sentry.test')
->setName('Sentry Test Transaction')
->setOrigin('auto.test.transaction')
->setSource(TransactionSource::custom())
->setSampled(true)
);
$span = $transaction->startChild(
SpanContext::make()
->setOp('sentry.sent')
->setOrigin('auto.test.span')
);
$this->info('Sending transaction...');
$span->finish();
$transactionId = $transaction->finish();
if (!$transactionId) {
$this->error('There was an error sending the transaction.');
$this->printDebugTips();
return 1;
}
$this->info("Transaction sent with ID: {$transactionId}");
}
error_reporting($old_error_reporting);
return 0;
} | Execute the console command.
@return int | handle | php | getsentry/sentry-laravel | src/Sentry/Laravel/Console/TestCommand.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Console/TestCommand.php | MIT |
protected function generateTestException(string $command, array $arg): Exception
{
// Do something silly
try {
throw new Exception('This is a test exception sent from the Sentry Laravel SDK.');
} catch (Exception $exception) {
return $exception;
}
} | Generate an example exception to send to Sentry. | generateTestException | php | getsentry/sentry-laravel | src/Sentry/Laravel/Console/TestCommand.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Console/TestCommand.php | MIT |
private function normalizeKeyOrKeys($keyOrKeys): array
{
if (is_string($keyOrKeys)) {
return [$keyOrKeys];
}
return collect($keyOrKeys)->map(function ($value, $key) {
return is_string($key) ? $key : $value;
})->values()->all();
} | Normalize the array of keys to a array of only strings.
@param string|string[]|array<array-key, mixed> $keyOrKeys
@return string[] | normalizeKeyOrKeys | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/CacheIntegration.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/CacheIntegration.php | MIT |
private function extractConsoleCommandInput(?InputInterface $input): ?string
{
if ($input instanceof ArgvInput) {
return (string)$input;
}
return null;
} | Extract the command input arguments if possible.
@param \Symfony\Component\Console\Input\InputInterface|null $input
@return string|null | extractConsoleCommandInput | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/ConsoleIntegration.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/ConsoleIntegration.php | MIT |
public function __construct(Container $container)
{
$this->container = $container;
} | @param Container $container The Laravel application container. | __construct | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
public function register(): void
{
// ...
} | Register the feature in the environment. | register | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
public function bootInactive(): void
{
if (method_exists($this, 'onBootInactive') && $this->isApplicable()) {
try {
$this->container->call([$this, 'onBootInactive']);
} catch (Throwable $exception) {
// If the feature setup fails, we don't want to prevent the rest of the SDK from working.
}
}
} | Initialize the feature in an inactive state (when no DSN was set). | bootInactive | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
protected function container(): Container
{
return $this->container;
} | Retrieve the Laravel application container.
@return Container | container | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
protected function getUserConfig(): array
{
$config = $this->container['config'][BaseServiceProvider::$abstract];
return empty($config) ? [] : $config;
} | Retrieve the user configuration.
@return array | getUserConfig | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
protected function shouldSendDefaultPii(): bool
{
$client = SentrySdk::getCurrentHub()->getClient();
if ($client === null) {
return false;
}
return $client->getOptions()->shouldSendDefaultPii();
} | Should default PII be sent by default. | shouldSendDefaultPii | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
protected function isTracingFeatureEnabled(string $feature, bool $default = true): bool
{
if (!array_key_exists($feature, $this->isTracingFeatureEnabled)) {
$this->isTracingFeatureEnabled[$feature] = $this->isFeatureEnabled('tracing', $feature, $default);
}
return $this->isTracingFeatureEnabled[$feature];
} | Indicates if the given feature is enabled for tracing. | isTracingFeatureEnabled | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
protected function isBreadcrumbFeatureEnabled(string $feature, bool $default = true): bool
{
if (!array_key_exists($feature, $this->isBreadcrumbFeatureEnabled)) {
$this->isBreadcrumbFeatureEnabled[$feature] = $this->isFeatureEnabled('breadcrumbs', $feature, $default);
}
return $this->isBreadcrumbFeatureEnabled[$feature];
} | Indicates if the given feature is enabled for breadcrumbs. | isBreadcrumbFeatureEnabled | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
private function isFeatureEnabled(string $category, string $feature, bool $default): bool
{
$config = $this->getUserConfig()[$category] ?? [];
return ($config[$feature] ?? $default) === true;
} | Helper to test if a certain feature is enabled in the user config. | isFeatureEnabled | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Feature.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Feature.php | MIT |
private function getFullUri(string $url): UriInterface
{
return new Uri($url);
} | Construct a full URI.
@param string $url
@return UriInterface | getFullUri | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/HttpClientIntegration.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/HttpClientIntegration.php | MIT |
private function getPartialUri(UriInterface $uri): string
{
return (string)Uri::fromParts([
'scheme' => $uri->getScheme(),
'host' => $uri->getHost(),
'port' => $uri->getPort(),
'path' => $uri->getPath(),
]);
} | Construct a partial URI, excluding the authority, query and fragment parts.
@param UriInterface $uri
@return string | getPartialUri | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/HttpClientIntegration.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/HttpClientIntegration.php | MIT |
protected function withParentSpanIfSampled(callable $callback): void
{
$parentSpan = $this->getParentSpanIfSampled();
if ($parentSpan === null) {
return;
}
$callback($parentSpan);
} | @param callable(Span $parentSpan): void $callback | withParentSpanIfSampled | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Concerns/WorksWithSpans.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Concerns/WorksWithSpans.php | MIT |
protected function withSentry(string $method, array $args, ?string $description, array $data)
{
$op = "file.{$method}"; // See https://develop.sentry.dev/sdk/performance/span-operations/#web-server
$data = array_merge($data, $this->defaultData);
if ($this->recordBreadcrumbs) {
Integration::addBreadcrumb(new Breadcrumb(
Breadcrumb::LEVEL_INFO,
Breadcrumb::TYPE_DEFAULT,
$op,
$description,
$data
));
}
if ($this->recordSpans) {
return trace(
function () use ($method, $args) {
return $this->filesystem->{$method}(...$args);
},
SpanContext::make()
->setOp($op)
->setData($data)
->setOrigin('auto.filesystem')
->setDescription($description)
);
}
return $this->filesystem->{$method}(...$args);
} | Execute the method on the underlying filesystem and wrap it with tracing and log a breadcrumb.
@param list<mixed> $args
@param array<string, mixed> $data
@return mixed | withSentry | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Storage/FilesystemDecorator.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Storage/FilesystemDecorator.php | MIT |
public static function configureDisk(string $diskName, array $diskConfig, bool $enableSpans = true, bool $enableBreadcrumbs = true): array
{
$currentDriver = $diskConfig['driver'];
if ($currentDriver !== self::STORAGE_DRIVER_NAME) {
$diskConfig['driver'] = self::STORAGE_DRIVER_NAME;
$diskConfig['sentry_disk_name'] = $diskName;
$diskConfig['sentry_original_driver'] = $currentDriver;
$diskConfig['sentry_enable_spans'] = $enableSpans;
$diskConfig['sentry_enable_breadcrumbs'] = $enableBreadcrumbs;
}
return $diskConfig;
} | Decorates the configuration for a single disk with Sentry driver configuration.
This replaces the driver with a custom driver that will capture performance traces and breadcrumbs.
The custom driver will be an instance of @see \Sentry\Laravel\Features\Storage\SentryS3V3Adapter
if the original driver is an @see \Illuminate\Filesystem\AwsS3V3Adapter,
and an instance of @see \Sentry\Laravel\Features\Storage\SentryFilesystemAdapter
if the original driver is an @see \Illuminate\Filesystem\FilesystemAdapter.
If the original driver is neither of those, it will be @see \Sentry\Laravel\Features\Storage\SentryFilesystem
or @see \Sentry\Laravel\Features\Storage\SentryCloudFilesystem based on the contract of the original driver.
You might run into problems if you expect another specific driver class.
@param array<string, mixed> $diskConfig
@return array<string, mixed> | configureDisk | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Storage/Integration.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Storage/Integration.php | MIT |
public static function configureDisks(array $diskConfigs, bool $enableSpans = true, bool $enableBreadcrumbs = true): array
{
$diskConfigsWithSentryDriver = [];
foreach ($diskConfigs as $diskName => $diskConfig) {
$diskConfigsWithSentryDriver[$diskName] = static::configureDisk($diskName, $diskConfig, $enableSpans, $enableBreadcrumbs);
}
return $diskConfigsWithSentryDriver;
} | Decorates the configuration for all disks with Sentry driver configuration.
@see self::configureDisk()
@param array<string, array<string, mixed>> $diskConfigs
@return array<string, array<string, mixed>> | configureDisks | php | getsentry/sentry-laravel | src/Sentry/Laravel/Features/Storage/Integration.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Features/Storage/Integration.php | MIT |
public function handle(Request $request, Closure $next)
{
$container = Container::getInstance();
if ($container->bound(HubInterface::class)) {
/** @var \Sentry\State\HubInterface $sentry */
$sentry = $container->make(HubInterface::class);
$client = $sentry->getClient();
if ($client !== null && $client->getOptions()->shouldSendDefaultPii()) {
$sentry->configureScope(static function (Scope $scope) use ($request): void {
$scope->setUser([
'ip_address' => $request->ip(),
]);
});
}
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | handle | php | getsentry/sentry-laravel | src/Sentry/Laravel/Http/SetRequestIpMiddleware.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Http/SetRequestIpMiddleware.php | MIT |
public function __invoke(Model $model, $propertyOrProperties): void
{
$property = is_array($propertyOrProperties)
? implode(', ', $propertyOrProperties)
: $propertyOrProperties;
if (!$this->shouldReport($model, $property)) {
return;
}
$this->markAsReported($model, $property);
$origin = $this->resolveEventOrigin();
if ($this->reportAfterResponse) {
app()->terminating(function () use ($model, $property, $origin) {
$this->report($model, $property, $origin);
});
} else {
$this->report($model, $property, $origin);
}
} | @param string|array<int, string> $propertyOrProperties | __invoke | php | getsentry/sentry-laravel | src/Sentry/Laravel/Integration/ModelViolations/ModelViolationReporter.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Integration/ModelViolations/ModelViolationReporter.php | MIT |
public function setBatchFormatter(FormatterInterface $formatter): self
{
$this->batchFormatter = $formatter;
return $this;
} | Sets the formatter for the logs generated by handleBatch().
@param FormatterInterface $formatter
@return \Sentry\Laravel\SentryHandler | setBatchFormatter | php | getsentry/sentry-laravel | src/Sentry/Laravel/Logs/LogsHandler.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Logs/LogsHandler.php | MIT |
public function getBatchFormatter(): FormatterInterface
{
if (!$this->batchFormatter) {
$this->batchFormatter = new LineFormatter();
}
return $this->batchFormatter;
} | Gets the formatter for the logs generated by handleBatch(). | getBatchFormatter | php | getsentry/sentry-laravel | src/Sentry/Laravel/Logs/LogsHandler.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Logs/LogsHandler.php | MIT |
public function __construct(Options $options, RepresentationSerializerInterface $representationSerializer)
{
$this->options = $options;
$this->frameBuilder = new FrameBuilder($options, $representationSerializer);
} | Constructor.
@param Options $options The SDK client options
@param RepresentationSerializerInterface $representationSerializer The representation serializer | __construct | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/BacktraceHelper.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/BacktraceHelper.php | MIT |
public function findFirstInAppFrameForBacktrace(array $backtrace): ?Frame
{
$file = Frame::INTERNAL_FRAME_FILENAME;
$line = 0;
foreach ($backtrace as $backtraceFrame) {
$frame = $this->frameBuilder->buildFromBacktraceFrame($file, $line, $backtraceFrame);
if ($frame->isInApp()) {
return $frame;
}
$file = $backtraceFrame['file'] ?? Frame::INTERNAL_FRAME_FILENAME;
$line = $backtraceFrame['line'] ?? 0;
}
return null;
} | Find the first in app frame for a given backtrace.
@param array<int, array<string, mixed>> $backtrace The backtrace
@phpstan-param list<array{
line?: integer,
file?: string,
}> $backtrace | findFirstInAppFrameForBacktrace | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/BacktraceHelper.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/BacktraceHelper.php | MIT |
public function getOriginalViewPathForFrameOfCompiledViewPath(Frame $frame): ?string
{
// Check if we are dealing with a frame for a cached view path
if (!Str::startsWith($frame->getFile(), '/storage/framework/views/')) {
return null;
}
// If for some reason the file does not exists, skip resolving
if (!file_exists($frame->getAbsoluteFilePath())) {
return null;
}
$viewFileContents = file_get_contents($frame->getAbsoluteFilePath());
preg_match('/PATH (?<originalPath>.*?) ENDPATH/', $viewFileContents, $matches);
// No path comment found in the file, must be a very old Laravel version
if (empty($matches['originalPath'])) {
return null;
}
return $this->stripPrefixFromFilePath($matches['originalPath']);
} | Takes a frame and if it's a compiled view path returns the original view path.
@param \Sentry\Frame $frame
@return string|null | getOriginalViewPathForFrameOfCompiledViewPath | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/BacktraceHelper.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/BacktraceHelper.php | MIT |
private function stripPrefixFromFilePath(string $filePath): string
{
foreach ($this->options->getPrefixes() as $prefix) {
if (Str::startsWith($filePath, $prefix)) {
return mb_substr($filePath, mb_strlen($prefix));
}
}
return $filePath;
} | Removes from the given file path the specified prefixes.
@param string $filePath The path to the file | stripPrefixFromFilePath | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/BacktraceHelper.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/BacktraceHelper.php | MIT |
public function __call(string $method, array $arguments)
{
$handlerMethod = "{$method}Handler";
if (!method_exists($this, $handlerMethod)) {
throw new RuntimeException("Missing tracing event handler: {$handlerMethod}");
}
try {
$this->{$handlerMethod}(...$arguments);
} catch (Exception $e) {
// Ignore to prevent bubbling up errors in the SDK
}
} | Pass through the event and capture any errors.
@param string $method
@param array $arguments | __call | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/EventHandler.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/EventHandler.php | MIT |
public function handle(Request $request, Closure $next)
{
if (app()->bound(HubInterface::class)) {
$this->startTransaction($request);
}
return $next($request);
} | Handle an incoming request.
@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed | handle | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/Middleware.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/Middleware.php | MIT |
public function terminate(Request $request, $response): void
{
// If there is no transaction there is nothing for us to do
if ($this->transaction === null) {
return;
}
if ($this->shouldRouteBeIgnored($request)) {
$this->discardTransaction();
return;
}
if ($this->appSpan !== null) {
$this->appSpan->finish();
$this->appSpan = null;
}
if ($response instanceof SymfonyResponse) {
$this->hydrateResponseData($response);
}
if ($this->continueAfterResponse) {
// Resolving the transaction finisher class will register the terminating callback
// which is responsible for calling `finishTransaction`. We have registered the
// class as a singleton to keep the state in the container and away from here
// this way we ensure the callback is only registered once even for Octane.
app(TransactionFinisher::class);
} else {
$this->finishTransaction();
}
} | Handle the application termination.
@param \Illuminate\Http\Request $request
@param mixed $response
@return void | terminate | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/Middleware.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/Middleware.php | MIT |
public function setBootedTimestamp(?float $timestamp = null): void
{
$this->bootedTimestamp = $timestamp ?? microtime(true);
} | Set the timestamp of application bootstrap completion.
@param float|null $timestamp The unix timestamp of the booted event, default to `microtime(true)` if not `null`.
@return void
@internal This method should only be invoked right after the application has finished "booting". | setBootedTimestamp | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/Middleware.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/Middleware.php | MIT |
private function shouldRouteBeIgnored(Request $request): bool
{
// Laravel Lumen doesn't use `illuminate/routing`.
// Instead we use the route available on the request to detect if a route was matched.
if (app() instanceof LumenApplication) {
return $request->route() === null && config('sentry.tracing.missing_routes', false) === false;
}
// If a route has not been matched we ignore unless we are configured to trace missing routes
return !$this->didRouteMatch && config('sentry.tracing.missing_routes', false) === false;
} | Indicates if the route should be ignored and the transaction discarded. | shouldRouteBeIgnored | php | getsentry/sentry-laravel | src/Sentry/Laravel/Tracing/Middleware.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Tracing/Middleware.php | MIT |
public static function toHuman(int $bytes, int $decimals = 2): string
{
$size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$factor = (int)floor((strlen($bytes) - 1) / 3);
if ($factor === 0) {
$decimals = 0;
}
return sprintf("%.{$decimals}f %s", $bytes / (1024 ** $factor), $size[$factor]);
} | Convert bytes to human readable format.
Credit: https://stackoverflow.com/a/23888858/1580028
@param int $bytes The amount of bytes to convert to human readable format.
@param int $decimals The number of decimals to use in the resulting string.
@return string | toHuman | php | getsentry/sentry-laravel | src/Sentry/Laravel/Util/Filesize.php | https://github.com/getsentry/sentry-laravel/blob/master/src/Sentry/Laravel/Util/Filesize.php | MIT |
protected function getCurrentSentryBreadcrumbs(): array
{
$scope = $this->getCurrentSentryScope();
$property = new ReflectionProperty($scope, 'breadcrumbs');
$property->setAccessible(true);
return $property->getValue($scope);
} | @return array<array-key, \Sentry\Breadcrumb> | getCurrentSentryBreadcrumbs | php | getsentry/sentry-laravel | test/Sentry/TestCase.php | https://github.com/getsentry/sentry-laravel/blob/master/test/Sentry/TestCase.php | MIT |
protected function getCapturedSentryEvents(): array
{
return self::$lastSentryEvents;
} | @return array<int, array{0: Event, 1: EventHint|null}> | getCapturedSentryEvents | php | getsentry/sentry-laravel | test/Sentry/TestCase.php | https://github.com/getsentry/sentry-laravel/blob/master/test/Sentry/TestCase.php | MIT |
public function testScheduleMacroWithTimeZone(): void
{
$expectedTimezone = 'UTC';
/** @var Event $scheduledEvent */
$scheduledEvent = $this->getScheduler()
->call(function () {})
->timezone(new DateTimeZone($expectedTimezone))
->sentryMonitor('test-timezone-monitor');
$scheduledEvent->run($this->app);
// We expect a total of 2 events to be sent to Sentry:
// 1. The start check-in event
// 2. The finish check-in event
$this->assertSentryCheckInCount(2);
$finishCheckInEvent = $this->getLastSentryEvent();
$this->assertNotNull($finishCheckInEvent->getCheckIn());
$this->assertEquals($expectedTimezone, $finishCheckInEvent->getCheckIn()->getMonitorConfig()->getTimezone());
} | When a timezone was defined on a command this would fail with:
Sentry\MonitorConfig::__construct(): Argument #4 ($timezone) must be of type ?string, DateTimeZone given
This test ensures that the timezone is properly converted to a string as expected. | testScheduleMacroWithTimeZone | php | getsentry/sentry-laravel | test/Sentry/Features/ConsoleSchedulingIntegrationTest.php | https://github.com/getsentry/sentry-laravel/blob/master/test/Sentry/Features/ConsoleSchedulingIntegrationTest.php | MIT |
public function toResponse($request)
{
return Response::make($this->render(), 200, [
'Content-Type' => 'text/xml',
]);
} | Create an HTTP response that represents the object.
@param \Illuminate\Http\Request $request
@return \Symfony\Component\HttpFoundation\Response | toResponse | php | spatie/laravel-sitemap | src/Sitemap.php | https://github.com/spatie/laravel-sitemap/blob/master/src/Sitemap.php | MIT |
public function toResponse($request)
{
return Response::make($this->render(), 200, [
'Content-Type' => 'text/xml',
]);
} | Create an HTTP response that represents the object.
@param \Illuminate\Http\Request $request
@return \Symfony\Component\HttpFoundation\Response | toResponse | php | spatie/laravel-sitemap | src/SitemapIndex.php | https://github.com/spatie/laravel-sitemap/blob/master/src/SitemapIndex.php | MIT |
public function crawled(
UriInterface $url,
ResponseInterface $response,
?UriInterface $foundOnUrl = null,
?string $linkText = null,
): void {
($this->hasCrawled)($url, $response);
} | Called when the crawler has crawled the given url successfully.
@param \Psr\Http\Message\UriInterface $url
@param \Psr\Http\Message\ResponseInterface $response
@param \Psr\Http\Message\UriInterface|null $foundOnUrl | crawled | php | spatie/laravel-sitemap | src/Crawler/Observer.php | https://github.com/spatie/laravel-sitemap/blob/master/src/Crawler/Observer.php | MIT |
public function crawlFailed(
UriInterface $url,
RequestException $requestException,
?UriInterface $foundOnUrl = null,
?string $linkText = null,
): void {
} | Called when the crawler had a problem crawling the given url.
@param \Psr\Http\Message\UriInterface $url
@param \GuzzleHttp\Exception\RequestException $requestException
@param \Psr\Http\Message\UriInterface|null $foundOnUrl | crawlFailed | php | spatie/laravel-sitemap | src/Crawler/Observer.php | https://github.com/spatie/laravel-sitemap/blob/master/src/Crawler/Observer.php | MIT |
public static function unwrap(array $values): array
{
foreach ($values as $k => $v) {
if ($v instanceof self) {
$values[$k] = $v->__toString();
} elseif (\is_array($v) && $values[$k] !== $v = static::unwrap($v)) {
$values[$k] = $v;
}
}
return $values;
} | Unwraps instances of AbstractString back to strings.
@return string[]|array | unwrap | php | symfony/string | AbstractString.php | https://github.com/symfony/string/blob/master/AbstractString.php | MIT |
public static function wrap(array $values): array
{
$i = 0;
$keys = null;
foreach ($values as $k => $v) {
if (\is_string($k) && '' !== $k && $k !== $j = (string) new static($k)) {
$keys ??= array_keys($values);
$keys[$i] = $j;
}
if (\is_string($v)) {
$values[$k] = new static($v);
} elseif (\is_array($v) && $values[$k] !== $v = static::wrap($v)) {
$values[$k] = $v;
}
++$i;
}
return null !== $keys ? array_combine($keys, $values) : $values;
} | Wraps (and normalizes) strings in instances of AbstractString.
@return static[]|array | wrap | php | symfony/string | AbstractString.php | https://github.com/symfony/string/blob/master/AbstractString.php | MIT |
public function localeLower(string $locale): static
{
if (null !== $transliterator = $this->getLocaleTransliterator($locale, 'Lower')) {
$str = clone $this;
$str->string = $transliterator->transliterate($str->string);
return $str;
}
return $this->lower();
} | @param string $locale In the format language_region (e.g. tr_TR) | localeLower | php | symfony/string | AbstractUnicodeString.php | https://github.com/symfony/string/blob/master/AbstractUnicodeString.php | MIT |
public function localeTitle(string $locale): static
{
if (null !== $transliterator = $this->getLocaleTransliterator($locale, 'Title')) {
$str = clone $this;
$str->string = $transliterator->transliterate($str->string);
return $str;
}
return $this->title();
} | @param string $locale In the format language_region (e.g. tr_TR) | localeTitle | php | symfony/string | AbstractUnicodeString.php | https://github.com/symfony/string/blob/master/AbstractUnicodeString.php | MIT |
public function localeUpper(string $locale): static
{
if (null !== $transliterator = $this->getLocaleTransliterator($locale, 'Upper')) {
$str = clone $this;
$str->string = $transliterator->transliterate($str->string);
return $str;
}
return $this->upper();
} | @param string $locale In the format language_region (e.g. tr_TR) | localeUpper | php | symfony/string | AbstractUnicodeString.php | https://github.com/symfony/string/blob/master/AbstractUnicodeString.php | MIT |
private function wcswidth(string $string): int
{
$width = 0;
foreach (preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) {
$codePoint = mb_ord($c, 'UTF-8');
if (0 === $codePoint // NULL
|| 0x034F === $codePoint // COMBINING GRAPHEME JOINER
|| (0x200B <= $codePoint && 0x200F >= $codePoint) // ZERO WIDTH SPACE to RIGHT-TO-LEFT MARK
|| 0x2028 === $codePoint // LINE SEPARATOR
|| 0x2029 === $codePoint // PARAGRAPH SEPARATOR
|| (0x202A <= $codePoint && 0x202E >= $codePoint) // LEFT-TO-RIGHT EMBEDDING to RIGHT-TO-LEFT OVERRIDE
|| (0x2060 <= $codePoint && 0x2063 >= $codePoint) // WORD JOINER to INVISIBLE SEPARATOR
) {
continue;
}
// Non printable characters
if (32 > $codePoint // C0 control characters
|| (0x07F <= $codePoint && 0x0A0 > $codePoint) // C1 control characters and DEL
) {
return -1;
}
self::$tableZero ??= require __DIR__.'/Resources/data/wcswidth_table_zero.php';
if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) {
$lbound = 0;
while ($ubound >= $lbound) {
$mid = floor(($lbound + $ubound) / 2);
if ($codePoint > self::$tableZero[$mid][1]) {
$lbound = $mid + 1;
} elseif ($codePoint < self::$tableZero[$mid][0]) {
$ubound = $mid - 1;
} else {
continue 2;
}
}
}
self::$tableWide ??= require __DIR__.'/Resources/data/wcswidth_table_wide.php';
if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) {
$lbound = 0;
while ($ubound >= $lbound) {
$mid = floor(($lbound + $ubound) / 2);
if ($codePoint > self::$tableWide[$mid][1]) {
$lbound = $mid + 1;
} elseif ($codePoint < self::$tableWide[$mid][0]) {
$ubound = $mid - 1;
} else {
$width += 2;
continue 2;
}
}
}
++$width;
}
return $width;
} | Based on https://github.com/jquast/wcwidth, a Python implementation of https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c. | wcswidth | php | symfony/string | AbstractUnicodeString.php | https://github.com/symfony/string/blob/master/AbstractUnicodeString.php | MIT |
public static function fromCallable(callable|array $callback, mixed ...$arguments): static
{
if (\is_array($callback) && !\is_callable($callback) && !(($callback[0] ?? null) instanceof \Closure || 2 < \count($callback))) {
throw new \TypeError(\sprintf('Argument 1 passed to "%s()" must be a callable or a [Closure, method] lazy-callable, "%s" given.', __METHOD__, '['.implode(', ', array_map('get_debug_type', $callback)).']'));
}
$lazyString = new static();
$lazyString->value = static function () use (&$callback, &$arguments): string {
static $value;
if (null !== $arguments) {
if (!\is_callable($callback)) {
$callback[0] = $callback[0]();
$callback[1] ??= '__invoke';
}
$value = $callback(...$arguments);
$callback = !\is_scalar($value) && !$value instanceof \Stringable ? self::getPrettyName($callback) : 'callable';
$arguments = null;
}
return $value ?? '';
};
return $lazyString;
} | @param callable|array $callback A callable or a [Closure, method] lazy-callable | fromCallable | php | symfony/string | LazyString.php | https://github.com/symfony/string/blob/master/LazyString.php | MIT |
final public static function isStringable(mixed $value): bool
{
return \is_string($value) || $value instanceof \Stringable || \is_scalar($value);
} | Tells whether the provided value can be cast to string. | isStringable | php | symfony/string | LazyString.php | https://github.com/symfony/string/blob/master/LazyString.php | MIT |
final public static function resolve(\Stringable|string|int|float|bool $value): string
{
return $value;
} | Casts scalars and stringable objects to strings.
@throws \TypeError When the provided value is not stringable | resolve | php | symfony/string | LazyString.php | https://github.com/symfony/string/blob/master/LazyString.php | MIT |
public function withEmoji(bool|string $emoji = true): static
{
if (false !== $emoji && !class_exists(EmojiTransliterator::class)) {
throw new \LogicException(\sprintf('You cannot use the "%s()" method as the "symfony/emoji" package is not installed. Try running "composer require symfony/emoji".', __METHOD__));
}
$new = clone $this;
$new->emoji = $emoji;
return $new;
} | @param bool|string $emoji true will use the same locale,
false will disable emoji,
and a string to use a specific locale | withEmoji | php | symfony/string | Slugger/AsciiSlugger.php | https://github.com/symfony/string/blob/master/Slugger/AsciiSlugger.php | MIT |
public static function resolve(): Application
{
/** @var non-empty-string $workingPath */
$workingPath = getcwd();
if (! defined('TESTBENCH_WORKING_PATH')) {
define('TESTBENCH_WORKING_PATH', $workingPath);
}
$composerConfig = ComposerHelper::getComposerConfig($workingPath);
if ($composerConfig) {
$vendorDir = ComposerHelper::getVendorDirFromComposerConfig($workingPath, $composerConfig);
} else {
$vendorDir = $workingPath . '/vendor';
}
$resolvingCallback = static function ($app): void {
$packageManifest = $app->make(PackageManifest::class);
if (file_exists($packageManifest->manifestPath)) {
return;
}
$packageManifest->build();
};
if (class_exists(Config::class)) {
$config = Config::loadFromYaml($workingPath);
self::createSymlinkToVendorPath(Testbench::create($config['laravel'], null, ['extra' => ['dont-discover' => ['*']]]), $vendorDir);
return Testbench::create(
$config['laravel'],
$resolvingCallback,
['enables_package_discoveries' => true, 'extra' => $config->getExtraAttributes()],
);
}
self::createSymlinkToVendorPath(Testbench::create(Testbench::applicationBasePath(), null, ['extra' => ['dont-discover' => ['*']]]), $vendorDir);
return Testbench::create(
null,
$resolvingCallback,
['enables_package_discoveries' => true],
);
} | Creates an application and registers service providers found.
@throws ReflectionException | resolve | php | larastan/larastan | src/ApplicationResolver.php | https://github.com/larastan/larastan/blob/master/src/ApplicationResolver.php | MIT |
private function processNodes(array $nodes): array
{
$nodes = array_filter($nodes, static function (Node $node) {
return $node instanceof Node\Stmt\InlineHTML;
});
if (count($nodes) === 0) {
return [];
}
$usedViews = [];
foreach ($nodes as $node) {
preg_match_all(self::VIEW_NAME_REGEX, $node->value, $matches, PREG_SET_ORDER, 0);
$usedViews = array_merge($usedViews, array_map(static function ($match) {
return $match[5];
}, $matches));
}
return $usedViews;
} | @param Node\Stmt[] $nodes
@return list<string> | processNodes | php | larastan/larastan | src/Collectors/UsedViewInAnotherViewCollector.php | https://github.com/larastan/larastan/blob/master/src/Collectors/UsedViewInAnotherViewCollector.php | MIT |
public function resolve(string $abstract): mixed
{
try {
$concrete = $this->getContainer()->make($abstract);
} catch (Throwable) {
return null;
}
return $concrete;
} | Resolve the given type from the container. | resolve | php | larastan/larastan | src/Concerns/HasContainer.php | https://github.com/larastan/larastan/blob/master/src/Concerns/HasContainer.php | MIT |
public function searchOnEloquentBuilder(ClassReflection $eloquentBuilder, string $methodName, Type $modelType): MethodReflection|null
{
// Check for macros first
if ($this->macroMethodsClassReflectionExtension->hasMethod($eloquentBuilder, $methodName)) {
return $this->macroMethodsClassReflectionExtension->getMethod($eloquentBuilder, $methodName);
}
$scopeName = 'scope' . ucfirst($methodName);
foreach ($modelType->getObjectClassReflections() as $reflection) {
// Check for Scope attribute
if ($reflection->hasNativeMethod($methodName)) {
$methodReflection = $reflection->getNativeMethod($methodName);
$hasScopeAttribute = false;
foreach ($methodReflection->getAttributes() as $attribute) {
// using string instead of class constant to avoid failing on older Laravel versions
if ($attribute->getName() === 'Illuminate\Database\Eloquent\Attributes\Scope') {
$hasScopeAttribute = true;
break;
}
}
if (! $methodReflection->isPublic() && $hasScopeAttribute) {
$parametersAcceptor = $methodReflection->getVariants()[0];
$parameters = $parametersAcceptor->getParameters();
// We shift the parameters,
// because first parameter is the Builder
array_shift($parameters);
$returnType = $parametersAcceptor->getReturnType();
return new EloquentBuilderMethodReflection(
$methodName,
$methodReflection->getDeclaringClass(),
$parameters,
$returnType,
$parametersAcceptor->isVariadic(),
);
}
}
// Check for @method phpdoc tags
if (array_key_exists($scopeName, $reflection->getMethodTags())) {
$methodTag = $reflection->getMethodTags()[$scopeName];
$parameters = [];
foreach ($methodTag->getParameters() as $parameterName => $parameterTag) {
$parameters[] = new AnnotationScopeMethodParameterReflection(
$parameterName,
$parameterTag->getType(),
$parameterTag->passedByReference(),
$parameterTag->isOptional(),
$parameterTag->isVariadic(),
$parameterTag->getDefaultValue(),
);
}
// We shift the parameters,
// because first parameter is the Builder
array_shift($parameters);
return new EloquentBuilderMethodReflection(
$scopeName,
$reflection,
$parameters,
$methodTag->getReturnType(),
);
}
if ($reflection->hasNativeMethod($scopeName)) {
$methodReflection = $reflection->getNativeMethod($scopeName);
$parametersAcceptor = $methodReflection->getVariants()[0];
$parameters = $parametersAcceptor->getParameters();
// We shift the parameters,
// because first parameter is the Builder
array_shift($parameters);
$returnType = $parametersAcceptor->getReturnType();
return new EloquentBuilderMethodReflection(
$scopeName,
$methodReflection->getDeclaringClass(),
$parameters,
$returnType,
$parametersAcceptor->isVariadic(),
);
}
}
$queryBuilderReflection = $this->reflectionProvider->getClass(QueryBuilder::class);
if (in_array($methodName, $this->passthru, true)) {
return $queryBuilderReflection->getNativeMethod($methodName);
}
if ($queryBuilderReflection->hasNativeMethod($methodName)) {
return $queryBuilderReflection->getNativeMethod($methodName);
}
// Check for query builder macros
if ($this->macroMethodsClassReflectionExtension->hasMethod($queryBuilderReflection, $methodName)) {
return $this->macroMethodsClassReflectionExtension->getMethod($queryBuilderReflection, $methodName);
}
return $this->dynamicWhere($methodName, new GenericObjectType($eloquentBuilder->getName(), [$modelType]));
} | This method mimics the `EloquentBuilder::__call` method.
Does not handle the case where $methodName exists in `EloquentBuilder`,
that should be checked by caller before calling this method.
@param ClassReflection $eloquentBuilder Can be `EloquentBuilder` or a custom builder extending it.
@throws MissingMethodFromReflectionException
@throws ShouldNotHappenException | searchOnEloquentBuilder | php | larastan/larastan | src/Methods/BuilderHelper.php | https://github.com/larastan/larastan/blob/master/src/Methods/BuilderHelper.php | MIT |
public function hasMethod(ClassReflection $classReflection, string $methodName): bool
{
/** @var class-string[] $classNames */
$classNames = [];
$found = false;
$macroTraitProperty = null;
if ($classReflection->isInterface() && Str::startsWith($classReflection->getName(), 'Illuminate\Contracts')) {
/** @var object|null $concrete */
$concrete = $this->resolve($classReflection->getName());
if ($concrete !== null) {
$className = $concrete::class;
if ($className && $this->reflectionProvider->getClass($className)->hasTraitUse(Macroable::class)) {
$classNames = [$className];
$macroTraitProperty = 'macros';
}
}
} elseif (
$this->hasIndirectTraitUse($classReflection, Macroable::class) ||
$classReflection->is(Builder::class) ||
$classReflection->is(QueryBuilder::class)
) {
$classNames = [$classReflection->getName()];
$macroTraitProperty = 'macros';
if ($classReflection->is(Builder::class)) {
$classNames[] = Builder::class;
}
} elseif ($classReflection->is(Facade::class)) {
$facadeClass = $classReflection->getName();
if ($facadeClass === Auth::class) {
$classNames = [SessionGuard::class, RequestGuard::class];
$macroTraitProperty = 'macros';
} elseif ($facadeClass === Cache::class) {
$classNames = [CacheManager::class, CacheRepository::class];
$macroTraitProperty = 'macros';
} else {
$concrete = null;
try {
$concrete = $facadeClass::getFacadeRoot();
} catch (Throwable) {
}
if ($concrete) {
$facadeClassName = $concrete::class;
if ($facadeClassName) {
$classNames = [$facadeClassName];
$macroTraitProperty = 'macros';
}
}
}
}
if ($classNames !== [] && $macroTraitProperty) {
foreach ($classNames as $className) {
$macroClassReflection = $this->reflectionProvider->getClass($className);
if (! $macroClassReflection->getNativeReflection()->hasProperty($macroTraitProperty)) {
continue;
}
$refProperty = $macroClassReflection->getNativeReflection()->getProperty($macroTraitProperty);
$found = array_key_exists($methodName, $refProperty->getValue());
if (! $found) {
continue;
}
$macroDefinition = $refProperty->getValue()[$methodName];
if (is_string($macroDefinition)) {
if (str_contains($macroDefinition, '::')) {
$macroDefinition = explode('::', $macroDefinition, 2);
$macroClassName = $macroDefinition[0];
if (! $this->reflectionProvider->hasClass($macroClassName) || ! $this->reflectionProvider->getClass($macroClassName)->hasNativeMethod($macroDefinition[1])) {
throw new ShouldNotHappenException('Class ' . $macroClassName . ' does not exist');
}
$methodReflection = $this->reflectionProvider->getClass($macroClassName)->getNativeMethod($macroDefinition[1]);
} elseif (is_callable($macroDefinition)) {
$methodReflection = new Macro(
$macroClassReflection,
$methodName,
$this->closureTypeFactory->fromClosureObject(Closure::fromCallable($macroDefinition)),
);
} else {
throw new ShouldNotHappenException('Function ' . $macroDefinition . ' does not exist');
}
} elseif (is_array($macroDefinition)) {
if (is_string($macroDefinition[0])) {
$macroClassName = $macroDefinition[0];
} else {
$macroClassName = get_class($macroDefinition[0]);
}
if ($macroClassName === false || ! $this->reflectionProvider->hasClass($macroClassName) || ! $this->reflectionProvider->getClass($macroClassName)->hasNativeMethod($macroDefinition[1])) {
throw new ShouldNotHappenException('Class ' . $macroClassName . ' does not exist');
}
$methodReflection = $this->reflectionProvider->getClass($macroClassName)->getNativeMethod($macroDefinition[1]);
} else {
$methodReflection = new Macro(
$macroClassReflection,
$methodName,
$this->closureTypeFactory->fromClosureObject($macroDefinition),
);
$methodReflection->setIsStatic(true);
}
$this->methods[$classReflection->getName() . '-' . $methodName] = $methodReflection;
break;
}
}
return $found;
} | @throws ReflectionException
@throws ShouldNotHappenException
@throws MissingMethodFromReflectionException | hasMethod | php | larastan/larastan | src/Methods/MacroMethodsClassReflectionExtension.php | https://github.com/larastan/larastan/blob/master/src/Methods/MacroMethodsClassReflectionExtension.php | MIT |
public function initializeTables(array $tables = []): array
{
if ($this->disableMigrationScan) {
return $tables;
}
if (count($this->databaseMigrationPath) === 0) {
$this->databaseMigrationPath = [database_path('migrations')];
}
$schemaAggregator = new SchemaAggregator($this->reflectionProvider, $tables);
$filesArray = $this->getMigrationFiles();
if (empty($filesArray)) {
return $tables;
}
uasort($filesArray, static function (SplFileInfo $a, SplFileInfo $b) {
return $a->getFilename() <=> $b->getFilename();
});
foreach ($filesArray as $file) {
try {
$schemaAggregator->addStatements($this->parser->parseFile($file->getPathname()));
} catch (ParserErrorsException) {
continue;
}
}
return $schemaAggregator->tables;
} | @param array<string, SchemaTable> $tables
@return array<string, SchemaTable> | initializeTables | php | larastan/larastan | src/Properties/MigrationHelper.php | https://github.com/larastan/larastan/blob/master/src/Properties/MigrationHelper.php | MIT |
private function getModelCasts(ClassReflection $modelClassReflection): array
{
try {
/** @var Model $modelInstance */
$modelInstance = $modelClassReflection->getNativeReflection()->newInstanceWithoutConstructor();
} catch (ReflectionException) {
throw new ShouldNotHappenException();
}
$modelCasts = $modelInstance->getCasts();
$castsMethodReturnType = $modelClassReflection->getMethod(
'casts',
new OutOfClassScope(),
)->getVariants()[0]->getReturnType();
if ($castsMethodReturnType->isConstantArray()->yes()) {
$modelCasts = array_merge(
$modelCasts,
array_combine(
array_map(static fn ($key) => $key->getValue(), $castsMethodReturnType->getKeyTypes()), // @phpstan-ignore-line
array_map(static fn ($value) => str_replace('\\\\', '\\', $value->getValue()), $castsMethodReturnType->getValueTypes()), // @phpstan-ignore-line
),
);
}
return $modelCasts;
} | @return array<string, string>
@throws ShouldNotHappenException
@throws MissingMethodFromReflectionException | getModelCasts | php | larastan/larastan | src/Properties/ModelCastHelper.php | https://github.com/larastan/larastan/blob/master/src/Properties/ModelCastHelper.php | MIT |
public function hasDatabaseProperty(ClassReflection|string $classReflectionOrTable, string $propertyName): bool
{
if (! $this->migrationsLoaded()) {
$this->loadMigrations();
}
if (is_string($classReflectionOrTable)) {
if (! array_key_exists($classReflectionOrTable, $this->tables)) {
return false;
}
return array_key_exists($propertyName, $this->tables[$classReflectionOrTable]->columns);
}
if (! $classReflectionOrTable->is(Model::class)) {
return false;
}
if ($classReflectionOrTable->isAbstract()) {
return false;
}
if (ReflectionHelper::hasPropertyTag($classReflectionOrTable, $propertyName)) {
return false;
}
try {
/** @var Model $modelInstance */
$modelInstance = $classReflectionOrTable->getNativeReflection()->newInstanceWithoutConstructor();
} catch (ReflectionException) {
return false;
}
if ($propertyName === $modelInstance->getKeyName()) {
return true;
}
$tableName = $modelInstance->getTable();
if (! array_key_exists($tableName, $this->tables)) {
return false;
}
return array_key_exists($propertyName, $this->tables[$tableName]->columns);
} | Determine if the model has a database property. | hasDatabaseProperty | php | larastan/larastan | src/Properties/ModelPropertyHelper.php | https://github.com/larastan/larastan/blob/master/src/Properties/ModelPropertyHelper.php | MIT |
public function hasAccessor(ClassReflection $classReflection, string $propertyName, bool $strictGenerics = true): bool
{
if (! $classReflection->is(Model::class)) {
return false;
}
$camelCase = Str::camel($propertyName);
if (! $classReflection->hasNativeMethod($camelCase)) {
return $classReflection->hasNativeMethod('get' . Str::studly($propertyName) . 'Attribute');
}
$methodReflection = $classReflection->getNativeMethod($camelCase);
if ($methodReflection->isPublic() || $methodReflection->isPrivate()) {
return false;
}
$returnType = $methodReflection->getVariants()[0]->getReturnType();
if (! $strictGenerics) {
return (new ObjectType(Attribute::class))->isSuperTypeOf($returnType)->yes();
}
if ($returnType->getObjectClassReflections() === [] || ! $returnType->getObjectClassReflections()[0]->isGeneric()) {
return false;
}
return (new GenericObjectType(Attribute::class, [new MixedType(), new MixedType()]))->isSuperTypeOf($returnType)->yes();
} | Determine if the model has a property accessor.
@param bool $strictGenerics Requires the Attribute generics to be defined. | hasAccessor | php | larastan/larastan | src/Properties/ModelPropertyHelper.php | https://github.com/larastan/larastan/blob/master/src/Properties/ModelPropertyHelper.php | MIT |
public function addStatements(array $stmts): void
{
$nodeFinder = new NodeFinder();
/** @var PhpParser\Node\Stmt\Class_[] $classes */
$classes = $nodeFinder->findInstanceOf($stmts, PhpParser\Node\Stmt\Class_::class);
foreach ($classes as $stmt) {
$this->addClassStatements($stmt->stmts);
}
} | @param array<int, PhpParser\Node\Stmt> $stmts | addStatements | php | larastan/larastan | src/Properties/SchemaAggregator.php | https://github.com/larastan/larastan/blob/master/src/Properties/SchemaAggregator.php | MIT |
private function addClassStatements(array $stmts): void
{
foreach ($stmts as $stmt) {
if (
! ($stmt instanceof PhpParser\Node\Stmt\ClassMethod)
|| $stmt->name->name === 'down'
|| ! $stmt->stmts
) {
continue;
}
$this->addUpMethodStatements($stmt->stmts);
}
} | @param array<int, PhpParser\Node\Stmt> $stmts | addClassStatements | php | larastan/larastan | src/Properties/SchemaAggregator.php | https://github.com/larastan/larastan/blob/master/src/Properties/SchemaAggregator.php | MIT |
private function processColumnUpdates(string $tableName, string $argName, array $stmts): void
{
if (! isset($this->tables[$tableName])) {
return;
}
$table = $this->tables[$tableName];
foreach ($stmts as $stmt) {
if (
! ($stmt instanceof PhpParser\Node\Stmt\Expression)
|| ! ($stmt->expr instanceof PhpParser\Node\Expr\MethodCall)
|| ! ($stmt->expr->name instanceof PhpParser\Node\Identifier)
) {
continue;
}
$rootVar = $stmt->expr;
$firstMethodCall = $rootVar;
$nullable = false;
while ($rootVar instanceof PhpParser\Node\Expr\MethodCall) {
if (
$rootVar->name instanceof PhpParser\Node\Identifier
&& $rootVar->name->name === 'nullable'
&& $this->getNullableArgumentValue($rootVar) === true
) {
$nullable = true;
}
$firstMethodCall = $rootVar;
$rootVar = $rootVar->var;
}
if (
! ($rootVar instanceof PhpParser\Node\Expr\Variable)
|| $rootVar->name !== $argName
|| ! ($firstMethodCall->name instanceof PhpParser\Node\Identifier)
) {
continue;
}
$firstArg = $firstMethodCall->getArgs()[0]->value ?? null;
$secondArg = $firstMethodCall->getArgs()[1]->value ?? null;
if ($firstMethodCall->name->name === 'foreignIdFor') {
if (
$firstArg instanceof PhpParser\Node\Expr\ClassConstFetch
&& $firstArg->class instanceof PhpParser\Node\Name
) {
$modelClass = $firstArg->class->toCodeString();
} elseif ($firstArg instanceof PhpParser\Node\Scalar\String_) {
$modelClass = $firstArg->value;
} else {
continue;
}
$columnName = Str::snake(class_basename($modelClass)) . '_id';
if ($secondArg instanceof PhpParser\Node\Scalar\String_) {
$columnName = $secondArg->value;
}
$type = $this->getModelReferenceType($modelClass);
$table->setColumn(new SchemaColumn($columnName, $type ?? 'int', $nullable));
continue;
}
if (! $firstArg instanceof PhpParser\Node\Scalar\String_) {
if ($firstArg instanceof PhpParser\Node\Expr\Array_ && $firstMethodCall->name->name === 'dropColumn') {
foreach ($firstArg->items as $arrayItem) {
if (! $arrayItem->value instanceof PhpParser\Node\Scalar\String_) {
continue;
}
$table->dropColumn($arrayItem->value->value);
}
}
if (
$firstMethodCall->name->name === 'timestamps'
|| $firstMethodCall->name->name === 'timestampsTz'
|| $firstMethodCall->name->name === 'nullableTimestamps'
|| $firstMethodCall->name->name === 'nullableTimestampsTz'
|| $firstMethodCall->name->name === 'rememberToken'
) {
switch (strtolower($firstMethodCall->name->name)) {
case 'droptimestamps':
case 'droptimestampstz':
$table->dropColumn('created_at');
$table->dropColumn('updated_at');
break;
case 'remembertoken':
$table->setColumn(new SchemaColumn('remember_token', 'string', $nullable));
break;
case 'dropremembertoken':
$table->dropColumn('remember_token');
break;
case 'timestamps':
case 'timestampstz':
case 'nullabletimestamps':
$table->setColumn(new SchemaColumn('created_at', 'string', true));
$table->setColumn(new SchemaColumn('updated_at', 'string', true));
break;
}
continue;
}
$defaultsMap = [
'softDeletes' => 'deleted_at',
'softDeletesTz' => 'deleted_at',
'softDeletesDatetime' => 'deleted_at',
'dropSoftDeletes' => 'deleted_at',
'dropSoftDeletesTz' => 'deleted_at',
'uuid' => 'uuid',
'id' => 'id',
'ulid' => 'ulid',
'ipAddress' => 'ip_address',
'macAddress' => 'mac_address',
];
if (! array_key_exists($firstMethodCall->name->name, $defaultsMap)) {
continue;
}
$columnName = $defaultsMap[$firstMethodCall->name->name];
} else {
$columnName = $firstArg->value;
}
$secondArgArray = null;
if ($secondArg instanceof PhpParser\Node\Expr\Array_) {
$secondArgArray = [];
foreach ($secondArg->items as $arrayItem) {
if (! $arrayItem->value instanceof PhpParser\Node\Scalar\String_) {
continue;
}
$secondArgArray[] = $arrayItem->value->value;
}
}
$this->processStatementAlterMethod(
strtolower($firstMethodCall->name->name),
$firstMethodCall,
$table,
$columnName,
$nullable,
$secondArg,
$argName,
$tableName,
$secondArgArray,
$stmt,
);
}
} | @param PhpParser\Node\Stmt[] $stmts
@throws Exception | processColumnUpdates | php | larastan/larastan | src/Properties/SchemaAggregator.php | https://github.com/larastan/larastan/blob/master/src/Properties/SchemaAggregator.php | MIT |
private function processStatementAlterMethod(
string $method,
PhpParser\Node\Expr\MethodCall|null $firstMethodCall,
SchemaTable $table,
string $columnName,
bool $nullable,
mixed $secondArg,
PhpParser\Node\Expr|string $argName,
string $tableName,
array|null $secondArgArray,
PhpParser\Node\Stmt\Expression $stmt,
): void {
switch ($method) {
case 'addcolumn':
$this->processStatementAlterMethod(
strtolower($firstMethodCall->args[0]->value->value ?? ''),
null,
$table,
$firstMethodCall->args[1]->value->value ?? '',
$nullable,
$secondArg,
$argName,
$tableName,
$secondArgArray,
$stmt,
);
return;
case 'biginteger':
case 'increments':
case 'id':
case 'integer':
case 'integerincrements':
case 'mediumincrements':
case 'mediuminteger':
case 'smallincrements':
case 'smallinteger':
case 'tinyincrements':
case 'tinyinteger':
case 'unsignedbiginteger':
case 'unsignedinteger':
case 'unsignedmediuminteger':
case 'unsignedsmallinteger':
case 'unsignedtinyinteger':
case 'bigincrements':
case 'foreignid':
$table->setColumn(new SchemaColumn($columnName, 'int', $nullable));
return;
case 'char':
case 'datetimetz':
case 'date':
case 'datetime':
case 'ipaddress':
case 'json':
case 'jsonb':
case 'linestring':
case 'longtext':
case 'macaddress':
case 'mediumtext':
case 'multilinestring':
case 'string':
case 'text':
case 'time':
case 'timestamp':
case 'ulid':
case 'uuid':
case 'binary':
$table->setColumn(new SchemaColumn($columnName, 'string', $nullable));
return;
case 'boolean':
$table->setColumn(new SchemaColumn($columnName, 'bool', $nullable));
return;
case 'geometry':
case 'geometrycollection':
case 'multipoint':
case 'multipolygon':
case 'multipolygonz':
case 'point':
case 'polygon':
case 'computed':
$table->setColumn(new SchemaColumn($columnName, 'mixed', $nullable));
return;
case 'double':
case 'float':
case 'unsigneddecimal':
case 'decimal':
$table->setColumn(new SchemaColumn($columnName, 'float', $nullable));
return;
case 'after':
if (
$secondArg instanceof PhpParser\Node\Expr\Closure
&& $secondArg->params[0]->var instanceof PhpParser\Node\Expr\Variable
&& ! ($secondArg->params[0]->var->name instanceof PhpParser\Node\Expr)
) {
$argName = $secondArg->params[0]->var->name;
$this->processColumnUpdates($tableName, $argName, $secondArg->stmts);
}
return;
case 'dropcolumn':
case 'dropifexists':
case 'dropsoftdeletes':
case 'dropsoftdeletestz':
case 'removecolumn':
case 'drop':
$table->dropColumn($columnName);
return;
case 'dropforeign':
case 'dropindex':
case 'dropprimary':
case 'dropunique':
case 'foreign':
case 'index':
case 'primary':
case 'renameindex':
case 'spatialIndex':
case 'unique':
case 'dropspatialindex':
return;
case 'dropmorphs':
$table->dropColumn($columnName . '_type');
$table->dropColumn($columnName . '_id');
return;
case 'enum':
$table->setColumn(new SchemaColumn($columnName, 'enum', $nullable, $secondArgArray));
return;
case 'morphs':
$table->setColumn(new SchemaColumn($columnName . '_type', 'string', $nullable));
$table->setColumn(new SchemaColumn($columnName . '_id', 'int', $nullable));
return;
case 'nullablemorphs':
$table->setColumn(new SchemaColumn($columnName . '_type', 'string', true));
$table->setColumn(new SchemaColumn($columnName . '_id', 'int', true));
return;
case 'nullableuuidmorphs':
$table->setColumn(new SchemaColumn($columnName . '_type', 'string', true));
$table->setColumn(new SchemaColumn($columnName . '_id', 'string', true));
return;
case 'rename':
/** @var PhpParser\Node\Expr\MethodCall $methodCall */
$methodCall = $stmt->expr;
$this->renameTableThroughMethodCall($table, $methodCall);
return;
case 'renamecolumn':
if ($secondArg instanceof PhpParser\Node\Scalar\String_) {
$table->renameColumn($columnName, $secondArg->value);
}
return;
case 'set':
$table->setColumn(new SchemaColumn($columnName, 'set', $nullable, $secondArgArray));
return;
case 'softdeletestz':
case 'timestamptz':
case 'timetz':
case 'year':
case 'softdeletes':
$table->setColumn(new SchemaColumn($columnName, 'string', true));
return;
case 'uuidmorphs':
$table->setColumn(new SchemaColumn($columnName . '_type', 'string', $nullable));
$table->setColumn(new SchemaColumn($columnName . '_id', 'string', $nullable));
return;
default:
// We know a property exists with a name, we just don't know its type.
$table->setColumn(new SchemaColumn($columnName, 'mixed', $nullable));
}
} | @param array<int, mixed> $secondArgArray
@throws Exception | processStatementAlterMethod | php | larastan/larastan | src/Properties/SchemaAggregator.php | https://github.com/larastan/larastan/blob/master/src/Properties/SchemaAggregator.php | MIT |
private function isNullable(array $definition): bool
{
if (! array_key_exists('null', $definition)) {
return false;
}
if (is_bool($definition['null'])) {
return $definition['null'];
}
return false;
} | @param array<string, string|bool|null> $definition | isNullable | php | larastan/larastan | src/Properties/SquashedMigrationHelper.php | https://github.com/larastan/larastan/blob/master/src/Properties/SquashedMigrationHelper.php | MIT |
public static function hasPropertyTag(ClassReflection $classReflection, string $propertyName): bool
{
if (array_key_exists($propertyName, $classReflection->getPropertyTags())) {
return true;
}
foreach ($classReflection->getAncestors() as $ancestor) {
if (array_key_exists($propertyName, $ancestor->getPropertyTags())) {
return true;
}
}
/** @phpstan-ignore-next-line */
return (new MixinPropertiesClassReflectionExtension([$classReflection->getName()]))
->hasProperty($classReflection, $propertyName);
} | Does the given class or any of its ancestors have an `@property*` annotation with the given name? | hasPropertyTag | php | larastan/larastan | src/Reflection/ReflectionHelper.php | https://github.com/larastan/larastan/blob/master/src/Reflection/ReflectionHelper.php | MIT |
public static function hasMethodTag(ClassReflection $classReflection, string $methodName): bool
{
if (array_key_exists($methodName, $classReflection->getMethodTags())) {
return true;
}
foreach ($classReflection->getAncestors() as $ancestor) {
if (array_key_exists($methodName, $ancestor->getMethodTags())) {
return true;
}
}
/** @phpstan-ignore-next-line */
return (new MixinMethodsClassReflectionExtension([$classReflection->getName()]))
->hasMethod($classReflection, $methodName);
} | Does the given class or any of its ancestors have an `@method*` annotation with the given name? | hasMethodTag | php | larastan/larastan | src/Reflection/ReflectionHelper.php | https://github.com/larastan/larastan/blob/master/src/Reflection/ReflectionHelper.php | MIT |
public function processNode(Node $node, Scope $scope): array
{
$classReflection = $node->getClassReflection();
// This rule is only applicable to deferrable serviceProviders
if (! $classReflection->is(ServiceProvider::class) || ! $classReflection->implementsInterface(DeferrableProvider::class)) {
return [];
}
if (! $classReflection->hasNativeMethod('provides')) {
throw new ShouldNotHappenException('If this scenario happens, the "provides" method is removed from the base Laravel ServiceProvider and this rule can be removed.');
}
$method = $classReflection->getNativeMethod('provides');
// The provides method is overwritten somewhere in the class hierarchy
if ($method->getDeclaringClass()->getName() !== ServiceProvider::class) {
return [];
}
return [
RuleErrorBuilder::message('ServiceProviders that implement the "DeferrableProvider" interface should implement the "provides" method that returns an array of strings or class-strings')
->line($node->getStartLine())
->identifier('larastan.deferrableServiceProvider.missingProvides')
->build(),
];
} | @return RuleError[]
@throws ShouldNotHappenException
@throws MissingMethodFromReflectionException | processNode | php | larastan/larastan | src/Rules/DeferrableServiceProviderMissingProvidesRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/DeferrableServiceProviderMissingProvidesRule.php | MIT |
public function __construct(private array $configDirectories, private FileHelper $fileHelper)
{
if (count($configDirectories) !== 0) {
return;
}
$this->configDirectories = [config_path()]; // @phpstan-ignore-line
} | @param list<non-empty-string> $configDirectories | __construct | php | larastan/larastan | src/Rules/NoEnvCallsOutsideOfConfigRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoEnvCallsOutsideOfConfigRule.php | MIT |
protected function isCalledOnModel(StaticCall $call, Scope $scope): bool
{
$class = $call->class;
if ($class instanceof FullyQualified) {
$type = new ObjectType($class->toString());
} elseif ($class instanceof Expr) {
$type = $scope->getType($class);
if ($type->isClassString()->yes() && $type->getConstantStrings() !== []) {
$type = new ObjectType($type->getConstantStrings()[0]->getValue());
}
} else {
// TODO can we handle relative names, do they even occur here?
return false;
}
return (new ObjectType(Model::class))
->isSuperTypeOf($type)
->yes();
} | Was the expression called on a Model instance? | isCalledOnModel | php | larastan/larastan | src/Rules/NoModelMakeRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoModelMakeRule.php | MIT |
public function __construct(
protected ReflectionProvider $reflectionProvider,
protected ModelPropertyExtension $propertyExtension,
array $onlyMethods,
array $excludeMethods,
) {
$allMethods = array_merge(
self::RISKY_METHODS,
self::RISKY_PARAM_METHODS,
[
'first',
'contains',
'containsstrict',
],
);
if (! empty($onlyMethods)) {
$this->shouldHandle = array_map(static function (string $methodName): string {
return Str::lower($methodName);
}, $onlyMethods);
} else {
$this->shouldHandle = $allMethods;
}
if (empty($excludeMethods)) {
return;
}
$this->shouldHandle = array_diff($this->shouldHandle, array_map(static function (string $methodName): string {
return Str::lower($methodName);
}, $excludeMethods));
} | @param string[] $onlyMethods
@param string[] $excludeMethods | __construct | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
protected function firstArgIsDatabaseColumn(Node\Expr\StaticCall|MethodCall $node, Scope $scope): bool
{
/** @var Arg[] $args */
$args = $node->args;
if (count($args) === 0 || ! ($args[0]->value instanceof Node\Scalar\String_)) {
return false;
}
if ($node instanceof Node\Expr\StaticCall) {
/** @var Node\Name $class */
$class = $node->class;
$modelReflection = $this->reflectionProvider->getClass($class->toCodeString());
/** @var String_ $firstArg */
$firstArg = $args[0]->value;
return $this->propertyExtension->hasProperty($modelReflection, $firstArg->value);
}
$iterableType = $scope->getType($node->var)->getIterableValueType();
if ((new ObjectType(stdClass::class))->isSuperTypeOf($iterableType)->yes()) {
$previousCall = $node->var;
if ($previousCall instanceof MethodCall) {
$queryBuilderType = $scope->getType($previousCall->var);
if ((new ObjectType(QueryBuilder::class))->isSuperTypeOf($queryBuilderType)->yes()) {
// We encountered a DB query such as DB::table(..)->get()->max('id')
// We assume max('id') could have been retrieved without calling get().
return true;
}
}
return false;
}
if ((new ObjectType(Model::class))->isSuperTypeOf($iterableType)->yes()) {
$iterableClassNames = $iterableType->getObjectClassNames();
if (count($iterableClassNames) === 0) {
return false;
}
$modelReflection = $this->reflectionProvider->getClass($iterableClassNames[0]);
/** @var String_ $firstArg */
$firstArg = $args[0]->value;
return $this->propertyExtension->hasProperty($modelReflection, $firstArg->value);
}
return false;
} | Determines whether the first argument is a string and references a database column. | firstArgIsDatabaseColumn | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
protected function callIsQuery(Node\Expr $call, Scope $scope): bool
{
if ($call instanceof MethodCall) {
$calledOn = $scope->getType($call->var);
return $this->isBuilder($calledOn);
}
if ($call instanceof Node\Expr\StaticCall) {
$class = $call->class;
if ($class instanceof Node\Name) {
$modelClassName = $class->toCodeString();
return (new ObjectType(Model::class))->isSuperTypeOf(new ObjectType($modelClassName))->yes()
&& $call->name instanceof Identifier
&& in_array($call->name->toLowerString(), ['get', 'all', 'pluck'], true);
}
}
return false;
} | Returns whether the method call is a call on a builder instance.
@phpstan-assert-if-true MethodCall|Node\Expr\StaticCall $call | callIsQuery | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
protected function isRiskyMethod(Identifier $name): bool
{
return in_array($name->toLowerString(), self::RISKY_METHODS, true);
} | Returns whether the method is one of the risky methods. | isRiskyMethod | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
protected function isRiskyParamMethod(Identifier $name): bool
{
return in_array($name->toLowerString(), self::RISKY_PARAM_METHODS, true);
} | Returns whether the method might be a risky method depending on the parameters passed. | isRiskyParamMethod | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
protected function isBuilder(Type $type): bool
{
return (new ObjectType(EloquentBuilder::class))->isSuperTypeOf($type)->yes()
|| (new ObjectType(QueryBuilder::class))->isSuperTypeOf($type)->yes()
|| (new ObjectType(Relation::class))->isSuperTypeOf($type)->yes();
} | Returns whether its argument is some builder instance. | isBuilder | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
protected function isCalledOnCollection(Node\Expr $expr, Scope $scope): bool
{
$calledOnType = $scope->getType($expr);
return (new ObjectType(Collection::class))->isSuperTypeOf($calledOnType)->yes();
} | Returns whether the Expr was not called on a Collection instance. | isCalledOnCollection | php | larastan/larastan | src/Rules/NoUnnecessaryCollectionCallRule.php | https://github.com/larastan/larastan/blob/master/src/Rules/NoUnnecessaryCollectionCallRule.php | MIT |
public function __construct(private FileHelper $fileHelper, private Parser $parser, array $configPaths)
{
foreach ($configPaths as $configPath) {
$this->configPaths[] = $this->fileHelper->absolutizePath($configPath);
}
$this->configFiles = $this->getConfigFiles();
} | @param list<non-empty-string> $configPaths | __construct | php | larastan/larastan | src/Support/ConfigParser.php | https://github.com/larastan/larastan/blob/master/src/Support/ConfigParser.php | MIT |
public function __construct(private array $viewDirectories, private FileHelper $fileHelper)
{
if (count($viewDirectories) !== 0) {
return;
}
$finder = $this->resolve(ViewFactory::class)->getFinder();
$viewDirectories = array_merge(
$finder->getPaths(),
...array_values($finder->getHints()),
);
$this->viewDirectories = $viewDirectories; // @phpstan-ignore-line
} | @param list<non-empty-string> $viewDirectories | __construct | php | larastan/larastan | src/Support/ViewFileHelper.php | https://github.com/larastan/larastan/blob/master/src/Support/ViewFileHelper.php | MIT |
public function scopeActive(Builder $query): Builder
{
return $query->where('active', 1);
} | @param Builder<Account> $query
@return Builder<Account> | scopeActive | php | larastan/larastan | tests/application/app/Account.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Account.php | MIT |
public function newCollection(array $models = []): AccountCollection
{
return new AccountCollection($models);
} | @param array<int, Account> $models
@return AccountCollection<int, Account> | newCollection | php | larastan/larastan | tests/application/app/Account.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Account.php | MIT |
public function sync($data, $deleting = true): array
{
$changes = [
'created' => [], 'deleted' => [], 'updated' => [],
];
$relatedKeyName = $this->related->getKeyName();
// First we need to attach any of the associated models that are not currently
// in the child entity table. We'll spin through the given IDs, checking to see
// if they exist in the array of current ones, and if not we will insert.
$current = $this->newQuery()->pluck(
$relatedKeyName
)->all();
// Separate the submitted data into "update" and "new"
$updateRows = [];
$newRows = [];
foreach ($data as $row) {
unset($row[$this->createdAt()], $row[$this->updatedAt()]); //remove the so they can be auto updated/created
if (method_exists($this->parent, 'getDeletedAtColumn')) {
unset($row[$this->parent->getDeletedAtColumn()]);
}
// We determine "updateable" rows as those whose $relatedKeyName (usually 'id') is set, not empty, and
// match a related row in the database.
if (isset($row[$relatedKeyName]) && ! empty($row[$relatedKeyName]) && in_array($row[$relatedKeyName], $current)) {
$id = $row[$relatedKeyName];
$updateRows[$id] = $row;
} else {
$newRows[] = $row;
}
}
// Next, we'll determine the rows in the database that aren't in the "update" list.
// These rows will be scheduled for deletion. Again, we determine based on the relatedKeyName (typically 'id').
$updateIds = array_keys($updateRows);
$deleteIds = [];
foreach ($current as $currentId) {
if (! in_array($currentId, $updateIds)) {
$deleteIds[] = $currentId;
}
}
// Delete any non-matching rows
if ($deleting && count($deleteIds) > 0) {
$this->getRelated()->destroy($deleteIds);
$changes['deleted'] = $this->castKeys($deleteIds);
}
// Update the updatable rows
foreach ($updateRows as $id => $row) {
$this->getRelated()->where($relatedKeyName, $id)
->update($row);
}
$changes['updated'] = $this->castKeys($updateIds);
// Insert the new rows
$newIds = [];
foreach ($newRows as $row) {
$newModel = $this->create($row);
$newIds[] = $newModel->$relatedKeyName;
}
$changes['created'][] = $this->castKeys($newIds);
return $changes;
} | @param mixed $data
@param bool $deleting
@return array<string, mixed> | sync | php | larastan/larastan | tests/application/app/HasManySyncable.php | https://github.com/larastan/larastan/blob/master/tests/application/app/HasManySyncable.php | MIT |
protected function castKeys(array $keys)
{
return (array) array_map(function ($v) {
return $this->castKey($v);
}, $keys);
} | Cast the given keys to integers if they are numeric and string otherwise.
@param array $keys
@return array | castKeys | php | larastan/larastan | tests/application/app/HasManySyncable.php | https://github.com/larastan/larastan/blob/master/tests/application/app/HasManySyncable.php | MIT |
protected function castKey($key)
{
return is_numeric($key) ? (int) $key : (string) $key;
} | Cast the given key to an integer if it is numeric.
@param mixed $key
@return mixed | castKey | php | larastan/larastan | tests/application/app/HasManySyncable.php | https://github.com/larastan/larastan/blob/master/tests/application/app/HasManySyncable.php | MIT |
public function newCollection(array $models = []): OnlyValueGenericCollection
{
return new OnlyValueGenericCollection($models);
} | @template TModel
@param TModel[] $models
@return OnlyValueGenericCollection<TModel> | newCollection | php | larastan/larastan | tests/application/app/ModelWithOnlyValueGenericCollection.php | https://github.com/larastan/larastan/blob/master/tests/application/app/ModelWithOnlyValueGenericCollection.php | MIT |
public function newEloquentBuilder($query): PostBuilder
{
return new PostBuilder($query);
} | @param \Illuminate\Database\Query\Builder $query
@return PostBuilder<Post> | newEloquentBuilder | php | larastan/larastan | tests/application/app/Post.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Post.php | MIT |
public function newCollection(array $models = []): RoleCollection
{
return new RoleCollection($models);
} | @param array<int, Role> $models
@return RoleCollection<int, Role> | newCollection | php | larastan/larastan | tests/application/app/Role.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Role.php | MIT |
public function newEloquentBuilder($query): ChildTeamBuilder
{
return new ChildTeamBuilder($query);
} | @param \Illuminate\Database\Query\Builder $query
@return ChildTeamBuilder | newEloquentBuilder | php | larastan/larastan | tests/application/app/Team.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Team.php | MIT |
public static function methodReturningUnionWithCollection()
{
return new Collection([]);
} | @phpstan-return Collection<int, Thread>|Thread | methodReturningUnionWithCollection | php | larastan/larastan | tests/application/app/Thread.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Thread.php | MIT |
public static function methodReturningUnionWithCollectionOfAnotherModel()
{
return new Collection([]);
} | @phpstan-return Collection<int, User>|User | methodReturningUnionWithCollectionOfAnotherModel | php | larastan/larastan | tests/application/app/Thread.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Thread.php | MIT |
public function newCollection(array $models = []): TransactionCollection
{
return new TransactionCollection($models);
} | @param array<int, Transaction> $models
@return TransactionCollection<int, Transaction> | newCollection | php | larastan/larastan | tests/application/app/Transaction.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Transaction.php | MIT |
public function scopeWhereActive(Builder $query): Builder
{
return $query->where('active', 1);
} | @param Builder<User> $query
@return Builder<User> | scopeWhereActive | php | larastan/larastan | tests/application/app/User.php | https://github.com/larastan/larastan/blob/master/tests/application/app/User.php | MIT |
public function email(): Attribute
{
return Attribute::make(
fn ($value) => 5,
fn (string $value) => strtolower($value)
);
} | This will not take any effect because it's public and does not specify generic types at return type. | email | php | larastan/larastan | tests/application/app/User.php | https://github.com/larastan/larastan/blob/master/tests/application/app/User.php | MIT |
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'meta' => json_decode($this->meta),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
'has_verified_email' => $this->hasVerifiedEmail(),
];
} | Transform the resource into an array.
@param \Illuminate\Http\Request $request
@return array<string, mixed> | toArray | php | larastan/larastan | tests/application/app/UserResource.php | https://github.com/larastan/larastan/blob/master/tests/application/app/UserResource.php | MIT |
public function get($model, $key, $value, $attributes)
{
return new \App\ValueObjects\Favorites();
} | Cast the given value.
@return \App\ValueObjects\Favorites | get | php | larastan/larastan | tests/application/app/Casts/Favorites.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Casts/Favorites.php | MIT |
public function set($model, $key, $value, $attributes)
{
if (! $value instanceof \App\ValueObjects\Favorites) {
throw new InvalidArgumentException('The given value is not a Favorites instance.');
}
return [];
} | Prepare the given value for storage.
@param Favorites $value | set | php | larastan/larastan | tests/application/app/Casts/Favorites.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Casts/Favorites.php | MIT |
public function __construct($algorithm = null)
{
$this->algorithm = $algorithm;
} | Create a new cast class instance.
@param string|null $algorithm
@return void | __construct | php | larastan/larastan | tests/application/app/Casts/Hash.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Casts/Hash.php | MIT |
public function set($model, string $key, $value, $attributes)
{
return is_null($this->algorithm)
? bcrypt($value)
: hash($this->algorithm, $value);
} | Prepare the given value for storage.
@param \Illuminate\Database\Eloquent\Model $model
@param string $key
@param string $value
@param array $attributes
@return string | set | php | larastan/larastan | tests/application/app/Casts/Hash.php | https://github.com/larastan/larastan/blob/master/tests/application/app/Casts/Hash.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.