base.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 using parameters in an associative array.
  54. *
  55. * <code>
  56. * echo asprintf('foo %(bar)', array('bar' => 'baz')); // prints 'foo baz'
  57. * </code>
  58. *
  59. * @param string $format The string to format.
  60. * @param array $params An associative array with parameters that are used in $format.
  61. * @package BasicWeb
  62. */
  63. function asprintf($format, array $params) {
  64. return preg_replace_callback(
  65. '/%\(([a-z-_ ]*)\)/i',
  66. function ($matches) use ($params) {
  67. return (string)$params[$matches[1]];
  68. },
  69. $format
  70. );
  71. }
  72. ?>