BikeObserver.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Mead
  5. * Date: 2019/9/19
  6. * Time: 10:09 AM
  7. */
  8. namespace App\Observers;
  9. use App\Handlers\BikeStatusInfoSyncHandler;
  10. use App\Models\Bike;
  11. use App\Models\LocationsLog;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. class BikeObserver
  16. {
  17. public function created(Bike $bike)
  18. {
  19. $bike_no = $bike->bike_no;
  20. $box_no = $bike->box_no;
  21. if ($bike_no && $box_no) {
  22. $redis = Redis::connection();
  23. $redis->hset(Bike::REDIS_BOX_NO_AND_BIKE_NO_TAG, $box_no, $bike_no);
  24. }
  25. }
  26. public function updated(Bike $bike)
  27. {
  28. $bike_no = $bike->bike_no;
  29. $box_no = $bike->box_no;
  30. $redis = Redis::connection();
  31. if ($bike->isDirty('box_no')) {
  32. DB::table('bikes')->where('id', $bike->id)->update([
  33. 'is_link' => Bike::LINK_OFFLINE
  34. ]);
  35. $old_box_no = $bike->getOriginal('box_no');
  36. $redis->hdel(Bike::REDIS_BOX_NO_AND_BIKE_NO_TAG, [$old_box_no]);
  37. }
  38. if ($bike_no && $box_no) {
  39. $redis->hset(Bike::REDIS_BOX_NO_AND_BIKE_NO_TAG, $box_no, $bike_no);
  40. if ($bike->isDirty('put_status')) {
  41. $BikeStatusInfoSyncHandler = (new BikeStatusInfoSyncHandler());
  42. if ((int)$bike->put_status === Bike::PUT_STATUS_NO) {
  43. $BikeStatusInfoSyncHandler->toBikeOffLineStatus($bike_no);
  44. } else {
  45. $location = LocationsLog::getNewestLocationByBikeNo($bike_no);
  46. if ($location['lat'] <= 0) {
  47. $location = json_decode($bike->last_location, true);
  48. }
  49. $BikeStatusInfoSyncHandler->toBikeOnLineStatus($bike_no, $location['lng'], $location['lat']);
  50. }
  51. }
  52. }
  53. }
  54. public function deleted(Bike $bike)
  55. {
  56. $box_no = $bike->box_no;
  57. $redis = Redis::connection();
  58. $redis->hdel(Bike::REDIS_BOX_NO_AND_BIKE_NO_TAG, [$box_no]);
  59. }
  60. }