Skip to content

Instantly share code, notes, and snippets.

@jacksleight
Last active February 28, 2023 14:39
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jacksleight/9495628eab586117e5d3b3bfb33111c3 to your computer and use it in GitHub Desktop.
Save jacksleight/9495628eab586117e5d3b3bfb33111c3 to your computer and use it in GitHub Desktop.
Convert legacy Bard Text Align mark values to Tiptap 2 text align values
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(\Statamic\Fieldtypes\Bard::class, \App\Fieldtypes\Bard::class);
}
}
<?php
namespace App\Fieldtypes;
class Bard extends \Statamic\Fieldtypes\Bard
{
protected function convertLegacyTiptap($value)
{
return parent::convertLegacyTiptap($this->convertLegacyTextAlign($value));
}
protected function convertLegacyTextAlign($value)
{
if (is_string($value)) {
return $value;
}
if (! in_array($value['type'] ?? null, ['heading', 'paragraph'])) {
return $value;
}
$found = null;
foreach (($value['content'] ?? []) as $i => $node) {
if (! isset($node['marks'])) {
continue;
}
foreach ($node['marks'] as $j => $mark) {
if ($mark['type'] === 'textAlign') {
unset($value['content'][$i]['marks'][$j]);
if (! $found) {
$found = $mark;
}
}
}
if (! count($value['content'][$i]['marks'])) {
unset($value['content'][$i]['marks']);
} else {
$value['content'][$i]['marks'] = array_values($value['content'][$i]['marks']);
}
}
if (! $found) {
return $value;
}
$value['attrs']['textAlign'] = $found['attrs']['align'];
return $value;
}
}
@MrMooky
Copy link

MrMooky commented Feb 17, 2023

Thanks a lot. I had to add another condition before the foreach ($value['content'] as $i => $node) loop. Otherwise it was throwing Undefined array key "content" in my case as there are a bunch of $values without that key.

if (! array_key_exists('content', $value)) {
    return $value;
}

@jacksleight
Copy link
Author

@MrMooky Ah good spot, I've updated it to handle that.

@spaceageliving
Copy link

@jacksleight Just installed this, it appears to working like a champ! Thanks!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment