Skip to content

Instantly share code, notes, and snippets.

@awcodes
Created July 6, 2023 12:45
Show Gist options
  • Save awcodes/982873d502ed2ee7903c2f68a33623c5 to your computer and use it in GitHub Desktop.
Save awcodes/982873d502ed2ee7903c2f68a33623c5 to your computer and use it in GitHub Desktop.
Migrate Media from WordPress to Curator
<?php
public function fetchDataWithGraphQL(string $query, $variables = [], string $next = null): array
{
$response = Http::withBasicAuth(
config('services.domain.username'),
config('services.domain.password')
)->post('https://www.domain.com/graphql', [
'query' => $query,
'variables' => $variables,
]);
if ($response->successful()) {
return $response->json();
}
return [];
}
public function migrateMedia(): void
{
$this->newLine();
$this->comment('Migrating media files...');
$query = <<<'GRAPHQL'
query MediaQuery($first: Int, $after: String) {
mediaItems(first: $first, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
title(format: RENDERED)
slug
altText
databaseId
date
description(format: RENDERED)
fileSize
guid
mimeType
caption(format: RENDERED)
mediaDetails {
width
height
file
}
}
}
}
GRAPHQL;
$hasNextPage = true;
$after = '';
while($hasNextPage) {
$items = $this->fetchDataWithGraphQL($query, ['first' => 100, 'after' => $after]);
$hasNextPage = $items['data']['mediaItems']['pageInfo']['hasNextPage'];
$after = $items['data']['mediaItems']['pageInfo']['endCursor'];
if ($items['data']['mediaItems']['nodes']) {
$nodes = $items['data']['mediaItems']['nodes'];
$progress = $this->createProgressBar(count($nodes));
foreach ($nodes as $node) {
$this->storeImage($node);
$progress->advance();
}
$progress->finish();
$this->newLine();
if (count($nodes) < 100 && $hasNextPage) {
$hasNextPage = false;
}
}
}
}
public function storeImage(array $file): int
{
$directory = app('curator')->getDirectory();
$diskName = app('curator')->getDiskName();
if (str_contains($file['guid'], '/media/')) {
$filename = Str::of($file['guid'])
->after('media/')
->beforeLast('.')
->lower()
->toString();
} else {
$filename = Str::of($file['guid'])
->after('uploads/')
->beforeLast('.')
->lower()
->toString();
}
$extension = Str::of($file['guid'])
->afterLast('.')
->toString();
$path = $directory . '/' . $this->stripDomain($filename) . '.' . $extension;
$media = Media::create([
'name' => $filename,
'path' => $path,
'ext' => $extension,
'type' => $file['mimeType'],
'alt' => $file['altText'],
'title' => self::sanitizeString($file['title']),
'caption' => self::sanitizeString($file['caption']),
'description' => '',
'width' => $file['mediaDetails']['width'] ?? null,
'height' => $file['mediaDetails']['height'] ?? null,
'disk' => $diskName,
'size' => $file['fileSize'] ?? null,
'wp_id' => $file['databaseId'] ?? null,
]);
if (! Storage::disk($diskName)->exists($path)) {
if (str_contains($file['guid'], '/media/')) {
$file['guid'] = str_replace('/media/', '/wp-content/uploads/', $file['guid']);
}
try {
$imageData = file_get_contents($file['guid']);
Storage::disk($diskName)->put($path, $imageData);
} catch (\Exception $e) {}
}
return $media->id;
}
public function migratePosts(): void
{
$this->newLine();
$this->comment('Migrating blog posts...');
$query = <<<'GRAPHQL'
query PostsQuery($first: Int, $after: String) {
posts(first: $first, after: $after) {
pageInfo {
hasNextPage
endCursor
}
nodes {
dateGmt
content(format: RENDERED)
featuredImageDatabaseId
authorDatabaseId
modifiedGmt
seoTitle
seoRobots
seoDescription
slug
status
title(format: RENDERED)
terms {
nodes {
slug
}
}
}
}
}
GRAPHQL;
$hasNextPage = true;
$after = '';
while($hasNextPage) {
$items = $this->fetchDataWithGraphQL($query, ['first' => 100, 'after' => $after]);
$hasNextPage = $items['data']['posts']['pageInfo']['hasNextPage'];
$after = $items['data']['posts']['pageInfo']['endCursor'];
if ($items['data']['posts']['nodes']) {
$nodes = $items['data']['posts']['nodes'];
$progress = $this->createProgressBar(count($nodes));
foreach ($nodes as $node) {
$p = Post::create([
...
'featured_image' => Media::where('wp_id', $node['featuredImageDatabaseId'])->first()->id ?? null,
]);
$progress->advance();
}
$progress->finish();
$this->newLine();
if (count($nodes) < 100 && $hasNextPage) {
$hasNextPage = false;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment