base.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * Commonly used classes used in the BasicWeb package.
  4. *
  5. * @author Taddeus Kroes
  6. * @version 1.0
  7. * @date 13-07-2012
  8. */
  9. namespace BasicWeb;
  10. require_once 'logger.php';
  11. /**
  12. * Base class for instantiable classes in the BasicWeb package.
  13. *
  14. * The base class defines a static 'create' method that acts as a chainable
  15. * shortcut for the class constructor.
  16. *
  17. * @package BasicWeb
  18. */
  19. abstract class Base {
  20. /**
  21. * Create a new object of the called class.
  22. *
  23. * This function provides a chainable constructor, which is not possible
  24. * using plain PHP code.
  25. *
  26. * @returns mixed
  27. */
  28. final static function create(/* [ arg0 [ , ... ] ] */) {
  29. $args = func_get_args();
  30. $class = get_called_class();
  31. $rc = new \ReflectionClass($class);
  32. return $rc->newInstanceArgs($args);
  33. }
  34. }
  35. /**
  36. * Exception, thrown when a required file does not exist.
  37. *
  38. * @package BasicWeb
  39. */
  40. class FileNotFoundError extends \RuntimeException {
  41. /**
  42. * Create a new FileNotFoundError instance.
  43. *
  44. * Sets an error message of the form 'File "path/to/file.php" does not exist.'.
  45. *
  46. * @param string $path Path to the file that does not exist.
  47. */
  48. function __construct($path) {
  49. $this->message = sprintf('File "%s" does not exist.', $path);
  50. }
  51. }
  52. /**
  53. * Format a string of the form 'foo %(bar)' with given parameters like array('bar' => 'some value').
  54. *
  55. * @param string $format The string to format.
  56. * @param array $params An associative array with parameters that are used in the format.
  57. */
  58. function asprintf($format, array $params) {
  59. return preg_replace_callback(
  60. '/%\(([a-z-_ ]*)\)/i',
  61. function ($matches) use ($params) {
  62. return (string)$params[$matches[1]];
  63. },
  64. $format
  65. );
  66. }
  67. ?>