Skip to content

Instantly share code, notes, and snippets.

@tdwesten
Created May 14, 2020 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdwesten/c1cd227b9c1eb4348f50f77c25df7019 to your computer and use it in GitHub Desktop.
Save tdwesten/c1cd227b9c1eb4348f50f77c25df7019 to your computer and use it in GitHub Desktop.
acf importer
<?php
/**
* Created by PhpStorm.
* User: thomasvanderwesten
* Date: 02-11-17
* Time: 11:25
*/
namespace AcfGroups;
use WP_CLI;
class acfJsonImporter {
private static $json_folder_path = false;
private static $acf_builder_path = false;
private static $tabs_one = ' ';
private static $tabs_two = ' ';
private static $tabs_three = ' ';
private static $tabs_four = ' ';
private static $tabs_five = ' ';
private static $tabs_six = ' ';
private static $tabs_seven = ' ';
public static function init() {
if ( class_exists( 'WP_CLI' ) ) {
WP_CLI::add_command( 'acfgroupsimport', [ get_called_class(), 'importData' ], $args = [], $assoc_args = [] );
}
self::$json_folder_path = get_stylesheet_directory() . '/acf-json';
self::$acf_builder_path = get_stylesheet_directory() . '/AcfGroups';
}
public static function importData( $args, $assoc_args ) {
$arguments = wp_parse_args( $assoc_args, [
'skip_existing_classes' => true,
] );
WP_CLI::log( 'Start import' );
WP_CLI::log( '--------------' );
foreach ( self::list_json_files() as $file ) {
self::parseFile( $file, $arguments );
}
WP_CLI::log( '--------------' );
WP_CLI::log( 'Import finished' );
}
public static function list_json_files() {
$files = [];
foreach ( glob( self::$json_folder_path . "/*.json" ) as $filename ) {
$files[] = $filename;
}
return $files;
}
/**
* @param string $file_path
* @param array $args
*
* @return bool
*/
public static function parseFile( $file_path, $args ) {
$content = file_get_contents( $file_path );
$json = json_decode( $content );
$class_name = preg_replace( '/[^A-Za-z0-9\-]/', '', ucwords( $json->title ) );
$group_title = $json->title;
if ( isset( $args['skip_existing_classes'] ) && ( $args['skip_existing_classes'] || $args['skip_existing_classes'] == 'true' ) ) {
// Skip import when file exists
if ( file_exists( self::$acf_builder_path . '/' . $class_name . '.php' ) ) {
WP_CLI::log( 'File ‘' . $class_name . '.php’ skipped. Class alreay exists. Remove class before importing.' );
return false;
}
}
//
unset( $json->title );
$fields = $json->fields;
unset( $json->fields );
//
$location = $json->location;
unset( $json->location );
unset( $json->modified );
unset( $json->active );
$group_args = self::parseArgs( $json );
// @formatter:off
$file = '<?php
namespace AcfGroups;
use StoutLogic\AcfBuilder\FieldsBuilder;
class ' . $class_name . ' extends Base {
public static function make() {
$field_group_title = \'' . $group_title . '\';
$group = new FieldsBuilder( sanitize_title_with_dashes( $field_group_title ), ' . $group_args . ' );
';
if ( isset( $fields ) && count( $fields ) > 0 ) {
$file .= PHP_EOL . self::$tabs_two . '$group' . PHP_EOL;
$file .= self::$tabs_three . '->setGroupConfig( \'title\', $field_group_title )' . PHP_EOL;
foreach ( $fields as $field ) {
$file .= self::parseFields( $field );
}
$file .= self::parseLocation( $location );
$file .= ';'; // add comma to last item
}
$file .= PHP_EOL . PHP_EOL . self::$tabs_two . 'self::create_group( $group );' . PHP_EOL;
$file .= self::$tabs_one . '}' . PHP_EOL . '}'; // close class
// @formatter:on
unset( $json->fields );
// Write the contents back to the file
WP_CLI::log( 'File ‘' . $class_name . '.php’ created.' );
file_put_contents( self::$acf_builder_path . '/' . $class_name . '.php', $file );
return true;
}
/**
* @param $field
*
* @return string
*/
public static function parseFields( $field ) {
$html = '';
$field_type = self::get_field_type( $field->type );
if ( $field_type === 'addMessage' ) {
$html = self::parseMessage( $field );
} else if ( $field_type === 'addRepeater' ) {
$html = self::parseRepeater( $field );
} else if ( $field_type == 'addFlexibleContent' ) {
$html = self::parseFlexibleContent( $field );
} else if ( $field_type === 'addSelect' || $field_type === 'addRadio' || $field_type === 'addCheckbox' ) {
$html = self::parseChoices( $field );
} else if ( $field_type === 'addField' ) {
$html = self::parseCustomField( $field );
} else {
$html = self::parseField( $field, $html );
}
return $html;
}
/**
* @param $field
* @param bool $incremental
*
* @return string
*/
public static function parseArgs( $field, $incremental = false, $is_conditional = false ) {
$args = '';
$excluded_keys = [
'type',
'name',
'sub_fields',
'layouts',
];
if ( $incremental && self::has_empty_fields_only( $field ) ) {
return '';
}
$args .= $is_conditional ? PHP_EOL . self::$tabs_six : ( $incremental ? PHP_EOL . self::$tabs_four : '' );
$args .= '[';
foreach ( $field as $key => $val ) {
if ( ( ! empty( $val ) || is_array( $val ) ) && $val !== '0' && ! in_array( $key, $excluded_keys ) ) {
// If field_args has key 'collapsed', get correct field name from sub fields
if ( $key === 'collapsed' && isset( $field->sub_fields ) ) {
foreach ( $field->sub_fields as $sub ) {
if ( $sub->key === $val ) {
$val = $sub->name;
}
}
}
if ( is_object( $val ) ) {
$temp_args = self::parseArgs( $val, true );
if ( $key === 'choices' ) {
$args = '\'choices\' => [' . $temp_args . '],';
} else {
$args .= $temp_args;
}
} else if ( is_array( $val ) ) {
$args .= PHP_EOL . self::$tabs_four . '\'' . $key . '\' => ';
$args .= '[';
foreach ( $val as $item ) {
if ( is_array( $item ) ) {
$args .= PHP_EOL . self::$tabs_five . '[';
foreach ( $item as $con_key => $con_val ) {
if ( is_object( $con_val ) ) {
$temp_con_args = self::parseArgs( $con_val, true, true );
$args .= $temp_con_args;
}
}
$args .= PHP_EOL . self::$tabs_five . '],';
} else {
$args .= '\'' . $item . '\', ';
}
}
$args .= $key === 'conditional_logic' ? PHP_EOL . self::$tabs_four . '],' : '],';
} else {
$val = str_replace( "\n", "\\n", $val ); // remove new lines
$val = str_replace( '"', '\"', $val ); // remove new lines
$val = str_replace( "\r", "\\r", $val ); // remove carriage returns
$tabs = $is_conditional ? self::$tabs_seven : self::$tabs_four;
$args .= PHP_EOL . $tabs . '\'' . $key . '\' => "' . $val . '",';
}
} else {
continue;
}
}
$args .= PHP_EOL;
$args .= $is_conditional ? self::$tabs_six : ( $incremental ? self::$tabs_four : self::$tabs_three );
$args .= $incremental ? '],' : ']';
return $args;
}
public static function has_empty_fields_only( $field ) {
$is_empty = true;
foreach ( $field as $key => $val ) {
if ( ! empty( $val ) && $val !== '0' ) {
$is_empty = false;
}
}
return $is_empty;
}
/**
* Parse Field type from AcfJson to AcfGroups naming
*
* @param $field_type
*
* @return bool|mixed
*/
public static function get_field_type( $field_type ) {
$fields = [
'message' => 'addMessage',
'wysiwyg' => 'addWysiwyg',
'text' => 'addText',
'image' => 'addImage',
'post_object' => 'addPostObject',
'repeater' => 'addRepeater',
'textarea' => 'addTextarea',
'flexible_content' => 'addFlexibleContent',
'select' => 'addSelect',
'radio' => 'addRadio',
'checkbox' => 'addCheckbox',
'true_false' => 'addTrueFalse',
'link' => 'addLink',
'page_link' => 'addPageLink',
'relationship' => 'addRelationship',
];
if ( isset( $fields[ $field_type ] ) ) {
return $fields[ $field_type ];
} else {
return 'addField';
}
}
public static function parseField( $field, $html ) {
$field_type = self::get_field_type( $field->type );
if ( $field_type ) {
$html .= self::$tabs_three . '->' . self::get_field_type( $field->type ) . '( \'' . $field->name . '\', ' . self::parseArgs( $field ) . ' )' . PHP_EOL;
}
return $html;
}
/**
* Parse location for AcfGroup
*
* @param $locations
*
* @return string
*/
public static function parseLocation( $locations ) {
$args = '';
if ( is_array( $locations ) ) {
foreach ( $locations as $key => $loc ) {
if ( is_array( $loc ) && count( $loc ) > 1 ) {
foreach ( $loc as $i => $l ) {
$args .= $key === 0 && $i === 0 ? self::$tabs_three . '->setLocation( ' . self::setLocationField( $l ) . ' )' : PHP_EOL . self::$tabs_four . '->and( ' . self::setLocationField( $l ) . ' )';
}
} else {
$l = array_shift( $loc );
if ( is_object( $l ) ) {
$args .= $key === 0 ? self::$tabs_three . '->setLocation( ' . self::setLocationField( $l ) . ' )' : PHP_EOL . self::$tabs_four . '->or( ' . self::setLocationField( $l ) . ' )';
}
}
}
}
return $args;
}
/**
* Set Location in correct format
*
* @param $location
*
* @return bool|string
*/
public static function setLocationField( $location ) {
if ( ! is_object( $location ) ) {
return false;
}
return '\'' . $location->param . '\', \'' . $location->operator . '\', \'' . $location->value . '\'';
}
/**
* Parse Message field
*
* @param $field
*
* @return string
*/
public static function parseMessage( $field ) {
$message = $field->message;
$message = str_replace( "\n", "\\n", $message ); // keep new lines
$message = str_replace( '"', '\"', $message ); // escape double quotes
$message = str_replace( "\r", "\\r", $message ); // keep carriage returns
unset( $field->message );
return self::$tabs_three . '->' . self::get_field_type( $field->type ) . '( \'' . $field->label . '\', "' . $message . '", ' . self::parseArgs( $field ) . ' )' . PHP_EOL;
}
/**
* Parse Repeater field
*
* @param $field
*
* @return string
*/
public static function parseRepeater( $field ) {
$field_args = self::parseArgs( $field );
$get_sub_fields = isset( $field->sub_fields ) ? $field->sub_fields : false;
$sub_fields = '';
if ( is_array( $get_sub_fields ) ) {
foreach ( $get_sub_fields as $sub_field ) {
$sub_fields .= self::parseFields( $sub_field );
}
}
$html = self::$tabs_three . '->' . self::get_field_type( $field->type ) . '( \'' . $field->name . '\', ' . $field_args . ' )' . PHP_EOL;
$html .= $sub_fields;
$html .= self::$tabs_three . '->endRepeater()' . PHP_EOL;
return $html;
}
/**
* Parse Flexible Content field
*
* @param $field
*
* @return string
*/
public static function parseFlexibleContent( $field ) {
$field_args = self::parseArgs( $field );
$get_layouts = isset( $field->layouts ) ? $field->layouts : false;
$layouts = '';
if ( $get_layouts instanceof \stdClass || is_array( $get_layouts ) ) {
foreach ( $get_layouts as $layout ) {
$layout_args = self::parseArgs( $layout );
$get_sub_fields = $layout->sub_fields;
$sub_fields = '';
if ( is_array( $get_sub_fields ) ) {
foreach ( $get_sub_fields as $sub_field ) {
$sub_fields .= self::parseFields( $sub_field );
}
}
$layouts .= PHP_EOL . self::$tabs_three . '->addLayout( \'' . $layout->name . '\', ' . $layout_args . ' )' . PHP_EOL;
$layouts .= $sub_fields;
}
}
$html = self::$tabs_three . '->' . self::get_field_type( $field->type ) . '( \'' . $field->name . '\', ' . $field_args . ' )' . PHP_EOL;
$html .= $layouts;
return $html;
}
/**
* Parse Select
*
* @param $field
*
* @return string
*/
public static function parseChoices( $field ) {
$get_choices = $field->choices;
unset( $field->choices );
$choices = '[';
foreach ( $get_choices as $key => $val ) {
$choices .= PHP_EOL . self::$tabs_four . '[ \'' . $key . '\' => \'' . $val . '\' ],';
}
$choices .= PHP_EOL . self::$tabs_three . ']';
$field_args = self::parseArgs( $field );
$html = self::$tabs_three . '->' . self::get_field_type( $field->type ) . '( \'' . $field->name . '\', ' . $field_args . ' )' . PHP_EOL;
$html .= self::$tabs_three . '->addChoices( ' . $choices . ' )' . PHP_EOL;
return $html;
}
/**
* Parse uncommon field
*
* @param $field
*
* @return string
*/
public static function parseCustomField( $field ) {
$html = self::$tabs_three . '->addField( \'' . $field->name . '\', \'' . $field->type . '\', ' . self::parseArgs( $field ) . ' )' . PHP_EOL;
return $html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment