AbstractFactory.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * The base abstract factory used by all PasswordLib factories
  4. *
  5. * PHP version 5.3
  6. *
  7. * @category PHPPasswordLib
  8. * @package Core
  9. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  10. * @copyright 2011 The Authors
  11. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  12. * @version Build @@version@@
  13. */
  14. namespace SecurityLib;
  15. /**
  16. * The base abstract factory used by all PasswordLib factories
  17. *
  18. * @category PHPPasswordLib
  19. * @package Core
  20. * @author Anthony Ferrara <ircmaxell@ircmaxell.com>
  21. */
  22. abstract class AbstractFactory {
  23. /**
  24. * Register a type with the factory by name
  25. *
  26. * This is an internal method to check if a provided class name implements
  27. * an interface, and if it does to append that class to an internal array
  28. * by name.
  29. *
  30. * @param string $type The name of the variable to store the class
  31. * @param string $implements The interface to validate against
  32. * @param string $name The name of this particular class
  33. * @param string $class The fully qualified class name
  34. * @param boolean $instantiate Should the class be stored instantiated
  35. *
  36. * @return void
  37. * @throws InvalidArgumentException If class does not implement interface
  38. */
  39. protected function registerType(
  40. $type,
  41. $implements,
  42. $name,
  43. $class,
  44. $instantiate = false
  45. ) {
  46. $name = strtolower($name);
  47. $refl = new \ReflectionClass($class);
  48. if (!$refl->implementsInterface($implements)) {
  49. $message = sprintf('Class must implement %s', $implements);
  50. throw new \InvalidArgumentException($message);
  51. }
  52. if ($instantiate) {
  53. $class = new $class;
  54. }
  55. $this->{$type}[$name] = $class;
  56. }
  57. /**
  58. * Load a set of classes from a directory into the factory
  59. *
  60. * @param string $directory The directory to search for classes in
  61. * @param string $namespace The namespace prefix for any found classes
  62. * @param string $callback The callback with which to register the class
  63. *
  64. * @return void
  65. */
  66. protected function loadFiles($directory, $namespace, $callback) {
  67. foreach (new \DirectoryIterator($directory) as $file) {
  68. $filename = $file->getBasename();
  69. if ($file->isFile() && substr($filename, -4) == '.php') {
  70. $name = substr($filename, 0, -4);
  71. $class = $namespace . $name;
  72. call_user_func($callback, $name, $class);
  73. }
  74. }
  75. }
  76. }