base.php 1.7 KB

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