Format.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. require_once(__DIR__ . '/FormatInterface.php');
  3. class Format {
  4. static protected $dirFormat;
  5. public function __construct(){
  6. throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
  7. }
  8. static public function create($nameFormat){
  9. if(!preg_match('@^[A-Z][a-zA-Z]*$@', $nameFormat)) {
  10. throw new \InvalidArgumentException('Name format must be at least
  11. one uppercase follow or not by alphabetic characters.');
  12. }
  13. $nameFormat = $nameFormat . 'Format';
  14. $pathFormat = self::getDir() . $nameFormat . '.php';
  15. if(!file_exists($pathFormat)) {
  16. throw new \Exception('The format you looking for does not exist.');
  17. }
  18. require_once $pathFormat;
  19. return new $nameFormat();
  20. }
  21. static public function setDir($dirFormat){
  22. if(!is_string($dirFormat)) {
  23. throw new \InvalidArgumentException('Dir format must be a string.');
  24. }
  25. if(!file_exists($dirFormat)) {
  26. throw new \Exception('Dir format does not exist.');
  27. }
  28. self::$dirFormat = $dirFormat;
  29. }
  30. static public function getDir(){
  31. $dirFormat = self::$dirFormat;
  32. if(is_null($dirFormat)) {
  33. throw new \LogicException(__CLASS__ . ' class need to know format path !');
  34. }
  35. return $dirFormat;
  36. }
  37. /**
  38. * Read format dir and catch informations about each format depending annotation
  39. * @return array Informations about each format
  40. */
  41. static public function searchInformation(){
  42. $pathDirFormat = self::getDir();
  43. $listFormat = array();
  44. $searchCommonPattern = array('name');
  45. $dirFiles = scandir($pathDirFormat);
  46. if($dirFiles !== false) {
  47. foreach($dirFiles as $fileName) {
  48. if(preg_match('@^([^.]+)Format\.php$@U', $fileName, $out)) { // Is PHP file ?
  49. $listFormat[] = $out[1];
  50. }
  51. }
  52. }
  53. return $listFormat;
  54. }
  55. }