Skip to content

Commit

Permalink
Parse JSON arrays as relationship values
Browse files Browse the repository at this point in the history
  • Loading branch information
duncanmcclean committed Nov 12, 2024
1 parent dc44d69 commit 1d503b8
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Transformers/AssetsTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ public function transform(string $value): null|string|array
$baseUrl = $this->config('base_url');
$relatedField = $this->config('related_field', 'path');

// When $value is a JSON string, decode it.
if (Str::startsWith($value, ['{', '[']) || Str::startsWith($value, ['[', ']'])) {
$value = collect(json_decode($value, true))->join('|');
}

$assets = collect(explode('|', $value))->map(function ($path) use ($assetContainer, $relatedField, $baseUrl) {
$path = Str::of($path)
->when($relatedField === 'url' && $baseUrl, function ($str) use ($baseUrl) {
Expand Down
5 changes: 5 additions & 0 deletions src/Transformers/EntriesTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ public function transform(string $value): null|string|array
$value = collect(unserialize($value))->join('|');
}

// When $value is a JSON string, decode it.
if (Str::startsWith($value, ['{', '[']) || Str::startsWith($value, ['[', ']'])) {
$value = collect(json_decode($value, true))->join('|');
}

if ($this->config('related_field') === 'id') {
return is_string($value) ? explode('|', $value) : $value;
}
Expand Down
5 changes: 5 additions & 0 deletions src/Transformers/TermsTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ class TermsTransformer extends AbstractTransformer
{
public function transform(string $value): null|string|array
{
// When $value is a JSON string, decode it.
if (Str::startsWith($value, ['{', '[']) || Str::startsWith($value, ['[', ']'])) {
$value = collect(json_decode($value, true))->join('|');
}

$terms = collect(explode('|', $value))->map(function ($value) {
$term = Term::query()
->whereIn('taxonomy', Arr::wrap($this->field->get('taxonomies')))
Expand Down
6 changes: 6 additions & 0 deletions src/Transformers/UsersTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,17 @@
namespace Statamic\Importer\Transformers;

use Statamic\Facades\User;
use Statamic\Support\Str;

class UsersTransformer extends AbstractTransformer
{
public function transform(string $value): null|string|array
{
// When $value is a JSON string, decode it.
if (Str::startsWith($value, ['{', '[']) || Str::startsWith($value, ['[', ']'])) {
$value = collect(json_decode($value, true))->join('|');
}

if ($this->config('related_field') === 'id') {
if (is_string($value)) {
return explode('|', $value);
Expand Down

0 comments on commit 1d503b8

Please sign in to comment.