NodeFactory.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * This class is responsible for creating Node objects
  5. *
  6. * @package PhpMyAdmin-navigation
  7. */
  8. declare(strict_types=1);
  9. namespace PhpMyAdmin\Navigation;
  10. use PhpMyAdmin\Navigation\Nodes\Node;
  11. /**
  12. * Node factory - instantiates Node objects or objects derived from the Node class
  13. *
  14. * @package PhpMyAdmin-Navigation
  15. */
  16. class NodeFactory
  17. {
  18. protected static $namespace = 'PhpMyAdmin\\Navigation\\Nodes\\%s';
  19. /**
  20. * Sanitizes the name of a Node class
  21. *
  22. * @param string $class The class name to be sanitized
  23. *
  24. * @return string
  25. */
  26. private static function sanitizeClass($class)
  27. {
  28. if (! preg_match('@^Node\w*$@', $class)) {
  29. $class = 'Node';
  30. trigger_error(
  31. sprintf(
  32. /* l10n: The word "Node" must not be translated here */
  33. __('Invalid class name "%1$s", using default of "Node"'),
  34. $class
  35. ),
  36. E_USER_ERROR
  37. );
  38. }
  39. return self::checkClass($class);
  40. }
  41. /**
  42. * Checks if a class exists and try to load it.
  43. * Will return the default class name back if the
  44. * file for some subclass is not available
  45. *
  46. * @param string $class The class name to check
  47. *
  48. * @return string
  49. */
  50. private static function checkClass($class)
  51. {
  52. $class = sprintf(self::$namespace, $class);
  53. if (! class_exists($class)) {
  54. $class = sprintf(self::$namespace, 'Node');
  55. trigger_error(
  56. sprintf(
  57. __('Could not load class "%1$s"'),
  58. $class
  59. ),
  60. E_USER_ERROR
  61. );
  62. }
  63. return $class;
  64. }
  65. /**
  66. * Instantiates a Node object
  67. *
  68. * @param string $class The name of the class to instantiate
  69. * @param string $name An identifier for the new node
  70. * @param int $type Type of node, may be one of CONTAINER or OBJECT
  71. * @param bool $isGroup Whether this object has been created
  72. * while grouping nodes
  73. *
  74. * @return mixed
  75. */
  76. public static function getInstance(
  77. $class = 'Node',
  78. $name = 'default',
  79. $type = Node::OBJECT,
  80. $isGroup = false
  81. ) {
  82. $class = self::sanitizeClass($class);
  83. return new $class($name, $type, $isGroup);
  84. }
  85. }