Skip to content

Instantly share code, notes, and snippets.

@Mosnar
Created October 4, 2019 13:22
Show Gist options
  • Save Mosnar/896f2f8df8d184383e7bc8245c831463 to your computer and use it in GitHub Desktop.
Save Mosnar/896f2f8df8d184383e7bc8245c831463 to your computer and use it in GitHub Desktop.
Migrates Craft 2 Focal Point Fields to Native Craft 3 Focalpoints
<?php
namespace craft\contentmigrations;
use Craft;
use craft\db\Migration;
use craft\db\Query;
use craft\db\Table;
use craft\fields\Assets;
use craft\records\Asset;
use craft\records\Field;
/**
* m190925_192346_migrate_focalpoint migration.
*/
class m190925_192346_migrate_focalpoint extends Migration
{
/**
* @inheritdoc
*/
public function safeUp()
{
$sql = 'SELECT assetId, focusX, focusY FROM {{%focuspoint_focuspoints}}';
$data = $this->db->createCommand($sql)->queryAll();
foreach ($data as $fp) {
$craftformatted_point = $this->formatX($fp['focusX']) . ';' . $this->formatY($fp['focusY']);
$assetID = $fp['assetId'];
print("Update $assetID to $craftformatted_point" . PHP_EOL);
$this->update(Table::ASSETS, ['focalPoint' => $craftformatted_point], ['id' => $assetID]);
}
$query = (new Query())->select(['id'])->from(Table::FIELDS)->where(['type' => 'FocusPoint_FocusPoint']);
$fieldsToUpdate = $query->all();
foreach($fieldsToUpdate as $field) {
$fieldRecord = Field::findOne($field['id']);
$fieldRecord->type = Assets::class;
$fieldRecord->save();
print('Updated field: '. $field['id'] . PHP_EOL);
}
}
private function formatX(float $val)
{
return sprintf('%01.4f', ((($val + 1) / 2) * 1));
}
private function formatY(float $val)
{
return sprintf('%01.4f', ((($val - 1) / 2) * -1));
}
/**
* @inheritdoc
*/
public function safeDown()
{
echo "m190925_192346_migrate_focalpoint cannot be reverted.\n";
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment