NodeFactory.php 2.4 KB

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