Browse Source

added comments and coder fixes

master
Paul Pound 9 years ago
parent
commit
16bf5e5f44
  1. 1
      README.md
  2. 5
      composer.json
  3. 22
      islandora_herbarium_object.module
  4. 26
      src/DataParser/DataParser.php
  5. 50
      src/DataParser/DataParserInterface.php
  6. 50
      src/DataParser/GbifParser.php
  7. 35
      src/DataParser/GeonamesParser.php
  8. 16
      src/DataParser/IpniParser.php
  9. 64
      src/DataParser/NrcanParser.php
  10. 26
      src/DataParser/XmlDataParser.php

1
README.md

@ -4,4 +4,3 @@
## License ## License

5
composer.json

@ -4,7 +4,10 @@
"type": "drupal-module", "type": "drupal-module",
"minimum-stability": "dev", "minimum-stability": "dev",
"prefer-stable": true, "prefer-stable": true,
"keywords": ["Drupal", "Islandora"], "keywords": [
"Drupal",
"Islandora"
],
"license": "GPL-2.0+", "license": "GPL-2.0+",
"homepage": "https://github.com/roblib/islandora_herbarium_object", "homepage": "https://github.com/roblib/islandora_herbarium_object",
"support": { "support": {

22
islandora_herbarium_object.module

@ -5,14 +5,13 @@
* Contains islandora_herbarium.module. * Contains islandora_herbarium.module.
*/ */
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatchInterface;
/** /**
* Implements hook_help(). * Implements hook_help().
*/ */
function islandora_herbarium_object_help($route_name, RouteMatchInterface $route_match) function islandora_herbarium_object_help($route_name, RouteMatchInterface $route_match) {
{
switch ($route_name) { switch ($route_name) {
// Main module help for the islandora_pdf module. // Main module help for the islandora_pdf module.
case 'help.page.islandora_herbarium': case 'help.page.islandora_herbarium':
@ -39,33 +38,30 @@ function islandora_herbarium_object_rdf_namespaces() {
/** /**
* Implements hook_entity_presave(). * Implements hook_entity_presave().
*/ */
function islandora_herbarium_object_entity_presave(Drupal\Core\Entity\EntityInterface $entity) function islandora_herbarium_object_entity_presave(EntityInterface $entity) {
{
if ($entity->bundle() == 'islandora_herbarium_object') { if ($entity->bundle() == 'islandora_herbarium_object') {
// Get the geo data. // Get the geo data.
try { try {
$geo = \Drupal::service('islandora_herbarium_object.geoparser'); $geo = \Drupal::service('islandora_herbarium_object.geoparser');
$geo->updateEntity($entity); $geo->updateEntity($entity);
} catch (Exception $e) { }
catch (Exception $e) {
drupal_set_message(t('There was an error retrieving Geo data. %msg.', drupal_set_message(t('There was an error retrieving Geo data. %msg.',
array('%msg'=> $e->getMessage())), 'error'); ['%msg' => $e->getMessage()]), 'error');
} }
// Get the taxonomy data. // Get the taxonomy data.
try { try {
$taxon = \Drupal::service('islandora_herbarium_object.taxonparser'); $taxon = \Drupal::service('islandora_herbarium_object.taxonparser');
$taxon->updateEntity($entity); $taxon->updateEntity($entity);
} catch(Exception $e) { }
catch (Exception $e) {
drupal_set_message(t('There was an error retrieving Taxon data. %msg.', drupal_set_message(t('There was an error retrieving Taxon data. %msg.',
array('%msg'=> $e->getMessage())), 'error'); ['%msg' => $e->getMessage()]), 'error');
} }
$title = $taxon->getValue('canonicalName') . ' - ' . $geo->getValue('name'); $title = $taxon->getValue('canonicalName') . ' - ' . $geo->getValue('name');
if ($title != ' - ') { if ($title != ' - ') {
$entity->setTitle($title); $entity->setTitle($title);
} }
} }
} }

26
src/DataParser/DataParser.php

@ -1,19 +1,19 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-04-30
* Time: 11:25 AM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
/**
* Abstract implementation of DataParserInterface base on arrays.
*/
abstract class DataParser implements DataParserInterface {
abstract class DataParser implements DataParserInterface
{
public $data; public $data;
public $data_arr = array();
public $dataArray = [];
/**
* {@inheritdoc}
*/
public function getRemoteData($uri, $returnAsVariable = FALSE) { public function getRemoteData($uri, $returnAsVariable = FALSE) {
$client = \Drupal::httpClient(); $client = \Drupal::httpClient();
$request = $client->get(trim($uri)); $request = $client->get(trim($uri));
@ -23,13 +23,17 @@ abstract class DataParser implements DataParserInterface
} }
if (!$returnAsVariable) { if (!$returnAsVariable) {
$this->data = $data; $this->data = $data;
} else { }
else {
return $data; return $data;
} }
} }
/**
* {@inheritdoc}
*/
public function getValue($key) { public function getValue($key) {
return isset($this->data_arr[$key]) ? $this->data_arr[$key] : ""; return isset($this->dataArray[$key]) ? $this->dataArray[$key] : "";
} }
} }

50
src/DataParser/DataParserInterface.php

@ -1,23 +1,53 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-04-30
* Time: 1:10 PM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
use Drupal\Core\Entity\EntityInterface;
interface DataParserInterface /**
{ * Common functions for herbarium taxon and location data.
*/
interface DataParserInterface {
public function getRemoteData($uri); /**
* Retrieve data from a remote URI.
*
* @param string $uri
* The request uri.
* @param bool $returnAsVariable
* If TRUE return the request data, otherwise set a class data variable(s).
*
* @return mixed
* Either NULL or the request data, determined by the value of
* $returnAsVariable.
*/
public function getRemoteData($uri, $returnAsVariable = FALSE);
/**
* Parse the Data stored in a local data structure.
*
* The local data structure is usually populated by the getRemoteData()
* function.
*/
public function parseData(); public function parseData();
/**
* Returns a value from a local data structure based on the corresponding key.
*
* @param string $key
* The key to use to lookup the data.
*
* @return string
* The value if the key exists otherwise an empty string.
*/
public function getValue($key); public function getValue($key);
public function updateEntity($entity); /**
* Update a Drupal Entity using the local data.
*
* @param Drupal\Core\Entity\EntityInterface $entity
* A Drupal Entity.
*/
public function updateEntity(EntityInterface $entity);
} }

50
src/DataParser/GbifParser.php

@ -1,31 +1,40 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-05-04
* Time: 1:19 PM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
use Drupal\Core\Entity\EntityInterface;
/**
* A data structure for GBif data.
*/
class GbifParser extends DataParser {
class GbifParser extends DataParser
{
public $gbifUrlPrefix = 'http://api.gbif.org/v1/species?name='; public $gbifUrlPrefix = 'http://api.gbif.org/v1/species?name=';
/**
* {@inheritdoc}
*/
public function parseData() { public function parseData() {
$arr = json_decode($this->data, TRUE); $arr = json_decode($this->data, TRUE);
if (empty($arr['results'])) { if (empty($arr['results'])) {
throw new \Exception('Error parsing json data.'); throw new \Exception('Error parsing json data.');
} }
$this->data_arr = reset($arr['results']); $this->dataArray = reset($arr['results']);
} }
public function updateEntity($entity) { /**
* {@inheritdoc}
*/
public function updateEntity(EntityInterface $entity) {
try { try {
$taxoniri = $entity->get("field_dwciri_scientificname")->getValue(); $taxoniri = $entity->get("field_dwciri_scientificname")->getValue();
$url = ''; $url = '';
if(empty($url = $taxoniri[0]['value']) && !empty($entity->get('field_dwc_scientificname')->getValue())) { if (empty($url = $taxoniri[0]['value']) && !empty($entity->get('field_dwc_scientificname')
$value = array($this->getGbifUrl($entity->get('field_dwc_scientificname')->getValue()[0]['value'])); ->getValue())) {
$value = [
$this->getGbifUrl($entity->get('field_dwc_scientificname')
->getValue()[0]['value']),
];
$taxoniri[] = ['value' => $value[0]]; $taxoniri[] = ['value' => $value[0]];
$url = $taxoniri[0]['value']; $url = $taxoniri[0]['value'];
if (empty($url)) { if (empty($url)) {
@ -35,10 +44,14 @@ class GbifParser extends DataParser
} }
$this->getRemoteData($url); $this->getRemoteData($url);
$this->parseData(); $this->parseData();
} catch (Exception $e) { }
catch (Exception $e) {
watchdog_exception('islandora_herbarium_object', $e, 'Error getting dwciri'); watchdog_exception('islandora_herbarium_object', $e, 'Error getting dwciri');
drupal_set_message(t('There was an error retrieving Taxon data. %msg. Verify the url is correct %url', drupal_set_message(t('There was an error retrieving Taxon data. %msg. Verify the url is correct %url',
array('%msg'=> $e->getMessage(), '%url' => $taxoniri[0]['value'])),'error'); [
'%msg' => $e->getMessage(),
'%url' => $taxoniri[0]['value'],
]), 'error');
return; return;
} }
$entity->set('field_dwc_scientificname', $this->getValue('canonicalName')); $entity->set('field_dwc_scientificname', $this->getValue('canonicalName'));
@ -53,6 +66,15 @@ class GbifParser extends DataParser
$entity->set('field_dwc_vernacularname', $this->getValue('vernacularName')); $entity->set('field_dwc_vernacularname', $this->getValue('vernacularName'));
} }
/**
* Return a string representation of a URL.
*
* @param string $scientificName
* The scientificName of a herbarium Specimen.
*
* @return string
* A string based on the gbifUrlPrefix and the scientificName.
*/
public function getGbifUrl($scientificName) { public function getGbifUrl($scientificName) {
return $this->gbifUrlPrefix . $scientificName; return $this->gbifUrlPrefix . $scientificName;
} }

35
src/DataParser/GeonamesParser.php

@ -1,19 +1,16 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-04-30
* Time: 11:35 AM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
/**
* Provides storage and functions for GeoName data.
*/
class GeonamesParser extends XmlDataParser {
class GeonamesParser extends XmlDataParser /**
{ * {@inheritdoc}
*/
public function parseData() public function parseData() {
{
$xml_doc = new \DOMDocument(); $xml_doc = new \DOMDocument();
if (empty($xml_doc->loadXML($this->data))) { if (empty($xml_doc->loadXML($this->data))) {
throw new \Exception('Failed loading data as xml'); throw new \Exception('Failed loading data as xml');
@ -39,6 +36,9 @@ class GeonamesParser extends XmlDataParser
$this->getXmlNodeValue($xml_doc, 'south'); $this->getXmlNodeValue($xml_doc, 'south');
} }
/**
* {@inheritdoc}
*/
public function updateEntity($entity) { public function updateEntity($entity) {
try { try {
$dwciri = $entity->get("field_dwciri_municipality")->getValue(); $dwciri = $entity->get("field_dwciri_municipality")->getValue();
@ -47,10 +47,11 @@ class GeonamesParser extends XmlDataParser
} }
$this->getRemoteData($dwciri[0]['value']); $this->getRemoteData($dwciri[0]['value']);
$this->parseData(); $this->parseData();
} catch (Exception $e) { }
catch (Exception $e) {
watchdog_exception('islandora_herbarium_object', $e, 'Error getting dwciri'); watchdog_exception('islandora_herbarium_object', $e, 'Error getting dwciri');
drupal_set_message(t('There was an error retrieving Municipality data. %msg. Verify the url is correct %url', drupal_set_message(t('There was an error retrieving Municipality data. %msg. Verify the url is correct %url',
array('%msg'=> $e->getMessage(), '%url' => $dwciri[0]['value'])), 'error'); ['%msg' => $e->getMessage(), '%url' => $dwciri[0]['value']]), 'error');
return; return;
} }
$entity->set('field_dwc_municipality', $this->getValue('name')); $entity->set('field_dwc_municipality', $this->getValue('name'));
@ -60,11 +61,13 @@ class GeonamesParser extends XmlDataParser
$entity->set('field_dwc_decimallatitude', $this->getValue('lat')); $entity->set('field_dwc_decimallatitude', $this->getValue('lat'));
$entity->set('field_dwc_decimallongitude', $this->getValue('lng')); $entity->set('field_dwc_decimallongitude', $this->getValue('lng'));
$entity->set('field_dwc_stateprovince', $this->getValue('adminName1')); $entity->set('field_dwc_stateprovince', $this->getValue('adminName1'));
$point = array( $point = [
'lon' => $this->getValue('lng'), 'lon' => $this->getValue('lng'),
'lat' => $this->getValue('lat'), 'lat' => $this->getValue('lat'),
); ];
$geo_field_value = \Drupal::service('geofield.wkt_generator')->WktBuildPoint($point); $geo_field_value = \Drupal::service('geofield.wkt_generator')
->WktBuildPoint($point);
$entity->set('field_herb_geo_field', $geo_field_value); $entity->set('field_herb_geo_field', $geo_field_value);
} }
} }

16
src/DataParser/IpniParser.php

@ -1,16 +1,15 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-04-30
* Time: 11:23 AM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
/**
* Provides storage and functions for IPNI data.
*/
abstract class IpniParser extends XmlDataParser {
class IpniParser extends XmlDataParser /**
{ * {@inheritdoc}
*/
public function parseData() { public function parseData() {
$xml_doc = new \DOMDocument(); $xml_doc = new \DOMDocument();
$xml_doc->loadXML($this->data); $xml_doc->loadXML($this->data);
@ -18,4 +17,5 @@ class IpniParser extends XmlDataParser
$this->getXmlNodeValue($xml_doc, 'genusPart'); $this->getXmlNodeValue($xml_doc, 'genusPart');
$this->getXmlNodeValue($xml_doc, 'specificEpithet'); $this->getXmlNodeValue($xml_doc, 'specificEpithet');
} }
} }

64
src/DataParser/NrcanParser.php

@ -1,35 +1,42 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-05-07
* Time: 10:44 AM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
use Drupal\Core\Entity\EntityInterface;
/**
* Provides storage and functions for NRCAN data.
*/
class NrcanParser extends DataParser {
class NrcanParser extends DataParser
{
public $nrcanUrlSearchPrefix = 'http://geogratis.gc.ca/services/geoname/en/geonames?q='; public $nrcanUrlSearchPrefix = 'http://geogratis.gc.ca/services/geoname/en/geonames?q=';
public $nrcanUrlPrefix = 'http://geogratis.gc.ca/services/geoname/en/geonames/'; public $nrcanUrlPrefix = 'http://geogratis.gc.ca/services/geoname/en/geonames/';
public function parseData() /**
{ * {@inheritdoc}
*/
public function parseData() {
$arr = json_decode($this->data, TRUE); $arr = json_decode($this->data, TRUE);
if (empty($arr)) { if (empty($arr)) {
throw new \Exception('Error parsing geo json data.'); throw new \Exception('Error parsing geo json data.');
} }
$this->data_arr = $arr; $this->dataArray = $arr;
} }
public function updateEntity($entity) { /**
* {@inheritdoc}
*/
public function updateEntity(EntityInterface $entity) {
try { try {
$url = ''; $url = '';
$dwciri = $entity->get("field_dwciri_municipality")->getValue(); $dwciri = $entity->get("field_dwciri_municipality")->getValue();
if(empty($url = $dwciri[0]['value']) && !empty($entity->get("field_dwc_municipality")->getValue())) { if (empty($url = $dwciri[0]['value']) && !empty($entity->get("field_dwc_municipality")
//throw new Exception("No URI provided, cannot look up location data."); ->getValue())) {
$value = array($this->getNrcanUrl($entity->get('field_dwc_municipality')->getValue()[0]['value'])); $value = [
$this->getNrcanUrl($entity->get('field_dwc_municipality')
->getValue()[0]['value']),
];
$dwciri[] = ['value' => $value[0]]; $dwciri[] = ['value' => $value[0]];
$url = $dwciri[0]['value']; $url = $dwciri[0]['value'];
if (empty($url)) { if (empty($url)) {
@ -40,14 +47,15 @@ class NrcanParser extends DataParser
$this->getRemoteData($url); $this->getRemoteData($url);
$this->parseData(); $this->parseData();
} catch (Exception $e) { }
catch (Exception $e) {
watchdog_exception('islandora_herbarium_object', $e, 'Error getting dwciri'); watchdog_exception('islandora_herbarium_object', $e, 'Error getting dwciri');
drupal_set_message(t('There was an error retrieving Municipality data. %msg. Verify the url is correct %url', drupal_set_message(t('There was an error retrieving Municipality data. %msg. Verify the url is correct %url',
array('%msg'=> $e->getMessage(), '%url' => $dwciri[0]['value'])), 'error'); ['%msg' => $e->getMessage(), '%url' => $dwciri[0]['value']]), 'error');
return; return;
} }
$entity->set('field_dwc_municipality', $this->getValue('name')); $entity->set('field_dwc_municipality', $this->getValue('name'));
// This parser assumes we are in canada // This parser assumes we are in canada.
$entity->set('field_dwc_countrycode', 'CA'); $entity->set('field_dwc_countrycode', 'CA');
$entity->set('field_dwc_country', 'Canada'); $entity->set('field_dwc_country', 'Canada');
$entity->set('field_dwc_continent', 'North America'); $entity->set('field_dwc_continent', 'North America');
@ -61,17 +69,28 @@ class NrcanParser extends DataParser
} }
catch (Exception $e) { catch (Exception $e) {
drupal_set_message(t('There was an error retrieving Province data. %msg.', drupal_set_message(t('There was an error retrieving Province data. %msg.',
array('%msg'=> $e->getMessage())), 'error'); ['%msg' => $e->getMessage()]), 'error');
} }
$entity->set('field_dwc_stateprovince', $province); $entity->set('field_dwc_stateprovince', $province);
$point = array( $point = [
'lon' => $this->getValue('longitude'), 'lon' => $this->getValue('longitude'),
'lat' => $this->getValue('latitude'), 'lat' => $this->getValue('latitude'),
); ];
$geo_field_value = \Drupal::service('geofield.wkt_generator')->WktBuildPoint($point); $geo_field_value = \Drupal::service('geofield.wkt_generator')
->WktBuildPoint($point);
$entity->set('field_herb_geo_field', $geo_field_value); $entity->set('field_herb_geo_field', $geo_field_value);
} }
/**
* Returns a URL string.
*
* @param string $municipality
* The municipality that we want to lookup.
*
* @return string
* URL String based on the nrcanUrlPrefix class variable plus a key that
* represents the municipality.
*/
public function getNrcanUrl($municipality) { public function getNrcanUrl($municipality) {
$url = $this->nrcanUrlSearchPrefix . $municipality . "&province=11"; $url = $this->nrcanUrlSearchPrefix . $municipality . "&province=11";
$data = $this->getRemoteData($url, TRUE); $data = $this->getRemoteData($url, TRUE);
@ -85,4 +104,5 @@ class NrcanParser extends DataParser
} }
return $this->nrcanUrlPrefix . $key; return $this->nrcanUrlPrefix . $key;
} }
} }

26
src/DataParser/XmlDataParser.php

@ -1,18 +1,22 @@
<?php <?php
/**
* Created by IntelliJ IDEA.
* User: ppound
* Date: 2018-05-04
* Time: 1:16 PM
*/
namespace Drupal\islandora_herbarium_object\DataParser; namespace Drupal\islandora_herbarium_object\DataParser;
/**
* Provides functions for simple XML data.
*/
abstract class XmlDataParser extends DataParser {
abstract class XmlDataParser extends DataParser /**
{ * Retrieves the value of the first xml node matching element_name.
public function getXmlNodeValue($xml_doc, $element_name) *
{ * @param \DOMDocument $xml_doc
$this->data_arr[$element_name] = $xml_doc->getElementsByTagName($element_name)[0]->nodeValue; * An xml document.
* @param string $element_name
* The xml node to lookup.
*/
public function getXmlNodeValue(\DOMDocument $xml_doc, $element_name) {
$this->dataArray[$element_name] = $xml_doc->getElementsByTagName($element_name)[0]->nodeValue;
} }
} }

Loading…
Cancel
Save