You are here

class GeocoderApiEnpoints in Geocoder 8.2

Same name and namespace in other branches
  1. 8.3 src/Controller/GeocoderApiEnpoints.php \Drupal\geocoder\Controller\GeocoderApiEnpoints

Class GeocoderApiEnpoints.

Hierarchy

Expanded class hierarchy of GeocoderApiEnpoints

File

src/Controller/GeocoderApiEnpoints.php, line 22

Namespace

Drupal\geocoder\Controller
View source
class GeocoderApiEnpoints extends ControllerBase {

  /**
   * The config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * Geocoder Service.
   *
   * @var \Drupal\geocoder\Geocoder
   */
  protected $geocoder;

  /**
   * The dumper plugin manager service.
   *
   * @var \Drupal\geocoder\DumperPluginManager
   */
  protected $dumperPluginManager;

  /**
   * The Geocoder formatter plugin manager service.
   *
   * @var \Drupal\geocoder\FormatterPluginManager
   */
  protected $geocoderFormatterPluginManager;

  /**
   * The Response.
   *
   * @var \Symfony\Component\HttpFoundation\Response
   */
  protected $response;

  /**
   * Get the Address Formatter.
   */
  protected function getAddressFormatter($address_format = NULL) {
    return $address_format ?: 'default_formatted_address';
  }

  /**
   * Set Geocoders Options.
   *
   * Merges Geocoders Options from Request Query and Module Configurations.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The Request object.
   *
   * @return array
   *   The merged Plugins Options array.
   */
  protected function setGeocodersOptions(Request $request) : array {

    // Retrieve geocoders options from the module configurations.
    $geocoders_configs = $this->config
      ->get('plugins_options') ?: [];

    // Get possible query string specific geocoders options.
    $geocoders_options = $request
      ->get('options') ?: [];

    // Merge geocoders options.
    $options = NestedArray::mergeDeep($geocoders_configs, $geocoders_options);
    return $options;
  }

  /**
   * Add a geometry property if not defined (as Google Maps Geocoding does).
   *
   * @param \Geocoder\Model\Address $address
   *   The Address array.
   *
   * @return array
   *   The Address Geometry Property.
   */
  protected function addGeometryProperty(Address $address) {

    /* @var array $address_array */
    $address_array = $address
      ->toArray();
    return [
      'location' => [
        'lat' => $address_array['latitude'],
        'lng' => $address_array['longitude'],
      ],
      'viewport' => [
        'northeast' => [
          'lat' => $address_array['bounds']['north'],
          'lng' => $address_array['bounds']['east'],
        ],
        'southwest' => [
          'lat' => $address_array['bounds']['south'],
          'lng' => $address_array['bounds']['west'],
        ],
      ],
    ];
  }

  /**
   * Get Address Collection Response.
   *
   * @param \Geocoder\Model\AddressCollection $geo_collection
   *   The Address Collection.
   * @param \Drupal\geocoder\DumperInterface|null $dumper
   *   The Dumper or null.
   * @param string|null $address_format
   *   The specific @GeocoderFormatter id to be used.
   */
  protected function getAddressCollectionResponse(AddressCollection $geo_collection, $dumper = NULL, $address_format = NULL) : void {
    $result = [];

    /** @var \Geocoder\Model\Address $geo_address **/
    foreach ($geo_collection
      ->all() as $k => $geo_address) {
      if (isset($dumper)) {
        $result[$k] = $dumper
          ->dump($geo_address);
      }
      else {
        $result[$k] = $geo_address
          ->toArray();

        // If a formatted_address property is not defined (as Google Maps
        // Geocoding does), then create it with our own formatter.
        if (!isset($result[$k]['formatted_address'])) {
          try {
            $result[$k]['formatted_address'] = $this->geocoderFormatterPluginManager
              ->createInstance($this
              ->getAddressFormatter($address_format))
              ->format($geo_address);
          } catch (\Exception $e) {
            watchdog_exception('geocoder', $e);
          }
        }

        // If a geometry property is not defined
        // (as Google Maps Geocoding does), then create it with our own dumper.
        if (!isset($result[$k]['geometry'])) {
          $result[$k]['geometry'] = $this
            ->addGeometryProperty($geo_address);
        }
      }
    }
    $this->response = new CacheableJsonResponse($result, 200);
    $this->response
      ->addCacheableDependency(CacheableMetadata::createFromObject($result));
  }

  /**
   * Get the output Dumper Format.
   *
   * @param string $format
   *   The Dumper Format.
   *
   * @return object|null
   *   The Dumper object or Null.
   */
  protected function getDumper($format) {
    $dumper = NULL;
    if (isset($format)) {
      try {
        $dumper = $this->dumperPluginManager
          ->createInstance($format);
      } catch (\Exception $e) {
        $dumper = NULL;
      }
    }
    return $dumper;
  }

  /**
   * Constructs a new GeofieldMapGeocoder object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\geocoder\Geocoder $geocoder
   *   The Geocoder service.
   * @param \Drupal\geocoder\DumperPluginManager $dumper_plugin_manager
   *   The dumper plugin manager service.
   * @param \Drupal\geocoder\FormatterPluginManager $geocoder_formatter_plugin_manager
   *   The geocoder formatter plugin manager service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, Geocoder $geocoder, DumperPluginManager $dumper_plugin_manager, FormatterPluginManager $geocoder_formatter_plugin_manager) {
    $this->config = $config_factory
      ->get('geocoder.settings');
    $this->geocoder = $geocoder;
    $this->dumperPluginManager = $dumper_plugin_manager;
    $this->geocoderFormatterPluginManager = $geocoder_formatter_plugin_manager;

    // Define a default empty Response as 204 No Content.
    $this->response = new Response('', 204);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('geocoder'), $container
      ->get('plugin.manager.geocoder.dumper'), $container
      ->get('plugin.manager.geocoder.formatter'));
  }

  /**
   * {@inheritdoc}
   */
  public function geocode(Request $request) {
    $address = $request
      ->get('address');
    $geocoders_ids = $request
      ->get('geocoder');
    $geocoders = explode(',', str_replace(' ', '', $geocoders_ids));
    $format = $request
      ->get('format');
    $address_format = $request
      ->get('address_format');
    if (isset($address)) {
      $options = $this
        ->setGeocodersOptions($request);
      $dumper = $this
        ->getDumper($format);
      $geo_collection = $this->geocoder
        ->geocode($address, $geocoders, $options);
      if ($geo_collection && $geo_collection instanceof AddressCollection) {
        $this
          ->getAddressCollectionResponse($geo_collection, $dumper, $address_format);
      }
    }
    return $this->response;
  }

  /**
   * {@inheritdoc}
   */
  public function reverseGeocode(Request $request) {
    $latlng = $request
      ->get('latlng');
    $geocoders_ids = $request
      ->get('geocoder');
    $geocoders = explode(',', $geocoders_ids);
    $format = $request
      ->get('format');
    if (isset($latlng)) {
      $latlng = explode(',', $request
        ->get('latlng'));
      $options = $this
        ->setGeocodersOptions($request);
      $dumper = $this
        ->getDumper($format);
      $geo_collection = $this->geocoder
        ->reverse($latlng[0], $latlng[1], $geocoders, $options);
      if ($geo_collection && $geo_collection instanceof AddressCollection) {
        $this
          ->getAddressCollectionResponse($geo_collection, $dumper);
      }
    }
    return $this->response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
GeocoderApiEnpoints::$config protected property The config factory service.
GeocoderApiEnpoints::$dumperPluginManager protected property The dumper plugin manager service.
GeocoderApiEnpoints::$geocoder protected property Geocoder Service.
GeocoderApiEnpoints::$geocoderFormatterPluginManager protected property The Geocoder formatter plugin manager service.
GeocoderApiEnpoints::$response protected property The Response.
GeocoderApiEnpoints::addGeometryProperty protected function Add a geometry property if not defined (as Google Maps Geocoding does).
GeocoderApiEnpoints::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
GeocoderApiEnpoints::geocode public function
GeocoderApiEnpoints::getAddressCollectionResponse protected function Get Address Collection Response.
GeocoderApiEnpoints::getAddressFormatter protected function Get the Address Formatter.
GeocoderApiEnpoints::getDumper protected function Get the output Dumper Format.
GeocoderApiEnpoints::reverseGeocode public function
GeocoderApiEnpoints::setGeocodersOptions protected function Set Geocoders Options.
GeocoderApiEnpoints::__construct public function Constructs a new GeofieldMapGeocoder object.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.