ToolsTestTrait.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Tools\TestSuite;
  3. use ReflectionClass;
  4. /**
  5. * Utility methods for easier testing in CakePHP & PHPUnit
  6. */
  7. trait ToolsTestTrait {
  8. /**
  9. * OsFix method
  10. *
  11. * @param string $string
  12. * @return string
  13. */
  14. protected static function osFix($string) {
  15. return str_replace(["\r\n", "\r"], "\n", $string);
  16. }
  17. /**
  18. * Checks if debug flag is set.
  19. *
  20. * Flag is set via `--debug`.
  21. * Allows additional stuff like non-mocking when enabling debug.
  22. *
  23. * @return bool Success
  24. */
  25. protected static function isDebug() {
  26. return !empty($_SERVER['argv']) && in_array('--debug', $_SERVER['argv'], true);
  27. }
  28. /**
  29. * Checks if verbose flag is set.
  30. *
  31. * Flags are `-v` and `-vv`.
  32. * Allows additional stuff like non-mocking when enabling debug.
  33. *
  34. * @param bool $onlyVeryVerbose If only -vv should be counted.
  35. * @return bool Success
  36. */
  37. protected static function isVerbose($onlyVeryVerbose = false) {
  38. if (empty($_SERVER['argv'])) {
  39. return false;
  40. }
  41. if (!$onlyVeryVerbose && in_array('-v', $_SERVER['argv'], true)) {
  42. return true;
  43. }
  44. if (in_array('-vv', $_SERVER['argv'], true)) {
  45. return true;
  46. }
  47. return false;
  48. }
  49. /**
  50. * Outputs debug information during a test run.
  51. * This is a convenience output handler since debug() itself is not desired
  52. * for tests in general.
  53. *
  54. * Forces flushing the output if -v or -vv is set.
  55. *
  56. * @param mixed $data
  57. * @return void
  58. */
  59. protected static function debug($data) {
  60. if (!static::isVerbose()) {
  61. return;
  62. }
  63. $showFrom = static::isVerbose(true);
  64. debug($data, null, $showFrom);
  65. }
  66. /**
  67. * Call protected/private method of a class.
  68. *
  69. * So
  70. * $this->invokeMethod($user, 'cryptPassword', array('passwordToCrypt'));
  71. * is equal to
  72. * $user->cryptPassword('passwordToCrypt');
  73. * (assuming the method was directly publicly accessible
  74. *
  75. * @param object &$object Instantiated object that we will run method on.
  76. * @param string $methodName Method name to call.
  77. * @param array $parameters Array of parameters to pass into method.
  78. *
  79. * @return mixed Method return.
  80. */
  81. protected function invokeMethod(&$object, $methodName, array $parameters = []) {
  82. $reflection = new ReflectionClass(get_class($object));
  83. $method = $reflection->getMethod($methodName);
  84. $method->setAccessible(true);
  85. return $method->invokeArgs($object, $parameters);
  86. }
  87. }