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 |
---|---|---|---|---|---|---|---|
public function attachCategories($categories)
{
return $this->syncCategories($categories, false);
}
|
Attach model categories.
@param mixed $categories
@return $this
|
attachCategories
|
php
|
rinvex/laravel-categories
|
src/Traits/Categorizable.php
|
https://github.com/rinvex/laravel-categories/blob/master/src/Traits/Categorizable.php
|
MIT
|
public function detachCategories($categories = null)
{
$categories = ! is_null($categories) ? $this->prepareCategoryIds($categories) : null;
// Sync model categories
$this->categories()->detach($categories);
return $this;
}
|
Detach model categories.
@param mixed $categories
@return $this
|
detachCategories
|
php
|
rinvex/laravel-categories
|
src/Traits/Categorizable.php
|
https://github.com/rinvex/laravel-categories/blob/master/src/Traits/Categorizable.php
|
MIT
|
protected function prepareCategoryIds($categories): array
{
// Convert collection to plain array
if ($categories instanceof BaseCollection && is_string($categories->first())) {
$categories = $categories->toArray();
}
// Find categories by their ids
if (is_numeric($categories) || (is_array($categories) && is_numeric(Arr::first($categories)))) {
return array_map('intval', (array) $categories);
}
// Find categories by their slugs
if (is_string($categories) || (is_array($categories) && is_string(Arr::first($categories)))) {
$categories = app('rinvex.categories.category')->whereIn('slug', (array) $categories)->get()->pluck('id');
}
if ($categories instanceof Model) {
return [$categories->getKey()];
}
if ($categories instanceof Collection) {
return $categories->modelKeys();
}
if ($categories instanceof BaseCollection) {
return $categories->toArray();
}
return (array) $categories;
}
|
Prepare category IDs.
@param mixed $categories
@return array
|
prepareCategoryIds
|
php
|
rinvex/laravel-categories
|
src/Traits/Categorizable.php
|
https://github.com/rinvex/laravel-categories/blob/master/src/Traits/Categorizable.php
|
MIT
|
public function __construct(
public array $whitelistedWords = [],
public array $whitelistedPaths = [],
public ?string $preset = null,
) {
$this->whitelistedWords = array_map(strtolower(...), $whitelistedWords);
}
|
Creates a new instance of Config.
@param array<int, string> $whitelistedWords
@param array<int, string> $whitelistedPaths
|
__construct
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
public static function exists(): bool
{
return file_exists(ProjectPath::get().'/'.self::JSON_CONFIGURATION_NAME);
}
|
Checks if the configuration file exists.
|
exists
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
public static function instance(): self
{
if (self::$instance instanceof self) {
return self::$instance;
}
$basePath = ProjectPath::get();
$filePath = $basePath.'/'.(self::$resolveConfigFilePathUsing instanceof Closure
? (self::$resolveConfigFilePathUsing)()
: self::JSON_CONFIGURATION_NAME);
$contents = file_exists($filePath)
? (string) file_get_contents($filePath)
: '{}';
/**
* @var array{
* preset?: string,
* ignore?: array{
* words?: array<int, string>,
* paths?: array<int, string>
* }
* } $jsonAsArray
*/
$jsonAsArray = json_decode($contents, true) ?: [];
return self::$instance = new self(
$jsonAsArray['ignore']['words'] ?? [],
$jsonAsArray['ignore']['paths'] ?? [],
$jsonAsArray['preset'] ?? null,
);
}
|
Fetches the instance of the configuration.
|
instance
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
public static function init(): bool
{
$filePath = ProjectPath::get().'/'.self::JSON_CONFIGURATION_NAME;
if (file_exists($filePath)) {
return false;
}
return (bool) file_put_contents($filePath, json_encode([
...match (true) {
class_exists('\Illuminate\Support\Str') => [
'preset' => 'laravel',
],
default => [
'preset' => 'base',
],
},
'ignore' => [
'words' => [
'php',
],
'paths' => [],
],
], JSON_PRETTY_PRINT));
}
|
Creates the configuration file for the user running the command.
|
init
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
public function ignoreWords(array $words): void
{
$this->whitelistedWords = array_merge($this->whitelistedWords, array_map(strtolower(...), $words));
$this->persist();
}
|
Adds a word to the ignore list.
@param array<int, string> $words
|
ignoreWords
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
public function isWordIgnored(string $word): bool
{
return in_array(strtolower($word), [
...$this->whitelistedWords,
...array_map(strtolower(...), PresetProvider::whitelistedWords($this->preset)),
]);
}
|
Checks if the word is ignored.
|
isWordIgnored
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
private function persist(): void
{
$filePath = ProjectPath::get().'/'.self::JSON_CONFIGURATION_NAME;
file_put_contents($filePath, json_encode([
...$this->preset !== null ? ['preset' => $this->preset] : [],
'ignore' => [
'words' => $this->whitelistedWords,
'paths' => $this->whitelistedPaths,
],
], JSON_PRETTY_PRINT));
}
|
Save the configuration to the file.
|
persist
|
php
|
peckphp/peck
|
src/Config.php
|
https://github.com/peckphp/peck/blob/master/src/Config.php
|
MIT
|
public function __construct(
private array $checkers,
) {
//
}
|
Creates a new instance of Kernel.
@param array<int, Contracts\Checker> $checkers
|
__construct
|
php
|
peckphp/peck
|
src/Kernel.php
|
https://github.com/peckphp/peck/blob/master/src/Kernel.php
|
MIT
|
public static function default(): self
{
$config = Config::instance();
$aspell = Aspell::default();
return new self(
[
new FileSystemChecker($config, $aspell),
new SourceCodeChecker($config, $aspell),
],
);
}
|
Creates the default instance of Kernel.
|
default
|
php
|
peckphp/peck
|
src/Kernel.php
|
https://github.com/peckphp/peck/blob/master/src/Kernel.php
|
MIT
|
public function handle(array $parameters): array
{
$issues = [];
foreach ($this->checkers as $checker) {
$issues = [
...$issues,
...$checker->check($parameters),
];
}
return $issues;
}
|
Handles the given parameters.
@param array{directory: string, onSuccess: callable(): void, onFailure: callable(): void} $parameters
@return array<int, ValueObjects\Issue>
|
handle
|
php
|
peckphp/peck
|
src/Kernel.php
|
https://github.com/peckphp/peck/blob/master/src/Kernel.php
|
MIT
|
public function check(array $parameters): array
{
$filesOrDirectories = iterator_to_array(Finder::create()
->notPath(NotPaths::get($parameters['directory'], $this->config->whitelistedPaths))
->ignoreDotFiles(true)
->ignoreUnreadableDirs()
->ignoreVCSIgnored(true)
->in($parameters['directory'])
->sortByName()
->getIterator());
$issues = [];
foreach ($filesOrDirectories as $fileOrDirectory) {
$name = SpellcheckFormatter::format($fileOrDirectory->getFilenameWithoutExtension());
$newIssues = array_map(
fn (Misspelling $misspelling): Issue => new Issue(
$misspelling,
$fileOrDirectory->getRealPath(),
0,
), $this->spellchecker->check($name),
);
$issues = [
...$issues,
...$newIssues,
];
$newIssues !== [] ? $parameters['onFailure']() : $parameters['onSuccess']();
}
return $issues;
}
|
Checks for issues in the given directory.
@param array{directory: string, onSuccess: callable(): void, onFailure: callable(): void} $parameters
@return array<int, Issue>
|
check
|
php
|
peckphp/peck
|
src/Checkers/FileSystemChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/FileSystemChecker.php
|
MIT
|
public function check(array $parameters): array
{
$sourceFiles = iterator_to_array(Finder::create()
->files()
->notPath(NotPaths::get($parameters['directory'], $this->config->whitelistedPaths))
->ignoreDotFiles(true)
->ignoreVCS(true)
->ignoreUnreadableDirs()
->ignoreVCSIgnored(true)
->in($parameters['directory'])
->name('*.php')
->sortByName()
->getIterator());
$issues = [];
foreach ($sourceFiles as $sourceFile) {
$newIssues = $this->getIssuesFromSourceFile($sourceFile);
$issues = [
...$issues,
...$newIssues,
];
$newIssues !== [] ? $parameters['onFailure']() : $parameters['onSuccess']();
}
return $issues;
}
|
Checks for issues in the given directory.
@param array{directory: string, onSuccess: callable(): void, onFailure: callable(): void} $parameters
@return array<int, Issue>
|
check
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getIssuesFromSourceFile(SplFileInfo $file): array
{
$definition = $this->getFullyQualifiedDefinitionName($file);
if ($definition === null) {
return [];
}
try {
$reflection = new ReflectionClass($definition);
} catch (ReflectionException) { // @phpstan-ignore-line
return [];
}
$namesToCheck = [
...$this->getMethodNames($reflection),
...$this->getPropertyNames($reflection),
...$this->getConstantNames($reflection),
];
if ($docComment = $reflection->getDocComment()) {
$namesToCheck = [
...$namesToCheck,
...array_values(array_filter(
explode(PHP_EOL, $docComment),
fn (string $line): bool => ! str_contains($line, '* @',
))),
];
}
if ($namesToCheck === []) {
return [];
}
$issues = [];
foreach ($namesToCheck as $name) {
$issues = [
...$issues,
...array_map(
fn (Misspelling $misspelling): Issue => new Issue(
$misspelling,
$file->getRealPath(),
$this->getErrorLine($file, $name),
), $this->spellchecker->check(SpellcheckFormatter::format($name))),
];
}
return $issues;
}
|
Get the issues from the given source file.
@return array<int, Issue>
|
getIssuesFromSourceFile
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getMethodNames(ReflectionClass $reflection): array
{
$methods = array_filter(
$reflection->getMethods(),
function (ReflectionMethod $method) use ($reflection): bool {
foreach ($reflection->getTraits() as $trait) {
if ($trait->hasMethod($method->getName())) {
return false;
}
}
return $method->class === $reflection->name;
},
);
foreach ($methods as $method) {
$namesToCheck[] = $method->getName();
$namesToCheck = [
...$namesToCheck,
...$this->getMethodParameters($method),
];
if ($docComment = $method->getDocComment()) {
$namesToCheck = [
...$namesToCheck,
...array_values(array_filter(
explode(PHP_EOL, $docComment),
fn (string $line): bool => ! str_contains($line, '* @',
))),
];
}
}
return $namesToCheck ?? [];
}
|
Get the method names contained in the given reflection.
@param ReflectionClass<object> $reflection
@return array<int, string>
|
getMethodNames
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getMethodParameters(ReflectionMethod $method): array
{
return array_map(
fn (ReflectionParameter $parameter): string => $parameter->getName(),
$method->getParameters(),
);
}
|
Get the method parameters names contained in the given method.
@return array<int, string>
|
getMethodParameters
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getConstantNames(ReflectionClass $reflection): array
{
return array_map(
fn (ReflectionClassConstant $constant): string => $constant->name,
array_values(array_filter(
$reflection->getReflectionConstants(),
function (ReflectionClassConstant $constant) use ($reflection): bool {
if ($constant->class !== $reflection->name) {
return false;
}
foreach ($reflection->getTraits() as $trait) {
if ($trait->hasConstant($constant->getName())) {
return false;
}
}
return true;
}
))
);
}
|
Get the constant names and their values contained in the given reflection.
This also includes cases from enums and their values (for string backed enums).
@param ReflectionClass<object> $reflection
@return array<int, string>
|
getConstantNames
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getPropertyNames(ReflectionClass $reflection): array
{
$properties = array_filter(
$reflection->getProperties(),
function (ReflectionProperty $property) use ($reflection): bool {
foreach ($reflection->getTraits() as $trait) {
if ($trait->hasProperty($property->getName())) {
return false;
}
}
return $property->class === $reflection->name;
},
);
$propertiesNames = array_map(
fn (ReflectionProperty $property): string => $property->getName(),
$properties,
);
$propertiesDocComments = array_reduce(
array_map(
fn (ReflectionProperty $property): array => explode(PHP_EOL, $property->getDocComment() ?: ''),
$properties,
),
fn (array $carry, array $item): array => [
...$carry,
...$item,
],
[],
);
return [
...$propertiesNames,
...$propertiesDocComments,
];
}
|
Get the property names contained in the given reflection.
@param ReflectionClass<object> $reflection
@return array<int, string>
|
getPropertyNames
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getFullyQualifiedDefinitionName(SplFileInfo $file): ?string
{
if (preg_match('/namespace (.*);/', $file->getContents(), $matches)) {
/** @var class-string $fullyQualifiedName */
$fullyQualifiedName = $matches[1].'\\'.$file->getFilenameWithoutExtension();
return $fullyQualifiedName;
}
return null;
}
|
Get the fully qualified definition name of the class, enum or trait.
@return class-string<object>|null
|
getFullyQualifiedDefinitionName
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function getErrorLine(SplFileInfo $file, string $misspellingWord): int
{
$contentsArray = explode(PHP_EOL, $file->getContents());
$contentsArrayLines = array_map(fn ($lineNumber): int => $lineNumber + 1, array_keys($contentsArray));
$lines = array_values(array_filter(
array_map(
fn (string $line, int $lineNumber): ?int => str_contains($line, $misspellingWord) ? $lineNumber : null,
$contentsArray,
$contentsArrayLines,
),
));
if ($lines === []) {
return 0;
}
return $lines[0];
}
|
Get the line number of the error.
|
getErrorLine
|
php
|
peckphp/peck
|
src/Checkers/SourceCodeChecker.php
|
https://github.com/peckphp/peck/blob/master/src/Checkers/SourceCodeChecker.php
|
MIT
|
private function findPathToScan(InputInterface $input): string
{
$passedDirectory = $input->getOption('path');
if (! is_string($passedDirectory)) {
return $this->inferProjectPath();
}
return $passedDirectory;
}
|
Decides whether to use a passed directory, or figure out the directory to scan automatically
|
findPathToScan
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function inferProjectPath(): string
{
$basePath = ProjectPath::get();
return match (true) {
isset($_ENV['APP_BASE_PATH']) => $_ENV['APP_BASE_PATH'],
default => $basePath,
};
}
|
Infer the project's base directory from the environment.
|
inferProjectPath
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function renderLineIssue(Issue $issue): void
{
$relativePath = str_replace((string) getcwd(), '.', $issue->file);
$lines = file($issue->file);
$lineContent = $lines[$issue->line - 1] ?? '';
$column = $this->getIssueColumn($issue, $lineContent);
$this->lastColumn[$issue->file][$issue->line][$issue->misspelling->word] = $column;
$lineInfo = ":{$issue->line}:$column";
$alignSpacer = str_repeat(' ', 6);
$spacer = str_repeat('-', $column);
$suggestions = $this->formatIssueSuggestionsForDisplay(
$issue,
);
render(<<<HTML
<div class="mx-2 mb-1">
<div class="space-x-1">
<span class="bg-red text-white px-1 font-bold">Misspelling</span>
<span><strong><a href="{$issue->file}{$lineInfo}">{$relativePath}{$lineInfo}</a></strong>: '<strong>{$issue->misspelling->word}</strong>'</span>
<code start-line="{$issue->line}">{$lineContent}</code>
<pre class="text-red-500 font-bold">{$alignSpacer}{$spacer}^</pre>
</div>
<div class="space-x-1 text-gray-700">
<span>Did you mean:</span>
<span class="font-bold">{$suggestions}</span>
</div>
</div>
HTML
);
}
|
Render the issue with the line.
|
renderLineIssue
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function renderLineLessIssue(Issue $issue): void
{
$relativePath = str_replace((string) getcwd(), '.', $issue->file);
$column = $this->getIssueColumn($issue, $relativePath);
$this->lastColumn[$issue->file][$issue->line][$issue->misspelling->word] = $column;
$spacer = str_repeat('-', $column);
$suggestions = $this->formatIssueSuggestionsForDisplay(
$issue,
);
render(<<<HTML
<div class="mx-2 mb-1">
<div class="space-x-1">
<span class="bg-red text-white px-1 font-bold">Misspelling</span>
<span><strong><a href="{$issue->file}">{$relativePath}</a></strong>: '<strong>{$issue->misspelling->word}</strong>'</span>
<pre class="text-blue-300 font-bold">{$relativePath}</pre>
<pre class="text-red-500 font-bold">{$spacer}^</pre>
</div>
<div class="space-x-1 text-gray-700">
<span>Did you mean:</span>
<span class="font-bold">{$suggestions}</span>
</div>
</div>
HTML);
}
|
Render the issue without the line.
|
renderLineLessIssue
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function renderStaticTextLineIssue(Issue $issue): void
{
$suggestions = $this->formatIssueSuggestionsForDisplay(
$issue,
);
render(<<<HTML
<div class="mx-2 mt-1 space-y-1">
<div class="space-x-1">
<span class="bg-red text-white px-1 font-bold">Misspelling</span>
<span>'<strong>{$issue->misspelling->word}</strong>'</span>
</div>
<div class="space-x-1 text-gray-700">
<span>Did you mean:</span>
<span class="font-bold">{$suggestions}</span>
</div>
</div>
HTML
);
}
|
Render the issue from --text option.
|
renderStaticTextLineIssue
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function getIssueColumn(Issue $issue, string $lineContent): int
{
$fromColumn = isset($this->lastColumn[$issue->file][$issue->line][$issue->misspelling->word])
? $this->lastColumn[$issue->file][$issue->line][$issue->misspelling->word] + 1 : 0;
return (int) strpos(strtolower($lineContent), $issue->misspelling->word, $fromColumn);
}
|
Get the column of the issue in the line.
|
getIssueColumn
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function addMisspellingsToConfig(array $issues): void
{
$misspellings = array_map(
fn (Issue $issue): string => $issue->misspelling->word,
$issues,
);
Config::instance()->ignoreWords(array_unique($misspellings));
}
|
Add misspellings to the configuration file.
@param array<int, Issue> $issues
|
addMisspellingsToConfig
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
private function checkStaticText(string $text, float $startTime): int
{
$aspell = Aspell::default();
$misspellings = $aspell->check($text);
if ($misspellings === []) {
render(<<<HTML
<div class="mx-2 my-1">
<div class="space-x-1 mb-1">
<span class="bg-green text-white px-1 font-bold">PASS</span>
<span>No misspellings found in the given text.</span>
</div>
<div class="space-x-1 text-gray-700">
<span>Duration:</span>
<span class="font-bold">{$this->getDuration($startTime)}s</span>
</div>
</div>
HTML
);
return Command::SUCCESS;
}
$issues = array_map(
fn ($misspelling): Issue => new Issue($misspelling, '', 0),
$misspellings,
);
foreach ($issues as $issue) {
$this->renderStaticTextLineIssue($issue);
}
$issuesCount = count($misspellings);
render(<<<HTML
<div class="mx-2 my-1 space-y-1">
<div class="space-x-1">
<span class="bg-red text-white px-1 font-bold">FAIL</span>
<span>{$issuesCount} misspelling(s) found in the given text.</span>
</div>
<div class="space-x-1 text-gray-700">
<span>Duration:</span>
<span class="font-bold">{$this->getDuration($startTime)}s</span>
</div>
</div>
HTML
);
return Command::FAILURE;
}
|
Check the given text from --text option for misspellings.
|
checkStaticText
|
php
|
peckphp/peck
|
src/Console/Commands/CheckCommand.php
|
https://github.com/peckphp/peck/blob/master/src/Console/Commands/CheckCommand.php
|
MIT
|
public static function default(): self
{
$basePath = __DIR__.'/../../';
$cache = new self("{$basePath}/.peck.cache");
$cache->get('__internal_version') === self::VERSION ?: $cache->flush();
$cache->set('__internal_version', self::VERSION);
return $cache;
}
|
Creates the default instance of Spellchecker.
|
default
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
public function get(string $key): mixed
{
$key = $this->getCacheKey($key);
$cacheFile = $this->getCacheFile($key);
if (! file_exists($cacheFile)) {
return null;
}
$serializedContents = file_get_contents($cacheFile);
if ($serializedContents === false || ! $this->isSerialized($serializedContents)) {
return null;
}
return unserialize($serializedContents);
}
|
Gets the value from the cache.
|
get
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
public function set(string $key, mixed $value): void
{
$key = $this->getCacheKey($key);
file_put_contents($this->getCacheFile($key), serialize($value));
}
|
Sets the given value in the cache.
|
set
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
public function has(string $key): bool
{
$key = $this->getCacheKey($key);
return is_readable($this->getCacheFile($key));
}
|
Checks if the cache has the given key.
|
has
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
public function getCacheFile(string $key): string
{
if (! is_dir($this->cacheDirectory) && ! mkdir($this->cacheDirectory, 0755, true)) {
throw new RuntimeException("Could not create cache directory: {$this->cacheDirectory}");
}
$separator = str_ends_with($this->cacheDirectory, '/') ? '' : DIRECTORY_SEPARATOR;
return $this->cacheDirectory.$separator.$key;
}
|
Gets the cache file for the given key.
|
getCacheFile
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
public function getCacheKey(string $key): string
{
return md5($key);
}
|
Gets the cache key for the given key.
|
getCacheKey
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
private function isSerialized(string $string): bool
{
return $string === serialize(false) || @unserialize($string) !== false;
}
|
Checks if the given string is serialized.
|
isSerialized
|
php
|
peckphp/peck
|
src/Plugins/Cache.php
|
https://github.com/peckphp/peck/blob/master/src/Plugins/Cache.php
|
MIT
|
public static function default(): self
{
return new self(
Config::instance(),
Cache::default(),
);
}
|
Creates the default instance of Spellchecker.
|
default
|
php
|
peckphp/peck
|
src/Services/Spellcheckers/Aspell.php
|
https://github.com/peckphp/peck/blob/master/src/Services/Spellcheckers/Aspell.php
|
MIT
|
public function check(string $text): array
{
/** @var array<int, Misspelling>|null $misspellings */
$misspellings = $this->cache->has($text) ? $this->cache->get($text) : $this->getMisspellings($text);
if (! is_array($misspellings)) {
$misspellings = $this->getMisspellings($text);
}
return array_filter($misspellings,
fn (Misspelling $misspelling): bool => ! $this->config->isWordIgnored($misspelling->word),
);
}
|
Checks of issues in the given text.
@return array<int, Misspelling>
|
check
|
php
|
peckphp/peck
|
src/Services/Spellcheckers/Aspell.php
|
https://github.com/peckphp/peck/blob/master/src/Services/Spellcheckers/Aspell.php
|
MIT
|
private function getMisspellings(string $text): array
{
$misspellings = iterator_to_array($this->run($text));
$this->cache->set($text, $misspellings);
return $misspellings;
}
|
Gets the misspellings from the given text.
@return array<int, Misspelling>
|
getMisspellings
|
php
|
peckphp/peck
|
src/Services/Spellcheckers/Aspell.php
|
https://github.com/peckphp/peck/blob/master/src/Services/Spellcheckers/Aspell.php
|
MIT
|
private function takeSuggestions(array $suggestions): array
{
$suggestions = array_filter($suggestions,
fn (string $suggestion): bool => in_array(preg_match('/[^a-zA-Z]/', $suggestion), [0, false], true)
);
return array_slice(array_values(array_unique($suggestions)), 0, 4);
}
|
Take the relevant suggestions from the given misspelling.
@param array<int, string> $suggestions
@return array<int, string>
|
takeSuggestions
|
php
|
peckphp/peck
|
src/Services/Spellcheckers/Aspell.php
|
https://github.com/peckphp/peck/blob/master/src/Services/Spellcheckers/Aspell.php
|
MIT
|
private function run(string $text): array
{
$process = self::$process ??= $this->createProcess();
$process->setInput($text);
$process->mustRun();
$output = $process->getOutput();
return array_values(array_map(function (string $line): Misspelling {
[$wordMetadataAsString, $suggestionsAsString] = explode(':', trim($line));
$word = explode(' ', $wordMetadataAsString)[1];
$suggestions = explode(', ', trim($suggestionsAsString));
return new Misspelling($word, $this->takeSuggestions($suggestions));
}, array_filter(explode(PHP_EOL, $output), fn (string $line): bool => str_starts_with($line, '&'))));
}
|
Runs the Aspell command with the given text and returns the suggestions, if any.
@return array<int, Misspelling>
|
run
|
php
|
peckphp/peck
|
src/Services/Spellcheckers/Aspell.php
|
https://github.com/peckphp/peck/blob/master/src/Services/Spellcheckers/Aspell.php
|
MIT
|
public static function get(string $in, array $paths): array
{
$paths = array_map(
fn (string $path): string => (realpath(ProjectPath::get())).'/'.ltrim(ltrim($path, '/'), './'),
$paths,
);
return array_map(
fn (string $path): string => ltrim(str_replace((string) realpath($in), '', $path), '/'),
$paths,
);
}
|
Gets the not paths for the given in / paths.
@param array<int, string> $paths
@return array<int, string>
|
get
|
php
|
peckphp/peck
|
src/Support/NotPaths.php
|
https://github.com/peckphp/peck/blob/master/src/Support/NotPaths.php
|
MIT
|
public static function whitelistedWords(?string $preset): array
{
if ($preset === null || ! self::stubExists($preset)) {
return [];
}
return [
...self::getWordsFromStub('base'),
...self::getWordsFromStub('iso4217'),
...self::getWordsFromStub('iso3166'),
...self::getWordsFromStub($preset),
];
}
|
Returns the whitelisted words for the given preset.
@return array<int, string>
|
whitelistedWords
|
php
|
peckphp/peck
|
src/Support/PresetProvider.php
|
https://github.com/peckphp/peck/blob/master/src/Support/PresetProvider.php
|
MIT
|
private static function getWordsFromStub(string $preset): array
{
$path = sprintf('%s/%s.stub', self::PRESET_STUBS_DIRECTORY, $preset);
return array_values(array_filter(array_map('trim', explode("\n", (string) file_get_contents($path)))));
}
|
Gets the words from the given stub.
@return array<int, string>
|
getWordsFromStub
|
php
|
peckphp/peck
|
src/Support/PresetProvider.php
|
https://github.com/peckphp/peck/blob/master/src/Support/PresetProvider.php
|
MIT
|
private static function stubExists(string $preset): bool
{
return file_exists(sprintf('%s/%s.stub', self::PRESET_STUBS_DIRECTORY, $preset));
}
|
Checks if the given preset exists.
|
stubExists
|
php
|
peckphp/peck
|
src/Support/PresetProvider.php
|
https://github.com/peckphp/peck/blob/master/src/Support/PresetProvider.php
|
MIT
|
public static function get(): string
{
return dirname(array_keys(ClassLoader::getRegisteredLoaders())[0]);
}
|
Gets the path of the project.
|
get
|
php
|
peckphp/peck
|
src/Support/ProjectPath.php
|
https://github.com/peckphp/peck/blob/master/src/Support/ProjectPath.php
|
MIT
|
public static function format(string $input): string
{
// Remove leading underscores
$input = ltrim($input, '_');
// Replace special characters with spaces
$input = (string) preg_replace('/[!@#$%^&<>():.|,\/\\\\_\-*]/', ' ', $input);
// Insert spaces between lowercase and uppercase letters (camelCase or PascalCase)
$input = (string) preg_replace('/([a-z])([A-Z])/', '$1 $2', $input);
// Split sequences of uppercase letters, ensuring the last uppercase letter starts a new word
$input = (string) preg_replace('/([A-Z]+)([A-Z][a-z])/', '$1 $2', $input);
// Replace multiple spaces with a single space
$input = (string) preg_replace('/\s+/', ' ', $input);
// Convert the final result to lowercase
return trim(strtolower($input));
}
|
Transforms the given input (method or class names) into a
human-readable format which can be used for spellchecking.
|
format
|
php
|
peckphp/peck
|
src/Support/SpellcheckFormatter.php
|
https://github.com/peckphp/peck/blob/master/src/Support/SpellcheckFormatter.php
|
MIT
|
public function __construct(
public string $word,
public array $suggestions,
) {}
|
Creates a new instance of Issue.
@param array<int, string> $suggestions
|
__construct
|
php
|
peckphp/peck
|
src/ValueObjects/Misspelling.php
|
https://github.com/peckphp/peck/blob/master/src/ValueObjects/Misspelling.php
|
MIT
|
public function methodWithDocBlockTypoError(): string
{
return 'This is a method with a doc block typo error';
}
|
This is a metohd with a doc block typo error
|
methodWithDocBlockTypoError
|
php
|
peckphp/peck
|
tests/Fixtures/ClassesToTest/ClassWithTypoErrors.php
|
https://github.com/peckphp/peck/blob/master/tests/Fixtures/ClassesToTest/ClassWithTypoErrors.php
|
MIT
|
private function methodWithSpellingMistakeInDocBlock(): void
{
// This is a method with a spelling mistake in doc block.
}
|
This is a method with a spellling mistake in the doc block.
|
methodWithSpellingMistakeInDocBlock
|
php
|
peckphp/peck
|
tests/Fixtures/ClassesToTest/TraitWithTypo.php
|
https://github.com/peckphp/peck/blob/master/tests/Fixtures/ClassesToTest/TraitWithTypo.php
|
MIT
|
private function methodWithSpellingMistakeInDocBlock(): void
{
// This is a method with a spelling mistake in doc block.
}
|
This is a method with a spellling mistake in the doc block.
|
methodWithSpellingMistakeInDocBlock
|
php
|
peckphp/peck
|
tests/Fixtures/EnumsToTest/BackendEnumWithTypoErrors.php
|
https://github.com/peckphp/peck/blob/master/tests/Fixtures/EnumsToTest/BackendEnumWithTypoErrors.php
|
MIT
|
private function methodWithSpellingMistakeInDocBlock(): void
{
// This is a method with a spelling mistake in doc block.
}
|
This is a method with a spellling mistake in the doc block.
|
methodWithSpellingMistakeInDocBlock
|
php
|
peckphp/peck
|
tests/Fixtures/EnumsToTest/UnitEnumWithTypoErrors.php
|
https://github.com/peckphp/peck/blob/master/tests/Fixtures/EnumsToTest/UnitEnumWithTypoErrors.php
|
MIT
|
private function nullOr(ReflectionMethod $method, int $indent): ?string
{
return $this->assertion($method, 'nullOr%s', '%s|null', $indent, function (string $firstParameter, string $parameters) use ($method) {
return "null === {$firstParameter} || static::{$method->name}({$firstParameter}, {$parameters});";
});
}
|
@param ReflectionMethod $method
@param int $indent
@return string|null
@throws ReflectionException
|
nullOr
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function all(ReflectionMethod $method, int $indent): ?string
{
return $this->assertion($method, 'all%s', 'iterable<%s>', $indent, function (string $firstParameter, string $parameters) use ($method) {
return <<<BODY
static::isIterable({$firstParameter});
foreach ({$firstParameter} as \$entry) {
static::{$method->name}(\$entry, {$parameters});
}
BODY;
});
}
|
@param ReflectionMethod $method
@param int $indent
@return string|null
@throws ReflectionException
|
all
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function allNullOr(ReflectionMethod $method, int $indent): ?string
{
return $this->assertion($method, 'allNullOr%s', 'iterable<%s|null>', $indent, function (string $firstParameter, string $parameters) use ($method) {
return <<<BODY
static::isIterable({$firstParameter});
foreach ({$firstParameter} as \$entry) {
null === \$entry || static::{$method->name}(\$entry, {$parameters});
}
BODY;
});
}
|
@param ReflectionMethod $method
@param int $indent
@return string|null
@throws ReflectionException
|
allNullOr
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function assertion(ReflectionMethod $method, string $methodNameTemplate, string $typeTemplate, int $indent, callable $body): ?string
{
$newMethodName = sprintf($methodNameTemplate, ucfirst($method->name));
$comment = $method->getDocComment();
$parsedComment = $this->parseDocComment($comment);
$parameters = [];
/** @psalm-var array<string, scalar|null> $parametersDefaults */
$parametersDefaults = [];
$parametersReflection = $method->getParameters();
foreach ($parametersReflection as $parameterReflection) {
$parameters[] = $parameterReflection->name;
if ($parameterReflection->isDefaultValueAvailable()) {
/** @var mixed $defaultValue */
$defaultValue = $parameterReflection->getDefaultValue();
Assert::nullOrScalar($defaultValue);
$parametersDefaults[$parameterReflection->name] = $defaultValue;
}
}
if (in_array($newMethodName, $this->skipMethods, true)) {
return null;
}
$paramsAdded = false;
$phpdocLines = [];
foreach ($parsedComment as $key => $values) {
if ($this->shouldSkipAnnotation($newMethodName, $key)) {
continue;
}
if ($paramsAdded || 'param' === $key) {
$paramsAdded = true;
if (count($phpdocLines) > 0) {
$phpdocLines[] = '';
}
}
if ('deprecated' === $key) {
$phpdocLines[] = '';
}
$longestType = 0;
$longestName = 0;
foreach ($values as $i => $value) {
$parts = $this->splitDocLine($value);
if (('param' === $key || 'psalm-param' === $key) && isset($parts[1]) && $parts[1] === '$'.$parameters[0] && 'mixed' !== $parts[0]) {
$parts[0] = $this->applyTypeTemplate($parts[0], $typeTemplate);
$values[$i] = implode(' ', $parts);
}
}
if ('param' === $key) {
[$longestType, $longestName] = $this->findLongestTypeAndName($values);
}
foreach ($values as $value) {
$parts = $this->splitDocLine($value);
$type = $parts[0];
if ('psalm-assert' === $key) {
$type = $this->applyTypeTemplate($type, $typeTemplate);
}
if ('param' === $key) {
if (!array_key_exists(1, $parts)) {
throw new RuntimeException(sprintf('param key must come with type and variable name in method: %s', $method->name));
}
$type = str_pad($type, $longestType, ' ');
$parts[1] = str_pad($parts[1], $longestName, ' ');
}
$comment = sprintf('@%s %s', $key, $type);
if (count($parts) >= 2) {
$comment .= sprintf(' %s', implode(' ', array_slice($parts, 1)));
}
$phpdocLines[] = trim($comment);
}
if ('deprecated' === $key || 'psalm-pure' === $key) {
$phpdocLines[] = '';
}
}
$phpdocLinesDeduplicatedEmptyLines = [];
foreach ($phpdocLines as $line) {
$currentLine = trim($line);
if ('' === $currentLine && count($phpdocLinesDeduplicatedEmptyLines) > 0) {
$previousLine = trim($phpdocLinesDeduplicatedEmptyLines[count($phpdocLinesDeduplicatedEmptyLines) - 1]);
if ('' === $previousLine) {
continue;
}
}
$phpdocLinesDeduplicatedEmptyLines[] = $line;
}
return $this->staticMethod($newMethodName, $parameters, $parametersDefaults, $phpdocLinesDeduplicatedEmptyLines, $indent, $body);
}
|
@psalm-param callable(string,string):string $body
@param ReflectionMethod $method
@param string $methodNameTemplate
@param string $typeTemplate
@param int $indent
@param callable $body
@return string|null
@throws ReflectionException
|
assertion
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function findLongestTypeAndName(array $values): array
{
$longestType = 0;
$longestName = 0;
foreach ($values as $value) {
$parts = $this->splitDocLine($value);
$type = $parts[0];
if (strlen($type) > $longestType) {
$longestType = strlen($type);
}
if (!array_key_exists(1, $parts)) {
continue;
}
$name = $parts[1];
if (strlen($name) > $longestName) {
$longestName = strlen($name);
}
}
return [$longestType, $longestName];
}
|
@psalm-param array<int, string> $values
@psalm-return array{int, int}
@param string[] $values
@return int[]
|
findLongestTypeAndName
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function staticMethod(string $name, array $parameters, array $defaultValues, array $phpdocLines, int $indent, callable $body): string
{
$indentation = str_repeat(' ', $indent);
$staticFunction = $this->phpdoc($phpdocLines, $indent)."\n";
$staticFunction .= $indentation.'public static function '.$name.$this->functionParameters($parameters, $defaultValues)."\n"
.$indentation."{\n";
$firstParameter = '$'.array_shift($parameters);
$parameters = implode(', ', \array_map(static function (string $parameter): string {
return '$'.$parameter;
}, $parameters));
$staticFunction .= preg_replace('/(?<=^|\n)(?!\n)/', $indentation.$indentation, $body($firstParameter, $parameters))."\n";
$staticFunction .= $indentation.'}';
return $staticFunction;
}
|
@psalm-param list<string> $parameters
@psalm-param array<string, scalar|null> $defaultValues
@psalm-param list<string> $phpdocLines
@psalm-param callable(string,string):string $body
@param string $name
@param string[] $parameters
@param string[] $defaultValues
@param array $phpdocLines
@param int $indent
@param callable $body
@return string
|
staticMethod
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function functionParameters(array $parameters, array $defaultValues): string
{
$result = '';
foreach ($parameters as $i => $parameter) {
if ($i > 0) {
$result .= ', ';
}
$result .= '$'.$parameter;
if (array_key_exists($parameter, $defaultValues)) {
$defaultValue = null === $defaultValues[$parameter] ? 'null' : var_export($defaultValues[$parameter], true);
$result .= ' = '.$defaultValue;
}
}
return '('.$result.')';
}
|
@psalm-param list<string> $parameters
@psalm-param array<string, scalar|null> $defaultValues
@param string[] $parameters
@param string[] $defaultValues
@return string
|
functionParameters
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function phpdoc(array $lines, int $indent): string
{
$indentation = str_repeat(' ', $indent);
$phpdoc = $indentation.'/**';
$throws = '';
foreach ($lines as $line) {
if (strpos($line, '@throws') === 0) {
$throws .= "\n".$indentation.rtrim(' * '.$line);
} else {
$phpdoc .= "\n".$indentation.rtrim(' * '.$line);
}
}
$phpdoc .= "\n".$indentation.' * @return void';
if (strlen($throws) > 0) {
$phpdoc .= "\n".$indentation.' *';
$phpdoc .= $throws;
}
$phpdoc .= "\n".$indentation.' */';
return $phpdoc;
}
|
@psalm-param list<string> $lines
@param string[] $lines
@param int $indent
@return string
|
phpdoc
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function parseDocComment(string $comment): array
{
$lines = explode("\n", $comment);
$result = [];
foreach ($lines as $line) {
if (preg_match('~^\*\s+@(\S+)(\s+.*)?$~', trim($line), $matches)) {
if (2 === count($matches)) {
$matches[2] = '';
}
$result[$matches[1]][] = trim($matches[2]);
}
}
return $result;
}
|
@psalm-return array<string, list<string>>
@param string $comment
@return string[][]
|
parseDocComment
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function splitDocLine(string $line): array
{
if (!preg_match('~^(.*)\s+(\$\S+)(?:\s+(.*))?$~', $line, $matches)) {
return [$line];
}
$parts = [trim($matches[1]), $matches[2]];
if (count($matches) > 3) {
$parts[2] = $matches[3];
}
return $parts;
}
|
@psalm-return array{0: string, 1?: string, 2?: string}
@param string $line
@return string[]
|
splitDocLine
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
private function getMethods(ReflectionClass $assert): array
{
$methods = [];
$staticMethods = $assert->getMethods(ReflectionMethod::IS_STATIC);
foreach ($staticMethods as $staticMethod) {
$modifiers = $staticMethod->getModifiers();
if (0 === ($modifiers & ReflectionMethod::IS_PUBLIC)) {
continue;
}
if ($staticMethod->getFileName() !== $assert->getFileName()) {
// Skip this method - was imported by generated mixin
continue;
}
if ('__callStatic' === $staticMethod->name) {
continue;
}
$methods[] = $staticMethod;
}
return $methods;
}
|
@psalm-return list<ReflectionMethod>
@param ReflectionClass $assert
@return ReflectionMethod[]
|
getMethods
|
php
|
webmozarts/assert
|
bin/src/MixinGenerator.php
|
https://github.com/webmozarts/assert/blob/master/bin/src/MixinGenerator.php
|
MIT
|
public static function string($value, $message = '')
{
if (!\is_string($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a string. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert string $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
string
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function stringNotEmpty($value, $message = '')
{
static::string($value, $message);
static::notEq($value, '', $message);
}
|
@psalm-pure
@psalm-assert non-empty-string $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
stringNotEmpty
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function integer($value, $message = '')
{
if (!\is_int($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an integer. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert int $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
integer
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function integerish($value, $message = '')
{
if (!\is_numeric($value) || $value != (int) $value) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an integerish value. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert numeric $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
integerish
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function positiveInteger($value, $message = '')
{
if (!(\is_int($value) && $value > 0)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a positive integer. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert positive-int $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
positiveInteger
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function float($value, $message = '')
{
if (!\is_float($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a float. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert float $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
float
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function numeric($value, $message = '')
{
if (!\is_numeric($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a numeric. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert numeric $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
numeric
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function natural($value, $message = '')
{
if (!\is_int($value) || $value < 0) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a non-negative integer. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert positive-int|0 $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
natural
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function boolean($value, $message = '')
{
if (!\is_bool($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a boolean. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert bool $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
boolean
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function scalar($value, $message = '')
{
if (!\is_scalar($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a scalar. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert scalar $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
scalar
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function object($value, $message = '')
{
if (!\is_object($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an object. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert object $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
object
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function resource($value, $type = null, $message = '')
{
if (!\is_resource($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a resource. Got: %s',
static::typeToString($value),
$type // User supplied message might include the second placeholder.
));
}
if ($type && $type !== \get_resource_type($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a resource of type %2$s. Got: %s',
static::typeToString($value),
$type
));
}
}
|
@psalm-pure
@psalm-assert resource $value
@param mixed $value
@param string|null $type type of resource this should be. @see https://www.php.net/manual/en/function.get-resource-type.php
@param string $message
@throws InvalidArgumentException
|
resource
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isCallable($value, $message = '')
{
if (!\is_callable($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a callable. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert callable $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isCallable
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isArray($value, $message = '')
{
if (!\is_array($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an array. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert array $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isArray
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isTraversable($value, $message = '')
{
@\trigger_error(
\sprintf(
'The "%s" assertion is deprecated. You should stop using it, as it will soon be removed in 2.0 version. Use "isIterable" or "isInstanceOf" instead.',
__METHOD__
),
\E_USER_DEPRECATED
);
if (!\is_array($value) && !($value instanceof Traversable)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a traversable. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert iterable $value
@deprecated use "isIterable" or "isInstanceOf" instead
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isTraversable
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isArrayAccessible($value, $message = '')
{
if (!\is_array($value) && !($value instanceof ArrayAccess)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an array accessible. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert array|ArrayAccess $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isArrayAccessible
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isCountable($value, $message = '')
{
if (
!\is_array($value)
&& !($value instanceof Countable)
&& !($value instanceof ResourceBundle)
&& !($value instanceof SimpleXMLElement)
) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a countable. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert countable $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isCountable
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isIterable($value, $message = '')
{
if (!\is_array($value) && !($value instanceof Traversable)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an iterable. Got: %s',
static::typeToString($value)
));
}
}
|
@psalm-pure
@psalm-assert iterable $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isIterable
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isInstanceOf($value, $class, $message = '')
{
if (!($value instanceof $class)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an instance of %2$s. Got: %s',
static::typeToString($value),
$class
));
}
}
|
@psalm-pure
@psalm-template ExpectedType of object
@psalm-param class-string<ExpectedType> $class
@psalm-assert ExpectedType $value
@param mixed $value
@param string|object $class
@param string $message
@throws InvalidArgumentException
|
isInstanceOf
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function notInstanceOf($value, $class, $message = '')
{
if ($value instanceof $class) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an instance other than %2$s. Got: %s',
static::typeToString($value),
$class
));
}
}
|
@psalm-pure
@psalm-template ExpectedType of object
@psalm-param class-string<ExpectedType> $class
@psalm-assert !ExpectedType $value
@param mixed $value
@param string|object $class
@param string $message
@throws InvalidArgumentException
|
notInstanceOf
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isInstanceOfAny($value, array $classes, $message = '')
{
foreach ($classes as $class) {
if ($value instanceof $class) {
return;
}
}
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an instance of any of %2$s. Got: %s',
static::typeToString($value),
\implode(', ', \array_map(array(static::class, 'valueToString'), $classes))
));
}
|
@psalm-pure
@psalm-param array<class-string> $classes
@param mixed $value
@param array<object|string> $classes
@param string $message
@throws InvalidArgumentException
|
isInstanceOfAny
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isAOf($value, $class, $message = '')
{
static::string($class, 'Expected class as a string. Got: %s');
if (!\is_a($value, $class, \is_string($value))) {
static::reportInvalidArgument(sprintf(
$message ?: 'Expected an instance of this class or to this class among its parents "%2$s". Got: %s',
static::valueToString($value),
$class
));
}
}
|
@psalm-pure
@psalm-template ExpectedType of object
@psalm-param class-string<ExpectedType> $class
@psalm-assert ExpectedType|class-string<ExpectedType> $value
@param object|string $value
@param string $class
@param string $message
@throws InvalidArgumentException
|
isAOf
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isNotA($value, $class, $message = '')
{
static::string($class, 'Expected class as a string. Got: %s');
if (\is_a($value, $class, \is_string($value))) {
static::reportInvalidArgument(sprintf(
$message ?: 'Expected an instance of this class or to this class among its parents other than "%2$s". Got: %s',
static::valueToString($value),
$class
));
}
}
|
@psalm-pure
@psalm-template UnexpectedType of object
@psalm-param class-string<UnexpectedType> $class
@psalm-assert !UnexpectedType $value
@psalm-assert !class-string<UnexpectedType> $value
@param object|string $value
@param string $class
@param string $message
@throws InvalidArgumentException
|
isNotA
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isAnyOf($value, array $classes, $message = '')
{
foreach ($classes as $class) {
static::string($class, 'Expected class as a string. Got: %s');
if (\is_a($value, $class, \is_string($value))) {
return;
}
}
static::reportInvalidArgument(sprintf(
$message ?: 'Expected an instance of any of this classes or any of those classes among their parents "%2$s". Got: %s',
static::valueToString($value),
\implode(', ', $classes)
));
}
|
@psalm-pure
@psalm-param array<class-string> $classes
@param object|string $value
@param string[] $classes
@param string $message
@throws InvalidArgumentException
|
isAnyOf
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function isEmpty($value, $message = '')
{
if (!empty($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an empty value. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert empty $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
isEmpty
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function notEmpty($value, $message = '')
{
if (empty($value)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a non-empty value. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert !empty $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
notEmpty
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function null($value, $message = '')
{
if (null !== $value) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected null. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert null $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
null
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function notNull($value, $message = '')
{
if (null === $value) {
static::reportInvalidArgument(
$message ?: 'Expected a value other than null.'
);
}
}
|
@psalm-pure
@psalm-assert !null $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
notNull
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function true($value, $message = '')
{
if (true !== $value) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a value to be true. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert true $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
true
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function false($value, $message = '')
{
if (false !== $value) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a value to be false. Got: %s',
static::valueToString($value)
));
}
}
|
@psalm-pure
@psalm-assert false $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
false
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function notFalse($value, $message = '')
{
if (false === $value) {
static::reportInvalidArgument(
$message ?: 'Expected a value other than false.'
);
}
}
|
@psalm-pure
@psalm-assert !false $value
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
notFalse
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function ip($value, $message = '')
{
if (false === \filter_var($value, \FILTER_VALIDATE_IP)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a value to be an IP. Got: %s',
static::valueToString($value)
));
}
}
|
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
ip
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function ipv4($value, $message = '')
{
if (false === \filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a value to be an IPv4. Got: %s',
static::valueToString($value)
));
}
}
|
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
ipv4
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function ipv6($value, $message = '')
{
if (false === \filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a value to be an IPv6. Got: %s',
static::valueToString($value)
));
}
}
|
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
ipv6
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function email($value, $message = '')
{
if (false === \filter_var($value, FILTER_VALIDATE_EMAIL)) {
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected a value to be a valid e-mail address. Got: %s',
static::valueToString($value)
));
}
}
|
@param mixed $value
@param string $message
@throws InvalidArgumentException
|
email
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
public static function uniqueValues(array $values, $message = '')
{
$allValues = \count($values);
$uniqueValues = \count(\array_unique($values));
if ($allValues !== $uniqueValues) {
$difference = $allValues - $uniqueValues;
static::reportInvalidArgument(\sprintf(
$message ?: 'Expected an array of unique values, but %s of them %s duplicated',
$difference,
1 === $difference ? 'is' : 'are'
));
}
}
|
Does non strict comparisons on the items, so ['3', 3] will not pass the assertion.
@param array $values
@param string $message
@throws InvalidArgumentException
|
uniqueValues
|
php
|
webmozarts/assert
|
src/Assert.php
|
https://github.com/webmozarts/assert/blob/master/src/Assert.php
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.