MapsBehavior.php 2.34 KB
<?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;
        }
    }