Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/1194 native alt field #1460

Draft
wants to merge 4 commits into
base: 5.x
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 40 additions & 6 deletions src/base/Field.php
Original file line number Diff line number Diff line change
Expand Up @@ -143,16 +143,47 @@ public function fetchValue(): mixed
// =========================================================================

/**
* @param $elementIds
* @param null $nodeKey
* Save native field data on the elements.
*
* @param array $elementIds
* @param string|null $nodeKey
* @return void
* @throws Throwable
* @throws ElementNotFoundException
* @throws Exception
*/
protected function populateNativeFields(array $elementIds, string $nodeKey = null): void
{
$this->populateFields($elementIds, $nodeKey, 'native');
}

/**
* @param array $elementIds
* @param string|null $nodeKey
* @return void
* @throws Throwable
* @throws ElementNotFoundException
* @throws Exception
*/
protected function populateElementFields($elementIds, $nodeKey = null): void
protected function populateElementFields(array $elementIds, string $nodeKey = null): void
{
$this->populateFields($elementIds, $nodeKey);
}

/**
* @param array $elementIds Array of elementIds to populate.
* @param string|null $nodeKey
* @param string $fieldType Type of field to populate, can be `custom` or `native`.
* @return void
* @throws Throwable
* @throws ElementNotFoundException
* @throws Exception
*/
private function populateFields(array $elementIds, string $nodeKey = null, string $fieldType = 'custom'): void
{
$elementsService = Craft::$app->getElements();
$fields = Hash::get($this->fieldInfo, 'fields');
$fieldTypeKey = $fieldType === 'custom' ? 'fields' : 'nativeFields';
$fields = Hash::get($this->fieldInfo, $fieldTypeKey);

$fieldData = [];

Expand All @@ -167,7 +198,6 @@ protected function populateElementFields($elementIds, $nodeKey = null): void

// Arrayed content doesn't provide defaults because it's unable to determine how many items it _should_ return
// This also checks if there was any data that corresponds on the same array index/level as our element
/** @phpstan-ignore-next-line */
$value = Hash::get($fieldValue, $nodeKey ?? $key, $default);

if ($value) {
Expand All @@ -180,7 +210,11 @@ protected function populateElementFields($elementIds, $nodeKey = null): void
foreach ($fieldData as $elementId => $fieldContent) {
$element = $elementsService->getElementById($elementId, null, Hash::get($this->feed, 'siteId'));

$element->setFieldValues($fieldContent);
if ($fieldType === 'native') {
$element->setAttributes($fieldContent);
} else {
$element->setFieldValues($fieldContent);
}

Plugin::debug([
$this->fieldHandle => [
Expand Down
5 changes: 5 additions & 0 deletions src/events/RegisterFeedMeFieldsEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,9 @@ class RegisterFeedMeFieldsEvent extends Event
* @var array
*/
public array $fields = [];

/**
* @var array
*/
public array $nativeFields = [];
}
57 changes: 57 additions & 0 deletions src/fieldlayoutelements/assets/Alt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace craft\feedme\fieldlayoutelements\assets;

use craft\feedme\base\Field;
use craft\feedme\base\FieldInterface;
use craft\fieldlayoutelements\assets\AltField;

/**
*
* @property-read string $mappingTemplate
*/
class Alt extends Field implements FieldInterface
{
// Properties
// =========================================================================

/**
* @var string
*/
public static string $name = 'Alt';

/**
* @var string
*/
public static string $class = AltField::class;

// Templates
// =========================================================================

/**
* @inheritDoc
*/
public function getMappingTemplate(): string
{
return 'feed-me/_includes/fieldlayoutelements/assets/alt';
}

// Public Methods
// =========================================================================

/**
* @inheritDoc
*/
public function parseField(): mixed
{
// used when importing into Asset element directly
// when importing into the sub-fields of the assets field, this will go through src/fields/Assets.php->parseField()
$value = $this->fetchValue();

if ($value === null) {
return null;
}

return $value;
}
}
202 changes: 202 additions & 0 deletions src/fieldlayoutelements/users/Addresses.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
<?php

namespace craft\feedme\fieldlayoutelements\users;

use Cake\Utility\Hash;
use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\elements\Address as AddressElement;
use craft\errors\ElementNotFoundException;
use craft\feedme\base\Field;
use craft\feedme\base\FieldInterface;
use craft\feedme\helpers\DataHelper;
use craft\feedme\Plugin;
use craft\fieldlayoutelements\users\AddressesField as AddressesField;
use craft\helpers\ArrayHelper;
use craft\helpers\Json;

/**
*
* @property-read string $mappingTemplate
*/
class Addresses extends Field implements FieldInterface
{
// Properties
// =========================================================================

/**
* @var string
*/
public static string $name = 'Addresses';

/**
* @var string
*/
public static string $class = AddressesField::class;

/**
* @var string
*/
public static string $elementType = AddressElement::class;


// Templates
// =========================================================================

/**
* @inheritDoc
*/
public function getMappingTemplate(): string
{
return 'feed-me/_includes/fieldlayoutelements/users/addresses';
}

// Public Methods
// =========================================================================

/**
* @inheritDoc
*/
public function parseField(): mixed
{
$fieldValue = [];

$fields = Hash::get($this->fieldInfo, 'fields');
$nativeFields = Hash::get($this->fieldInfo, 'nativeFields');

// figure out how many addresses we have in the dataset
$fieldGroups = array_filter(
['nativeFields' => $nativeFields, 'fields' => $fields],
fn($group) => !empty($group)
);
$noAddresses = $this->getNumberOfAddresses($fieldGroups);

for ($i = 0; $i < $noAddresses; $i++) {
// we have to find/create Address element here
// todo - should we allow finding an existing address? if so, what should we map by? id and custom fields?
$element = $this->_createElement($nativeFields, $i);

// if we were able to save the address, and we have fields to process, go ahead and do that
if ($element && $fields) {
$this->populateElementFields([$element->id], $i);
}

// returning just the address id for compareElementContent check
$fieldValue[] = $element->id;
}

return $fieldValue;
}

private function handleNativeFields(ElementInterface $element, array $nativeFields, int $nodeKey): void
{
$attributeValues = [];
foreach ($nativeFields as $fieldHandle => $fieldInfo) {
$default = Hash::get($fieldInfo, 'default');
//$fieldValue = DataHelper::fetchArrayValue($this->feedData, $fieldInfo);
$fieldValue = DataHelper::fetchValue($this->feedData, $fieldInfo, $this->feed);

// Find the class to deal with the attribute
$name = 'parse' . ucwords($fieldHandle);

// Set a default handler for non-specific attribute classes
if (!method_exists($this, $name)) {
$value = Hash::get($fieldValue, $nodeKey, $default);
} else {
$value = $this->$name($element, $fieldInfo, $nodeKey);
}

if (!empty($value)) {
$attributeValues[$fieldHandle] = $value;
}
}

if (!empty($attributeValues)) {
$element->setAttributes($attributeValues, false);
}
}

private function parseAddress($element, $fieldInfo, $nodeKey): void
{
$nativeFields = Hash::get($fieldInfo, 'nativeFields');
$this->handleNativeFields($element, $nativeFields, $nodeKey);
}

private function parseLatLong($element, $fieldInfo, $nodeKey): void
{
$nativeFields = Hash::get($fieldInfo, 'nativeFields');
$this->handleNativeFields($element, $nativeFields, $nodeKey);
}

private function getNumberOfAddresses(array $fields): int
{
$noAddresses = 0;

foreach ($fields as $fieldTypeGroup) {
foreach ($fieldTypeGroup as $fieldInfo) {
$node = Hash::get($fieldInfo, 'node');
if ($node) {
$nodeSegments = explode('/', $node);
$regex = str_replace('//', '/', implode('\/\d?\/', $nodeSegments));
$matches = preg_grep('/' . $regex . '/', array_keys($this->feedData));
if (count($matches) > $noAddresses) {
$noAddresses = count($matches);
}
}
}
}

return $noAddresses;
}

// Private Methods
// =========================================================================

/**
* @param array $nativeFields
* @param int $nodeIndex
* @return ElementInterface|null
*/
private function _createElement(array $nativeFields, int $nodeIndex): ?ElementInterface
{
$element = new AddressElement();
$element->setScenario(Element::SCENARIO_ESSENTIALS);
$element->setOwner($this->element);

// native fields have to go first!
if ($nativeFields) {
$this->handleNativeFields($element, $nativeFields, $nodeIndex);
}

if (!Craft::$app->getElements()->saveElement($element)) {
Plugin::error('Address error: Could not create - `{e}`.', ['e' => Json::encode($element->getErrors())]);

return null;
}

Plugin::info('Address `#{id}` added.', ['id' => $element->id]);

return $element;
}

/**
* Attempt to find User based on search criteria. Return array of found IDs.
*
* @param $criteria
* @return array|int[]
*/
private function _findAddresses($criteria): array
{
$query = AddressElement::find();
Craft::configure($query, $criteria);

Plugin::info('Search for existing address with query `{i}`', ['i' => json_encode($criteria)]);

$ids = $query->ids();

Plugin::info('Found `{i}` existing addresses: `{j}`', ['i' => count($ids), 'j' => json_encode($ids)]);

return $ids;
}
}
7 changes: 7 additions & 0 deletions src/fields/Assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ public function parseField(): mixed
$upload = Hash::get($this->fieldInfo, 'options.upload');
$conflict = Hash::get($this->fieldInfo, 'options.conflict');
$fields = Hash::get($this->fieldInfo, 'fields');
$nativeFields = Hash::get($this->fieldInfo, 'nativeFields');
$node = Hash::get($this->fieldInfo, 'node');
$nodeKey = null;

Expand Down Expand Up @@ -252,6 +253,12 @@ public function parseField(): mixed
$this->populateElementFields($foundElements, $nodeKey);
}

// this is used by the sub-fields of the assets field; not when importing into Asset element directly;
// when importing into Asset element directly, src/fieldlayoutelements/assets/Alt.php is used
if ($nativeFields) {
$this->populateNativeFields($foundElements, $nodeKey);
}

$foundElements = array_unique($foundElements);

// Protect against sending an empty array - removing any existing elements
Expand Down
Loading
Loading