Skip to content

Commit

Permalink
Implement Nexus PHPStan
Browse files Browse the repository at this point in the history
  • Loading branch information
paulbalandan committed Aug 7, 2024
1 parent 80f84bd commit 4851283
Show file tree
Hide file tree
Showing 20 changed files with 865 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.{yml,yaml}]
[*.{neon,yml,yaml}]
indent_size = 2
3 changes: 3 additions & 0 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
__DIR__.'/tests',
__DIR__.'/tools',
])
->notPath([
'#PHPStan/.+/data/.+#',
])
->append([
__FILE__,
'bin/parallel-phpunit',
Expand Down
13 changes: 12 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
},
"replace": {
"nexusphp/clock": "self.version",
"nexusphp/option": "self.version"
"nexusphp/option": "self.version",
"nexusphp/phpstan-nexus": "self.version"
},
"provide": {
"psr/clock-implementation": "1.0"
Expand All @@ -44,6 +45,9 @@
},
"files": [
"src/Nexus/Option/functions.php"
],
"exclude-from-classmap": [
"tests/PHPStan/**/data/**"
]
},
"autoload-dev": {
Expand All @@ -59,6 +63,13 @@
"preferred-install": "dist",
"sort-packages": true
},
"extra": {
"phpstan": {
"includes": [
"src/Nexus/PHPStan/extension.neon"
]
}
},
"scripts": {
"post-update-cmd": [
"@composer update --ansi --working-dir=tools"
Expand Down
2 changes: 2 additions & 0 deletions phpstan.dist.neon
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
includes:
- vendor/phpstan/phpstan/conf/bleedingEdge.neon
- phpstan-baseline.php
- src/Nexus/PHPStan/extension.neon

parameters:
phpVersion: 80200
Expand All @@ -14,6 +15,7 @@ parameters:
- tools
excludePaths:
analyseAndScan:
- tests/PHPStan/**/data/**
- tools/vendor/**
bootstrapFiles:
- vendor/autoload.php
Expand Down
21 changes: 21 additions & 0 deletions src/Nexus/PHPStan/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 John Paul E. Balandan, CPA <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
47 changes: 47 additions & 0 deletions src/Nexus/PHPStan/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# PHPStan extensions for Nexus

These are Nexus-specific extensions and rules for [PHPStan](https://github.com/phpstan/phpstan).

## Installation

composer require --dev nexusphp/phpstan-nexus

If you also install [phpstan/extension-installer](https://github.com/phpstan/extension-installer) then you're all set!

<details>
<summary>Manual installation</summary>

If you don't want to use `phpstan/extension-installer`, include extension.neon in your project's PHPStan config:

```yml
includes:
- vendor/nexusphp/phpstan-nexus/extension.neon
```
</details>
## Rules
The following rules will automatically be enabled once the `extension.neon` is added:

1. Class constants, properties and methods, as well as functions, should follow the correct
naming convention:
* Class constants - UPPER_SNAKE_CASE format
* Class properties - camelCase format with no underscores
* Class methods - camelCase format with no underscores, except for magic methods where double
underscores are allowed
* Functions - lower_snake_case format

## License

Nexus Option is licensed under the [MIT License][5].

## Resources

* [Report issues][2] and [send pull requests][3] in the [main Nexus repository][4]

[1]: https://doc.rust-lang.org/std/option/enum.Option.html
[2]: https://github.com/NexusPHP/framework/issues
[3]: https://github.com/NexusPHP/framework/pulls
[4]: https://github.com/NexusPHP/framework
[5]: LICENSE
113 changes: 113 additions & 0 deletions src/Nexus/PHPStan/Rules/Constants/ClassConstantNamingRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\PHPStan\Rules\Constants;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\ConstantReflection;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;

/**
* @implements Rule<Node\Stmt\ClassConst>
*/
final class ClassConstantNamingRule implements Rule
{
public function getNodeType(): string
{
return Node\Stmt\ClassConst::class;
}

/**
* @param Node\Stmt\ClassConst $node
*/
public function processNode(Node $node, Scope $scope): array
{
if (! $scope->isInClass()) {
throw new ShouldNotHappenException(); // @codeCoverageIgnore
}

$errors = [];

foreach ($node->consts as $const) {
$errors = [
...$errors,
...$this->processSingleConstant($scope->getClassReflection(), $const),
];
}

return $errors;
}

/**
* @return list<IdentifierRuleError>
*/
private function processSingleConstant(ClassReflection $classReflection, Node\Const_ $const): array
{
$constantName = $const->name->toString();
$prototype = $this->findPrototype($classReflection, $constantName);

if (
null !== $prototype
&& ! str_starts_with($prototype->getDeclaringClass()->getDisplayName(), 'Nexus\\')
) {
return [];
}

if (preg_match('/^[A-Z][A-Z0-9_]+$/', $constantName) !== 1) {
return [
RuleErrorBuilder::message(\sprintf(
'Constant %s::%s should be in UPPER_SNAKE_CASE format.',
$classReflection->getDisplayName(),
$constantName,
))
->identifier('nexus.constantCasing')
->line($const->getStartLine())
->build(),
];
}

return [];
}

private function findPrototype(ClassReflection $classReflection, string $constantName): ?ConstantReflection
{
foreach ($classReflection->getImmediateInterfaces() as $immediateInterface) {
if ($immediateInterface->hasConstant($constantName)) {
return $immediateInterface->getConstant($constantName); // @codeCoverageIgnore
}
}

$parentClass = $classReflection->getParentClass();

if (null === $parentClass) {
return null; // @codeCoverageIgnore
}

if (! $parentClass->hasConstant($constantName)) {
return null;
}

$constant = $parentClass->getConstant($constantName);

if ($constant->isPrivate()) {
return null; // @codeCoverageIgnore
}

return $constant;
}
}
94 changes: 94 additions & 0 deletions src/Nexus/PHPStan/Rules/Functions/FunctionNamingRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php

declare(strict_types=1);

/**
* This file is part of the Nexus framework.
*
* (c) John Paul E. Balandan, CPA <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace Nexus\PHPStan\Rules\Functions;

use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\ShouldNotHappenException;

/**
* @implements Rule<Node\Stmt\Function_>
*/
final class FunctionNamingRule implements Rule
{
public function getNodeType(): string
{
return Node\Stmt\Function_::class;
}

/**
* @param Node\Stmt\Function_ $node
*/
public function processNode(Node $node, Scope $scope): array
{
if (null === $node->namespacedName) {
throw new ShouldNotHappenException(); // @codeCoverageIgnore
}

$functionName = $node->namespacedName->toString();

if (! str_starts_with($functionName, 'Nexus\\')) {
return [
RuleErrorBuilder::message(\sprintf(
'Function %s() should be namespaced using the "Nexus\\" namespace.',
$functionName,
))
->identifier('nexus.functionNamespace')
->build(),
];
}

$basename = basename(str_replace('\\', '/', $functionName));

if (preg_match('/^[a-z][a-z0-9_]+$/', $basename) !== 1) {
return [
RuleErrorBuilder::message(\sprintf(
'Function %s() should be in lower snake case format.',
$functionName,
))
->identifier('nexus.functionCasing')
->build(),
];
}

$errors = [];

foreach (array_values($node->params) as $index => $param) {
if (! $param->var instanceof Node\Expr\Variable) {
continue; // @codeCoverageIgnore
}

if (! \is_string($param->var->name)) {
continue; // @codeCoverageIgnore
}

if (preg_match('/^[a-z][a-zA-Z0-9]+$/', $param->var->name) !== 1) {
$errors[] = RuleErrorBuilder::message(\sprintf(
'Parameter #%d $%s of function %s() should be in camelCase format.',
$index + 1,
$param->var->name,
$functionName,
))
->identifier('nexus.functionParamCasing')
->line($param->getStartLine())
->build()
;
}
}

return $errors;
}
}
Loading

0 comments on commit 4851283

Please sign in to comment.