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

Updated normalizeValue #75

Merged
merged 4 commits into from
Jun 15, 2021
Merged
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
47 changes: 35 additions & 12 deletions src/fields/OembedField.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
use craft\gql\resolvers\elements\MatrixBlock as MatrixBlockResolver;
use craft\gql\types\generators\MatrixBlockType as MatrixBlockTypeGenerator;
use craft\gql\types\QueryArgument;
use craft\helpers\ArrayHelper;
use craft\helpers\Gql as GqlHelper;
use craft\helpers\Json;
use craft\helpers\UrlHelper;
use GraphQL\Type\Definition\Type;
use wrav\oembed\gql\OembedFieldTypeGenerator;
use wrav\oembed\Oembed;
Expand Down Expand Up @@ -46,6 +49,11 @@ class OembedField extends Field
* @var array
*/
public $oembed = [];

/**
* @var mixed|null
*/
protected $value;

// Static Methods
// =========================================================================
Expand Down Expand Up @@ -105,23 +113,38 @@ public function getContentGqlType()
*/
public function normalizeValue($value, ElementInterface $element = null)
{
if (is_array($value)) {
if (isset($value['url'])) {
return new OembedModel($value['url']);
}
// If null, don’t proceed
if ($value === null) {
return null;
}

if (is_string($value) && $decValue = json_decode($value, true)) {
if (isset($decValue['url'])) {
return new OembedModel($decValue['url']);
}

// If an instance of `OembedModel` and URL is set, return it
if ($value instanceof OembedModel && $value->url) {
return $this->value = $value;
}

$oembed = $value ? new OembedModel($value) : null;
// If JSON object string, decode it and use that as the value
if (Json::isJsonObject($value)) {
$value = Json::decode($value); // Returns an array
}

$this->oembed = $oembed;
// If array with `url` attribute, that’s our url so update the value
if (is_array($value)) {
$value = ArrayHelper::getValue($value, 'url');
}

return $oembed;
// Run `getValue` twice to avoid https://github.com/wrav/oembed/issues/74
if (is_array($value)) {
$value = ArrayHelper::getValue($value, 'url');
}

// If URL string, return an instance of `OembedModel`
if (is_string($value) && UrlHelper::isFullUrl($value)) {
return $this->value = new OembedModel($value);
}

// If we get here, something’s gone wrong
return null;
joshuabaker marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down