Skip to content

Commit

Permalink
✨ Add richText caster method
Browse files Browse the repository at this point in the history
  • Loading branch information
bbs-smuller committed Jun 20, 2019
1 parent 6a4e8f9 commit 14d7334
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"require": {
"php": ">=7.1.3",
"ext-json": "*",
"contentful/contentful": "^4.1",
"erusev/parsedown": "^1.7",
"guzzlehttp/guzzle": "^6.3",
"illuminate/support": "~5.6|~5.7|~5.8",
Expand Down
23 changes: 23 additions & 0 deletions src/Distilleries/Contentful/Helpers/Caster.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Exception;
use Illuminate\Support\Carbon;
use Contentful\RichText\Renderer;
use Illuminate\Support\Collection;
use Distilleries\Contentful\Models\Location;

Expand Down Expand Up @@ -78,6 +79,28 @@ public static function fromJson($json): ?array
return $data;
}

/**
* Return rendered HTML rich-text data.
*
* @param mixed $object
* @return string|null
*/
public static function richText($object): ?string
{
$html = '';

if (! empty($object)) {
try {
$node = app('contentful.rich-text.parser')->parse($object);
$html = (new Renderer)->render($node);
} catch (Exception $e) {
dd($e->getMessage());
}
}

return $html;
}

/**
* Transform markdown content to an HTML string.
*
Expand Down
27 changes: 27 additions & 0 deletions src/Distilleries/Contentful/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public function provides(): array
'command.contentful.sync-locales',
'command.contentful.import-clean',
'command.contentful.import-publish',
'contentful.rich-text.parser'
];
}

Expand Down Expand Up @@ -58,6 +59,8 @@ public function register()
$this->app->bind(Api\SyncApi::class, Api\Sync\Api::class);
$this->app->bind(Api\UploadApi::class, Api\Upload\Api::class);

$this->registerContentfulRelated();

if ($this->app->runningInConsole()) {
$this->registerCommands();
}
Expand Down Expand Up @@ -108,4 +111,28 @@ private function registerCommands()
$this->commands('command.contentful.import-clean');
$this->commands('command.contentful.import-publish');
}

/**
* Bind utilities in IoC.
*
* @return void
*/
private function registerContentfulRelated()
{
$this->app->singleton('contentful.rich-text.parser', function () {
$spaceId = config('contentful.space_id');
$environment = config('contentful.environment');

$client = new \Contentful\Delivery\Client(config('contentful.tokens.delivery.live'), $spaceId, $environment);
$linkResolver = new \Contentful\Delivery\LinkResolver(
$client,
new \Contentful\Delivery\ResourcePool\Extended(
$client,
new \Cache\Adapter\Void\VoidCachePool
)
);

return new \Contentful\RichText\Parser($linkResolver);
});
}
}

0 comments on commit 14d7334

Please sign in to comment.