-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathCachingDocBlockFactory.php
More file actions
72 lines (63 loc) Β· 2.09 KB
/
CachingDocBlockFactory.php
File metadata and controls
72 lines (63 loc) Β· 2.09 KB
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
<?php
declare(strict_types=1);
namespace LanguageServer;
use Microsoft\PhpParser\Node;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlockFactory;
use phpDocumentor\Reflection\Types;
/**
* Caches DocBlocks by node start position and file URI.
*/
class CachingDocBlockFactory
{
/**
* Maps file + node start positions to DocBlocks.
*/
private $cache = [];
/**
* @var DocBlockFactory
*/
private $docBlockFactory;
public function __construct()
{
$this->docBlockFactory = DocBlockFactory::createInstance();
}
/**
* @return DocBlock|null
*/
public function getDocBlock(Node $node)
{
$cacheKey = $node->getStart() . ':' . $node->getUri();
if (array_key_exists($cacheKey, $this->cache)) {
return $this->cache[$cacheKey];
}
$text = $node->getDocCommentText();
return $this->cache[$cacheKey] = $text === null ? null : $this->createDocBlockFromNodeAndText($node, $text);
}
public function clearCache()
{
$this->cache = [];
}
/**
* @return DocBlock|null
*/
private function createDocBlockFromNodeAndText(Node $node, string $text)
{
list($namespaceImportTable,,) = $node->getImportTablesForCurrentScope();
$namespaceImportTable = array_map('strval', $namespaceImportTable);
$namespaceDefinition = $node->getNamespaceDefinition();
if ($namespaceDefinition !== null && $namespaceDefinition->name !== null) {
$namespaceName = (string)$namespaceDefinition->name->getNamespacedName();
} else {
$namespaceName = 'global';
}
$context = new Types\Context($namespaceName, $namespaceImportTable);
try {
// create() throws when it thinks the doc comment has invalid fields.
// For example, a @see tag that is followed by something that doesn't look like a valid fqsen will throw.
return $this->docBlockFactory->create($text, $context);
} catch (\InvalidArgumentException $e) {
return null;
}
}
}