ElementImportOneService.php 9 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php

namespace Biopen\GeoDirectoryBundle\Services;

use Doctrine\ODM\MongoDB\DocumentManager;
use Biopen\GeoDirectoryBundle\Document\Element;
use Biopen\GeoDirectoryBundle\Document\ElementStatus;
use Biopen\GeoDirectoryBundle\Document\ModerationState;
use Biopen\GeoDirectoryBundle\Document\Coordinates;
10
use Biopen\GeoDirectoryBundle\Document\OpenHours;
11 12 13 14 15 16 17 18 19 20 21 22 23 24
use Biopen\GeoDirectoryBundle\Document\Option;
use Biopen\GeoDirectoryBundle\Document\OptionValue;
use Biopen\GeoDirectoryBundle\Document\UserInteractionContribution;
use Biopen\GeoDirectoryBundle\Document\PostalAddress;
use Biopen\GeoDirectoryBundle\Document\ElementImage;

class ElementImportOneService
{
	private $em;
	private $geocoder;
	private $interactionService;

	protected $optionIdsToAddToEachElement = [];

25
	protected $coreFields = ['id', 'name', 'categories', 'streetAddress', 'addressLocality', 'postalCode', 'addressCountry', 'latitude', 'longitude', 'images', 'owner', 'source', 'openHours'];
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
	protected $privateDataProps;

	/**
    * Constructor
    */
  public function __construct(DocumentManager $documentManager, $geocoder, $interactionService)
  {
		$this->em = $documentManager;
		$this->geocoder = $geocoder->using('google_maps');
		$this->interactionService = $interactionService;
		$this->currentRow = [];
  }

  public function initialize($import)
  {
    $this->optionIdsToAddToEachElement = [];
    foreach ($import->getOptionsToAddToEachElement() as $option) {
      $this->optionIdsToAddToEachElement[] = $option->getId();
    }

    // Getting the private field of the custom data
    $config = $this->em->getRepository('BiopenCoreBundle:Configuration')->findConfiguration();
    $this->privateDataProps = $config->getApi()->getPublicApiPrivateProperties();
  }

	public function createElementFromArray($row, $import)
	{
		$updateExisting = false; // if we create a new element or update an existing one
		$realUpdate = false; // if we are sure that the external has been edited with 'FieldToCheckElementHaveBeenUpdated'
Sebastian Castro's avatar
Sebastian Castro committed
55 56 57 58 59 60 61

		// adds missings fields instead of checking if each field is set before accessing
		$missingFields = array_diff($this->coreFields, array_keys($row));
    foreach ($missingFields as $missingField) {
      $row[$missingField] = "";
    }

62
		if (isset($row['id']))
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
		{
			if (in_array($row['id'], $import->getIdsToIgnore())) return;
			$qb = $this->em->createQueryBuilder('BiopenGeoDirectoryBundle:Element');
			$qb->field('source')->references($import);
			$qb->field('oldId')->equals("" . $row['id']);
			$element = $qb->getQuery()->getSingleResult();
		} else {
			$qb = $this->em->createQueryBuilder('BiopenGeoDirectoryBundle:Element');
			$qb->field('source')->references($import);
			$qb->field('name')->equals($row['name']);
			$qb->field('geo.latitude')->equals((float) number_format((float)$row['latitude'], 5));
			$qb->field('geo.longitude')->equals((float) number_format((float)$row['longitude'], 5));
			$element = $qb->getQuery()->getSingleResult();
		}

		if ($element) // if element with this Id already exists
		{
			$updatedAtField = $import->getFieldToCheckElementHaveBeenUpdated();
			// if updated date hasn't change, nothing to do
			if ($updatedAtField && array_key_exists($updatedAtField, $row)) {
				if ($row[$updatedAtField] && $row[$updatedAtField] == $element->getCustomProperty($updatedAtField)) {
					$element->setPreventJsonUpdate(true);
					if ($element->getStatus() == ElementStatus::DynamicImportTemp) $element->setStatus(ElementStatus::DynamicImport);
					$this->em->persist($element);
					return "nothing_to_do";
				} else {
					$realUpdate = true;
				}
			}
			$updateExisting = true;
			// resetting "geolocc" and "no options" modearation state so it will be calculated again
			if ($element->getModerationState() < 0) $element->setModerationState(ModerationState::NotNeeded);
		}
		else
		{
			$element = new Element();
		}
		$this->currentRow = $row;

		$element->setOldId($row['id']);
		$element->setName($row['name']);
104
		$address = new PostalAddress($row['streetAddress'], $row['addressLocality'], $row['postalCode'], $row["addressCountry"]);
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
		$element->setAddress($address);

		$defaultSourceName = $import ? $import->getSourceName() : 'Inconnu';
		$element->setSourceKey( (strlen($row['source']) > 0 && $row['source'] != 'Inconnu') ? $row['source'] : $defaultSourceName);
		$element->setSource($import);

		if (array_key_exists('owner', $row)) $element->setUserOwnerEmail($row['owner']);

		$lat = $row['latitude']; $lng = $row['longitude'];
		if (is_object($lat) || is_array($lat) || strlen($lat) == 0 || is_object($lng) || strlen($lng) == 0 || $lat == 'null' || $lat == null)
		{
			$lat = 0; $lng = 0;
			if ($import->getGeocodeIfNecessary())
			{
		   	$result = $this->geocoder->geocode($address->getFormatedAddress())->first();
		   	$lat = $result->getLatitude();
		   	$lng = $result->getLongitude();
			}
		}

		if ($lat == 0 || $lng == 0) $element->setModerationState(ModerationState::GeolocError);
		$element->setGeo(new Coordinates((float)$lat, (float)$lng));

		$this->createCategories($element, $row, $import);
		$this->createImages($element, $row);
130
		$this->createOpenHours($element, $row);
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
		$this->saveCustomFields($element, $row);

		if ($import->isDynamicImport()) { // keep the same status for the one who were deleted
			$status = (!$element->getStatus() || $element->getStatus() == ElementStatus::DynamicImportTemp) ? ElementStatus::DynamicImport : $element->getStatus();
			$element->setIsExternal(true);
		}
		else
			$status = ElementStatus::AddedByAdmin;

		// create import contribution if first time imported
		if (!$updateExisting)
		{
			$contribution = $this->interactionService->createContribution(null, 0, $status);
			$element->addContribution($contribution);
      // $this->mailService->sendAutomatedMail('add', $element, $message);
		}
		// create edit contribution if real update
		else if ($realUpdate) {
			$contribution = $this->interactionService->createContribution(null, 1, $status);
			$element->addContribution($contribution);
		}

		$element->setStatus($status);
		$element->updateTimestamp();

		$this->em->persist($element);

		return $updateExisting ? "updated" : "created";
	}

	private function saveCustomFields($element, $raw_data)
	{
		$customFields = array_diff(array_keys($raw_data), $this->coreFields);
		$customData = [];
    foreach ($customFields as $customField) {
			if ($customField && is_string($customField)) $customData[$customField] = $raw_data[$customField];
		}

    $element->setCustomData($customData, $this->privateDataProps);
	}

	private function createImages($element, $row)
	{
		$element->resetImages();
		$images_raw = $row['images'];
		if (is_string($images_raw) && strlen($images_raw) > 0) $images = explode(',', $row['images']);
		else if (is_array($images_raw)) $images = $images_raw;
		else
		{
			$keys = array_keys($row);
			$image_keys = array_filter($keys, function($key) { return $this->startsWith($key, 'image'); });
			$images = array_map(function($key) use ($row) { return $row[$key]; }, $image_keys);
		}

		if (count($images) == 0) return;

		foreach($images as $imageUrl)
		{
			if (is_string($imageUrl) && strlen($imageUrl) > 5)
			{
				$elementImage = new ElementImage();
				$elementImage->setExternalImageUrl($imageUrl);
				$element->addImage($elementImage);
			}
		}
	}

198 199
	private function createOpenHours($element, $row)
	{
200
		if (!isset($row['openhours']) || !$this->isAssociativeArray($row['openhours'])) return;
201
		$element->setOpenHours(new OpenHours($row['openhours']));
202 203 204 205 206 207 208 209 210 211
	}

	private function isAssociativeArray($a) {
    if (!is_array($a)) return false;
    foreach(array_keys($a) as $key)
      if (!is_int($key)) return true;
    return false;
  }


212 213 214 215 216 217 218 219 220 221 222 223
	function startsWith($haystack, $needle)
	{
	  $length = strlen($needle);
	  return (substr($haystack, 0, $length) === $needle);
	}

	private function createCategories($element, $row, $import)
	{
		$element->resetOptionsValues();
		$optionsIdAdded = [];
		$options = $row['categories'];

224 225 226 227
		$defaultOption = array("index" => 0, "description" => "");
		foreach ($options as $option) {
    	$option = array_merge($defaultOption, $option);
			$this->addOptionValue($element, $option['mappedId'], $option['index'], $option['description']);
228 229
		}

230 231 232 233 234 235 236 237 238 239 240 241 242
		if ($import->getNeedToHaveOptionsOtherThanTheOnesAddedToEachElements()) {
			// checking option number before adding optionIdsToAddToEachElement
			if (count($element->getOptionValues()) == 0) $element->setModerationState(ModerationState::NoOptionProvided);
		}

		// Manually add some options to each element imported
		foreach ($this->optionIdsToAddToEachElement as $optionId) {
			if (!in_array($optionId, $optionsIdAdded)) $optionsIdAdded[] = $this->addOptionValue($element, $optionId);
		}

		if (count($element->getOptionValues()) == 0) $element->setModerationState(ModerationState::NoOptionProvided);
	}

243
	private function addOptionValue($element, $id, $index = 0, $description = "")
244
	{
245
		if (!$id || $id == "0" || $id == 0) return;
246 247
		$optionValue = new OptionValue();
		$optionValue->setOptionId($id);
248 249
	  $optionValue->setIndex($index);
	  $optionValue->setDescription($description);
250 251 252 253
	  $element->addOptionValue($optionValue);
	  return $id;
	}
}