1<?php
2/**
3 * An abstract visitor class that includes a mapping between functions and classes,
4 * simulating overloading.
5 *
6 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
7 * @copyright Copyright 2010-2014 PhpCss Team
8 */
9
10namespace PhpCss\Ast\Visitor {
11
12  use PhpCss\Ast;
13
14  /**
15   * An abstract visitor class that includes a mapping between functions and classes,
16   * simulating overloading.
17   */
18  abstract class Overload implements Ast\Visitor {
19
20    /**
21     * Map the class name of the PhpCss\Ast\Node instance to a method name, validate if it exists and return
22     * it as callback.
23     *
24     * @param Ast\Node $object
25     * @param string $prefix
26     * @return callable|null
27     */
28    protected function getMethodByClass(Ast\Node $object, string $prefix = 'visit'): ?callable {
29      $method = $prefix.substr(str_replace('\\', '', get_class($object)), 9);
30      if (method_exists($this, $method)) {
31        return [$this, $method];
32      }
33      return NULL;
34    }
35
36    /**
37     * Entering an node in the ast, called before visiting children
38     *
39     * @param Ast\Node $astNode
40     * @return boolean
41     */
42    public function visitEnter(Ast\Node $astNode): bool {
43      if ($method = $this->getMethodByClass($astNode, 'visitEnter')) {
44        return $method($astNode);
45      }
46      return TRUE;
47    }
48
49    /**
50     * Visiting the $node element
51     *
52     * @param Ast\Node $astNode
53     */
54    public function visit(Ast\Node $astNode): void {
55      if ($method = $this->getMethodByClass($astNode)) {
56        $method($astNode);
57      }
58    }
59
60    /**
61     * Entering an element in the ast, called after visiting children
62     *
63     * @param Ast\Node $astNode
64     * @return void
65     */
66    public function visitLeave(Ast\Node $astNode): void {
67      if ($method = $this->getMethodByClass($astNode, 'visitLeave')) {
68        $method($astNode);
69      }
70    }
71  }
72}
73