Bridge.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. require_once(__DIR__ . '/BridgeInterface.php');
  3. class Bridge {
  4. static protected $dirBridge;
  5. public function __construct(){
  6. throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
  7. }
  8. /**
  9. * Create a new bridge object
  10. * @param string $nameBridge Defined bridge name you want use
  11. * @return Bridge object dedicated
  12. */
  13. static public function create($nameBridge){
  14. if(!preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameBridge)) {
  15. $message = <<<EOD
  16. 'nameBridge' must start with one uppercase character followed or not by
  17. alphanumeric or dash characters!
  18. EOD;
  19. throw new \InvalidArgumentException($message);
  20. }
  21. $nameBridge = $nameBridge . 'Bridge';
  22. $pathBridge = self::getDir() . $nameBridge . '.php';
  23. if(!file_exists($pathBridge)) {
  24. throw new \Exception('The bridge you looking for does not exist. It should be at path '
  25. . $pathBridge);
  26. }
  27. require_once $pathBridge;
  28. if((new ReflectionClass($nameBridge))->isInstantiable()) {
  29. return new $nameBridge();
  30. }
  31. return false;
  32. }
  33. static public function setDir($dirBridge){
  34. if(!is_string($dirBridge)) {
  35. throw new \InvalidArgumentException('Dir bridge must be a string.');
  36. }
  37. if(!file_exists($dirBridge)) {
  38. throw new \Exception('Dir bridge does not exist.');
  39. }
  40. self::$dirBridge = $dirBridge;
  41. }
  42. static public function getDir(){
  43. if(is_null(self::$dirBridge)) {
  44. throw new \LogicException(__CLASS__ . ' class need to know bridge path !');
  45. }
  46. return self::$dirBridge;
  47. }
  48. /**
  49. * Lists the available bridges.
  50. * @return array List of the bridges
  51. */
  52. static public function listBridges(){
  53. $listBridge = array();
  54. $dirFiles = scandir(self::getDir());
  55. if($dirFiles !== false) {
  56. foreach($dirFiles as $fileName) {
  57. if(preg_match('@^([^.]+)Bridge\.php$@U', $fileName, $out)) {
  58. $listBridge[] = $out[1];
  59. }
  60. }
  61. }
  62. return $listBridge;
  63. }
  64. static public function isWhitelisted($whitelist, $name){
  65. return in_array($name, $whitelist)
  66. || in_array($name . '.php', $whitelist)
  67. || in_array($name . 'bridge', $whitelist) // DEPRECATED
  68. || in_array($name . 'bridge.php', $whitelist) // DEPRECATED
  69. || (count($whitelist) === 1 && trim($whitelist[0]) === '*');
  70. }
  71. }