Blame view

common/behaviors/MapsBehavior.php 2.42 KB
14a09168   Alex Savenko   init commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
  <?php

      namespace common\behaviors;

  

      use yii\base\Behavior;

      use yii\base\ErrorException;

      use yii\base\Event;

      use yii\db\ActiveRecord;

      use yii\helpers\Html;

  

      /**

       * Class MapsBehavior

       * @package common\behaviors

       */

      class MapsBehavior extends Behavior

      {

  

          public $location_attributes = [ ];

  

          public $required_attributes = [ ];

  

          /**

           * @inheritdoc

           */

          public function events()

          {

              return [

                  ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',

                  ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',

              ];

          }

  

          /**

           * After saving model get latitude (lat) and longitude (lng) from Google Map Api and insert

           * to the database

           *

           * @param Event $event

           *

           * @return bool

           * @throws ErrorException

           */

          public function beforeSave($event)

          {

              /**

               * @var ActiveRecord $owner

               */

              $owner = $this->owner;

              foreach($this->required_attributes as $required_attribute) {

                  if(empty( $owner->$required_attribute )) {

                      return true;

                  }

              }

              $location = '';

              $first = true;

              foreach($this->location_attributes as $location_attribute) {

                  if(!$first) {

                      $location .= '+';

                  }

                  $location .= $owner->$location_attribute;

                  $first = false;

              }

              $location = urlencode(Html::encode($location));

              $ch = curl_init();

              if(!$ch) {

                  throw new ErrorException('Curl error');

              }

              curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/geocode/json?address=" . $location);

              curl_setopt($ch, CURLOPT_HEADER, 0);

              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

              curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

              $result = json_decode(curl_exec($ch));

              curl_close($ch);

              if(!empty($result->results)) {

                  $owner->lat = $result->results[0]->geometry->location->lat;

                  $owner->lng = $result->results[0]->geometry->location->lng;

              }

              return true;

          }

      }