| 1 |
<?php namespace WPDeveloper\BetterDocs\Dependencies\SuperClosure\Analyzer; |
| 2 |
|
| 3 |
use WPDeveloper\BetterDocs\Dependencies\SuperClosure\Exception\ClosureAnalysisException; |
| 4 |
|
| 5 |
abstract class ClosureAnalyzer |
| 6 |
{ |
| 7 |
/** |
| 8 |
* Analyzer a given closure. |
| 9 |
* |
| 10 |
* @param \Closure $closure |
| 11 |
* |
| 12 |
* @throws ClosureAnalysisException |
| 13 |
* |
| 14 |
* @return array |
| 15 |
*/ |
| 16 |
public function analyze(\Closure $closure) |
| 17 |
{ |
| 18 |
$data = [ |
| 19 |
'reflection' => new \ReflectionFunction($closure), |
| 20 |
'code' => null, |
| 21 |
'hasThis' => false, |
| 22 |
'context' => [], |
| 23 |
'hasRefs' => false, |
| 24 |
'binding' => null, |
| 25 |
'scope' => null, |
| 26 |
'isStatic' => $this->isClosureStatic($closure), |
| 27 |
]; |
| 28 |
|
| 29 |
$this->determineCode($data); |
| 30 |
$this->determineContext($data); |
| 31 |
$this->determineBinding($data); |
| 32 |
|
| 33 |
return $data; |
| 34 |
} |
| 35 |
|
| 36 |
abstract protected function determineCode(array &$data); |
| 37 |
|
| 38 |
/** |
| 39 |
* Returns the variables that are in the "use" clause of the closure. |
| 40 |
* |
| 41 |
* These variables are referred to as the "used variables", "static |
| 42 |
* variables", "closed upon variables", or "context" of the closure. |
| 43 |
* |
| 44 |
* @param array $data |
| 45 |
*/ |
| 46 |
abstract protected function determineContext(array &$data); |
| 47 |
|
| 48 |
private function determineBinding(array &$data) |
| 49 |
{ |
| 50 |
$data['binding'] = $data['reflection']->getClosureThis(); |
| 51 |
if ($scope = $data['reflection']->getClosureScopeClass()) { |
| 52 |
$data['scope'] = $scope->getName(); |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
private function isClosureStatic(\Closure $closure) |
| 57 |
{ |
| 58 |
$closure = @$closure->bindTo(new \stdClass); |
| 59 |
|
| 60 |
if ($closure === null) { |
| 61 |
return true; |
| 62 |
} |
| 63 |
|
| 64 |
$rebound = new \ReflectionFunction($closure); |
| 65 |
|
| 66 |
return $rebound->getClosureThis() === null; |
| 67 |
} |
| 68 |
} |
| 69 |
|