Skip to content

Instantly share code, notes, and snippets.

@cmuench
Last active January 26, 2025 10:17
Show Gist options
  • Save cmuench/31dd3b15ff2b9ac15c3a16012b09e2ab to your computer and use it in GitHub Desktop.
Save cmuench/31dd3b15ff2b9ac15c3a16012b09e2ab to your computer and use it in GitHub Desktop.
Statamic: Convert image field data to responsive field
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Yaml\Yaml;
/**
* This command converts the content of a image field to a responsive image field
* in the markdown data of a collection.
*/
class ResponsiveConvertFieldContentCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'responsive:convert-field-content
{collection : The name of the collection to process (e.g., articles)}
{field : The name of the field to convert (e.g., image)}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Convert an image field to a responsive field in a Statamic collection';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$collection = $this->argument('collection');
$field = $this->argument('field');
$basePath = base_path("content/collections/$collection");
if (!is_dir($basePath)) {
$this->error("The collection directory '$basePath' does not exist.");
return Command::FAILURE;
}
$files = scandir($basePath);
foreach ($files as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) !== 'md') {
continue;
}
$filePath = "$basePath/$file";
$content = file_get_contents($filePath);
if (strpos($content, '---') === false) {
$this->line("Skipping file without front matter: $file");
continue;
}
// Split the content into front matter and body
$parts = preg_split('/---[\r\n]/', $content, 3);
if (count($parts) < 3) {
$this->line("Skipping file with invalid front matter: $file");
continue;
}
[$before, $frontMatter, $body] = $parts;
// Parse YAML
$data = Yaml::parse($frontMatter);
// Update the specified field
if (isset($data[$field])) {
$imagePath = $data[$field];
// Handle different formats of the image path
if (is_array($imagePath)) {
$imagePath = reset($imagePath); // Get the first element if it's an array
}
$data[$field] = [
'src' => (string) $imagePath, // Ensure it's treated as a string
];
}
// Save the updated file
$newFrontMatter = Yaml::dump($data, 2, 2);
$newContent = "---\n" . $newFrontMatter . "---\n" . trim($body);
file_put_contents($filePath, $newContent);
$this->info("Converted field in file: $file");
}
$this->info('Conversion completed.');
return Command::SUCCESS;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment