File: PhpPrinterIndentationDetectorVisitor.php

package info (click to toggle)
php-phpstan-phpdoc-parser 2.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,476 kB
  • sloc: php: 21,156; makefile: 50; xml: 42; sh: 17
file content (80 lines) | stat: -rw-r--r-- 1,613 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php declare(strict_types = 1);

namespace PHPStan\PhpDocParser\Printer;

use PhpParser\Internal\TokenStream;
use PhpParser\Node;
use PhpParser\NodeVisitor;
use PhpParser\NodeVisitorAbstract;
use function count;
use function preg_match;
use function preg_match_all;
use function property_exists;
use function strlen;
use const PREG_SET_ORDER;

class PhpPrinterIndentationDetectorVisitor extends NodeVisitorAbstract
{

	public string $indentCharacter = ' ';

	public int $indentSize = 4;

	private TokenStream $origTokens;

	public function __construct(TokenStream $origTokens)
	{
		$this->origTokens = $origTokens;
	}

	public function enterNode(Node $node)
	{
		if ($node instanceof Node\Stmt\Namespace_ || $node instanceof Node\Stmt\Declare_) {
			return null;
		}
		if (!property_exists($node, 'stmts')) {
			return null;
		}

		if (count($node->stmts) === 0) {
			return null;
		}

		$firstStmt = $node->stmts[0];
		$text = $this->origTokens->getTokenCode($node->getStartTokenPos(), $firstStmt->getStartTokenPos(), 0);

		$c = preg_match_all('~\n([\\x09\\x20]*)~', $text, $matches, PREG_SET_ORDER);
		if ($c === 0 || $c === false) {
			return null;
		}

		$char = '';
		$size = 0;
		foreach ($matches as $match) {
			$l = strlen($match[1]);
			if ($l === 0) {
				continue;
			}

			$char = $match[1];
			$size = $l;
			break;
		}

		if ($size > 0) {
			$d = preg_match('~^(\\x20+)$~', $char);
			if ($d !== false && $d > 0) {
				$size = strlen($char);
				$char = ' ';
			}

			$this->indentCharacter = $char;
			$this->indentSize = $size;

			return NodeVisitor::STOP_TRAVERSAL;
		}

		return null;
	}

}