A library for validating access to methods based on the source context (API, Web, CLI, etc.) using attributes and dynamic proxies
- Source Validation — Restrict access to methods by source type
- Dynamic Proxies — Automatic generation of proxy classes
- Attributes — Simple declarative configuration via PHP attributes
- Laravel Integration — Ready-to-use Laravel integration
- Multiple Contexts — Support for various context implementations
composer require din9xtr/source-context#[AutoValidateSources]
class UserService implements SomeInterface // it's important
{
// ...
}class UserService implements SomeInterface // it's important
{
#[AllowedSources([Source::API, Source::WEB])]
public function createUser(array $data): User
{
}
#[AllowedSources([Source::CLI, Source::CRON])]
public function listUsers(): void
{
}
}<?php
readonly class SomeInstance
{
public function __construct(
private SourceContextInterface $context,
) {
}
public function exec(): ?SourceInterface
{
$this->context->set(NoSource::CLI);
}
}- AutoValidateSources — Marks the class for automatic source validation
#[AutoValidateSources]
class YourService
{
// ...
}- AllowedSources — Restricts access to the method to certain sources
#[AllowedSources([Source::API, Source::WEB])]
public function someMethod(): void
{
// ...
}Throws exceptions if the source is not in
#[AllowedSources([])]
RuntimeException: Method App\Service\UserService::createUser not allowed for source `name`
- InMemorySourceContext — In-memory context for request-response applications
- StaticSourceContext — Static context
Supported sources:
Source::API
Source::WEB
Source::QUEUE
Source::CLI
Source::CRON
Source::TESTThe service provider automatically registers all classes with the AutoValidateSources attribute
Or you can specify them in the source-context.php configuration file
<?php
declare(strict_types=1);
return [
'auto_validate_classes' => [
\YourApp\YourService::class,
],
'scan_chunk_size' => 2048,
];use App\SourceContext\Contract\SourceContextInterface;
use App\SourceContext\Implementation\InMemorySourceContext;
$context = new InMemorySourceContext();
$context->set(Source::API);
$service = new UserService();
$proxy = ProxyGenerator::createProxy($service, $context);enum YourSource: string implements SourceInterface
{
case API = 'api';
case WEB = 'web';
case NEW_SOURCE = 'new_source';
public function is(self|string|SourceInterface $other): bool
{
return $this->value === (string) $other;
}
}This project is open-source and available under the MIT License.
Copyright © 2026 Din9xtr