PhpParser\Node\Name::slice PHP Метод

slice() публичный Метод

This method returns a new instance of the same type as the original and with the same attributes. If the slice is empty, null is returned. The null value will be correctly handled in concatenations using concat(). Offset and length have the same meaning as in array_slice().
public slice ( integer $offset, integer | null $length = null ) : static | null
$offset integer Offset to start the slice at (may be negative)
$length integer | null Length of the slice (may be negative)
Результат static | null Sliced name
    public function slice($offset, $length = null)
    {
        $numParts = count($this->parts);
        $realOffset = $offset < 0 ? $offset + $numParts : $offset;
        if ($realOffset < 0 || $realOffset > $numParts) {
            throw new \OutOfBoundsException(sprintf('Offset %d is out of bounds', $offset));
        }
        if (null === $length) {
            $realLength = $numParts - $realOffset;
        } else {
            $realLength = $length < 0 ? $length + $numParts - $realOffset : $length;
            if ($realLength < 0 || $realLength > $numParts) {
                throw new \OutOfBoundsException(sprintf('Length %d is out of bounds', $length));
            }
        }
        if ($realLength === 0) {
            // Empty slice is represented as null
            return null;
        }
        return new static(array_slice($this->parts, $realOffset, $realLength), $this->attributes);
    }

Usage Example

Пример #1
0
 protected function resolveOtherName(Name $name, $type)
 {
     // fully qualified names are already resolved
     if ($name->isFullyQualified()) {
         return $name;
     }
     // resolve aliases for qualified names
     $aliasName = strtolower($name->getFirst());
     if ($name->isQualified() && isset($this->aliases[Stmt\Use_::TYPE_NORMAL][$aliasName])) {
         $alias = $this->aliases[Stmt\Use_::TYPE_NORMAL][$aliasName];
         return FullyQualified::concat($alias, $name->slice(1), $name->getAttributes());
     }
     if ($name->isUnqualified()) {
         if ($type === Stmt\Use_::TYPE_CONSTANT) {
             // constant aliases are case-sensitive, function aliases case-insensitive
             $aliasName = $name->getFirst();
         }
         if (!isset($this->aliases[$type][$aliasName])) {
             // unqualified, unaliased names cannot be resolved at compile-time
             return $name;
         }
         // resolve unqualified aliases
         return new FullyQualified($this->aliases[$type][$aliasName], $name->getAttributes());
     }
     if (null !== $this->namespace) {
         // if no alias exists prepend current namespace
         return FullyQualified::concat($this->namespace, $name, $name->getAttributes());
     }
     return new FullyQualified($name->parts, $name->getAttributes());
 }