Skip to content

Instantly share code, notes, and snippets.

@opdavies
Created September 26, 2024 23:43
Show Gist options
  • Save opdavies/a2f9d92cf3b67db6a64b9fca4e4e6697 to your computer and use it in GitHub Desktop.
Save opdavies/a2f9d92cf3b67db6a64b9fca4e4e6697 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace App;
use Drupal\atdc\Builder\PostBuilder;
use Drupal\node\Entity\Node as DrupalNode;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PhpParser\Node;
use PhpParser\Node\Name\FullyQualified;
/**
* @implements Rule<\PhpParser\Node\Expr\StaticCall>
*/
final class CreatingPostNodesOutsideTheRepositoryRule implements Rule {
public function getNodeType(): string {
return 'PhpParser\Node\Expr\StaticCall';
}
public function processNode(Node $node, Scope $scope): array {
if (!$node->class instanceof FullyQualified) {
return [];
}
if ($node->class->toString() !== DrupalNode::class) {
return [];
}
if ($node->name->toString() !== 'create') {
return [];
}
// Return is there are no arguments to Node::create().
// We only need to continue if the "type" is "post".
if (count($node->args) === 0) {
return [];
}
$items = $node->args[0]->value->items;
foreach ($items as $item) {
if ($item->key->value !== 'type' || $item->value->value !== 'post') {
return [];
}
}
// Allow creating a post within the PostBuilder.
if ($scope->isInClass()) {
$inClassReflection = $scope->getClassReflection();
if ($inClassReflection->getName() === PostBuilder::class) {
return [];
}
}
return [
RuleErrorBuilder::message('Create posts using the PostNodeRepository')
->build(),
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment