Last active
August 2, 2023 11:06
-
-
Save tomdavies/208b743a24efd003f0692620ae83662d to your computer and use it in GitHub Desktop.
Adding a custom DataType to Feed Me for CraftCMS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace modules\datatypes; | |
use craft\feedme\datatypes\Json; | |
use illuminate\Support\Collection; | |
class CustomJsonDatatype extends Json | |
{ | |
/** | |
* @var string | |
*/ | |
// This will be the name of the Feed Type visible when setting up the feed | |
public static string $name = 'Custom JSON'; | |
// Public Methods | |
// ========================================================================= | |
/** | |
* @inheritDoc | |
*/ | |
public function getFeed($url, $settings, bool $usePrimaryElement = true): array | |
{ | |
// Get the feed from the parent class | |
$feed = parent::getFeed($url, $settings, $usePrimaryElement); | |
// Map over the data key with our custom transformer method | |
$feed['data'] = collect($feed['data']) | |
->map(function($item) { | |
return $this->transformItem(collect($item)); | |
}) | |
->toArray(); | |
return $feed; | |
} | |
public function transformItem(Collection $item): ?Collection | |
{ | |
// do whatever you want here to each item | |
if ($item->Category) { | |
$values = collect(explode('|', $item->Category)); | |
$item->put('Category', $values->map(fn($value) => trim($value))->toArray()); | |
} | |
return $item; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace modules; | |
use Craft; | |
use craft\feedme\events\RegisterFeedMeDataTypesEvent; | |
use craft\feedme\services\DataTypes; | |
use modules\datatypes\CustomJsonDatatype; | |
use yii\base\Event; | |
use yii\base\Module as BaseModule; | |
class Module extends BaseModule | |
{ | |
public function init(): void | |
{ | |
Craft::setAlias('@modules', __DIR__); | |
parent::init(); | |
Craft::$app->onInit(function() { | |
$this->registerFeedMeDataTypes(); | |
}); | |
} | |
private function registerFeedMeDataTypes(): void | |
{ | |
// see https://docs.craftcms.com/feed-me/v4/developers/data-types.html#the-registerfeedmedatatypes-event | |
Event::on( | |
DataTypes::class, | |
DataTypes::EVENT_REGISTER_FEED_ME_DATA_TYPES, | |
static function(RegisterFeedMeDataTypesEvent $e) { | |
$e->dataTypes[] = CustomJsonDatatype::class; | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment