2018-07-31 08:54:00 +00:00
|
|
|
<?php declare(strict_types=1);
|
|
|
|
|
|
|
|
namespace Rector\NodeModifier;
|
|
|
|
|
|
|
|
use PhpParser\Node;
|
|
|
|
use PhpParser\Node\Stmt\Class_;
|
2018-07-31 09:15:27 +00:00
|
|
|
use PhpParser\Node\Stmt\ClassConst;
|
2018-07-31 08:54:00 +00:00
|
|
|
use PhpParser\Node\Stmt\ClassMethod;
|
|
|
|
use PhpParser\Node\Stmt\Property;
|
|
|
|
use Rector\Exception\InvalidNodeTypeException;
|
2018-09-21 05:12:24 +00:00
|
|
|
use function Safe\sprintf;
|
2018-07-31 08:54:00 +00:00
|
|
|
|
|
|
|
final class VisibilityModifier
|
|
|
|
{
|
2018-07-31 09:15:27 +00:00
|
|
|
/**
|
|
|
|
* @var string[]
|
|
|
|
*/
|
|
|
|
private $allowedNodeTypes = [ClassMethod::class, Property::class, ClassConst::class];
|
|
|
|
|
2018-07-31 08:54:00 +00:00
|
|
|
/**
|
|
|
|
* This way "abstract", "static", "final" are kept
|
|
|
|
*
|
2018-07-31 09:15:27 +00:00
|
|
|
* @param ClassMethod|Property|ClassConst $node
|
2018-07-31 08:54:00 +00:00
|
|
|
*/
|
2018-07-31 09:15:27 +00:00
|
|
|
public function removeOriginalVisibilityFromFlags(Node $node): void
|
2018-07-31 08:54:00 +00:00
|
|
|
{
|
|
|
|
$this->ensureIsClassMethodOrProperty($node, __METHOD__);
|
|
|
|
|
|
|
|
if ($node->isPublic()) {
|
|
|
|
$node->flags -= Class_::MODIFIER_PUBLIC;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($node->isProtected()) {
|
|
|
|
$node->flags -= Class_::MODIFIER_PROTECTED;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($node->isPrivate()) {
|
|
|
|
$node->flags -= Class_::MODIFIER_PRIVATE;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-31 09:15:27 +00:00
|
|
|
/**
|
|
|
|
* @param ClassMethod|Property|ClassConst $node
|
|
|
|
*/
|
|
|
|
public function addVisibilityFlag(Node $node, string $visibility): void
|
|
|
|
{
|
|
|
|
$this->ensureIsClassMethodOrProperty($node, __METHOD__);
|
|
|
|
|
|
|
|
if ($visibility === 'public') {
|
|
|
|
$node->flags |= Class_::MODIFIER_PUBLIC;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($visibility === 'protected') {
|
|
|
|
$node->flags |= Class_::MODIFIER_PROTECTED;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ($visibility === 'private') {
|
|
|
|
$node->flags |= Class_::MODIFIER_PRIVATE;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-31 08:54:00 +00:00
|
|
|
private function ensureIsClassMethodOrProperty(Node $node, string $location): void
|
|
|
|
{
|
2018-07-31 09:15:27 +00:00
|
|
|
foreach ($this->allowedNodeTypes as $allowedNodeType) {
|
|
|
|
if (is_a($node, $allowedNodeType, true)) {
|
|
|
|
return;
|
|
|
|
}
|
2018-07-31 08:54:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
throw new InvalidNodeTypeException(sprintf(
|
|
|
|
'"%s" only accepts "%s" types. "%s" given.',
|
|
|
|
$location,
|
2018-07-31 09:15:27 +00:00
|
|
|
implode('", "', $this->allowedNodeTypes),
|
2018-07-31 08:54:00 +00:00
|
|
|
get_class($node)
|
|
|
|
));
|
|
|
|
}
|
|
|
|
}
|