Parser.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: NODELOG
  5. * Date: 16/6/22
  6. * Time: 下午4:53
  7. */
  8. namespace common\components\notify;
  9. use yii\base\BaseObject;
  10. use yii\helpers\StringHelper;
  11. class Parser extends BaseObject
  12. {
  13. /**
  14. * Regex to get values between curly bracket {$value}.
  15. */
  16. const RULE = '/\{(.+?)(?:\{(.+)\})?\}/';
  17. public function parse($item)
  18. {
  19. $body = $item['text'];
  20. $specialValues = $this->getValues($body);
  21. if (count($specialValues) > 0) {
  22. $specialValues = array_filter($specialValues, function ($value) {
  23. return StringHelper::startsWith($value, 'extra.') || StringHelper::startsWith($value, 'to.') || StringHelper::startsWith($value, 'from.');
  24. });
  25. foreach ($specialValues as $replacer) {
  26. $replace = array_get($item, $replacer);
  27. $body = $this->replaceBody($body, $replace, $replacer);
  28. }
  29. }
  30. return $body;
  31. }
  32. /**
  33. * Get the values between {}
  34. * and return an array of it.
  35. *
  36. * @param $body
  37. * @return mixed
  38. */
  39. protected function getValues($body)
  40. {
  41. $values = [];
  42. preg_match_all(self::RULE, $body, $values);
  43. return $values[1];
  44. }
  45. /**
  46. * Replace body of the category.
  47. *
  48. * @param $body
  49. * @param $replacer
  50. * @param $valueMatch
  51. * @return mixed
  52. */
  53. protected function replaceBody($body, $valueMatch, $replacer)
  54. {
  55. $body = str_replace('{'.$replacer.'}', $valueMatch, $body);
  56. return $body;
  57. }
  58. }