TimeSearchBehavior.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /**
  3. * Author: lf
  4. * Blog: https://blog.feehi.com
  5. * Email: job@feehi.com
  6. * Created at: 2018-01-22 17:23
  7. */
  8. namespace backend\behaviors;
  9. use backend\components\search\SearchEvent;
  10. class TimeSearchBehavior extends \yii\base\Behavior
  11. {
  12. public $created_at;
  13. public $updated_at;
  14. public $createdAtAttribute = 'created_at';
  15. public $updatedAtAttribute = 'updated_at';
  16. public $timeAttributes = [];
  17. public $delimiter = "~";
  18. public $format = "int";
  19. public function init()
  20. {
  21. parent::init();
  22. empty($this->timeAttributes) && $this->timeAttributes = [$this->createdAtAttribute => $this->createdAtAttribute, $this->updatedAtAttribute => $this->updatedAtAttribute] ;
  23. }
  24. public function events()
  25. {
  26. return [
  27. SearchEvent::BEFORE_SEARCH => 'beforeSearch'
  28. ];
  29. }
  30. public function beforeSearch($event)
  31. {
  32. /** @var $event \backend\components\search\SearchEvent */
  33. foreach ($this->timeAttributes as $filed => $attribute) {
  34. if($attribute !== null) $timeAt = $event->sender->{$attribute};
  35. if( !empty($timeAt) ){
  36. $time = explode($this->delimiter, $timeAt);
  37. if( $this->format === 'int' ){
  38. $startAt = strtotime($time[0]);
  39. $endAt = strtotime($time[1]);
  40. }else{
  41. $startAt = $time[0];
  42. $endAt = $time[1];
  43. }
  44. $event->query->andFilterWhere([
  45. 'between',
  46. $filed,
  47. $startAt,
  48. $endAt
  49. ]);
  50. }
  51. }
  52. }
  53. }