diff --git a/css/anchored-header.css b/css/anchored-header.css
index 02ca0c2..8f409b2 100644
--- a/css/anchored-header.css
+++ b/css/anchored-header.css
@@ -5,15 +5,15 @@ h3[id]:hover a.anchorlink:before,
h4[id]:hover a.anchorlink:before,
h5[id]:hover a.anchorlink:before,
h6[id]:hover a.anchorlink:before {
- color: #888;
- content: "\f103"; /*dashicons-admin-links*/
- font-size: smaller;
- text-decoration: none;
- vertical-align: baseline;
+ color: #888;
+ content: "\f103"; /*dashicons-admin-links*/
+ font-size: smaller;
+ text-decoration: none;
+ vertical-align: baseline;
}
a.anchorlink {
- font-size: smaller;
- margin-left: 0.5em;
- text-decoration: none;
+ font-size: smaller;
+ margin-left: 0.5em;
+ text-decoration: none;
}
diff --git a/inc/docs.php b/inc/class-docs.php
similarity index 76%
rename from inc/docs.php
rename to inc/class-docs.php
index 60e282c..c7d4693 100644
--- a/inc/docs.php
+++ b/inc/class-docs.php
@@ -1,10 +1,25 @@
$cmd ) {
- if ( in_array( $cmd['name'], array( 'website', 'api-dump' ) ) ) {
+ if ( in_array( $cmd['name'], [ 'website', 'api-dump' ], true ) ) {
unset( $ee['subcommands'][ $k ] );
continue;
}
@@ -89,25 +113,36 @@ public static function get_subcommands(){
/**
* Update the commands data array with new data
+ *
+ * @param object $command Command object.
+ * @param array $commands_data Contain command data.
+ * @param string $parent Parent command string.
+ *
+ * @return void
*/
private static function update_commands_data( $command, &$commands_data, $parent ) {
+
$full = trim( $parent . ' ' . $command->get_name() );
$reflection = new \ReflectionClass( $command );
$repo_url = '';
- if ( 'help' === substr( $full, 0, 4 )
- || 'cli' === substr( $full, 0, 3 ) ) {
+
+ if ( 'help' === substr( $full, 0, 4 ) || 'cli' === substr( $full, 0, 3 ) ) {
$repo_url = 'https://github.com/EasyEngine/handbook';
}
+
if ( $reflection->hasProperty( 'when_invoked' ) ) {
$when_invoked = $reflection->getProperty( 'when_invoked' );
$when_invoked->setAccessible( true );
$closure = $when_invoked->getValue( $command );
$closure_reflection = new \ReflectionFunction( $closure );
$static = $closure_reflection->getStaticVariables();
+
if ( isset( $static['callable'][0] ) ) {
+
$reflection_class = new \ReflectionClass( $static['callable'][0] );
$filename = $reflection_class->getFileName();
preg_match( '#vendor/([^/]+/[^/]+)#', $filename, $matches );
+
if ( ! empty( $matches[1] ) ) {
$repo_url = 'https://github.com/' . $matches[1];
}
@@ -115,14 +150,18 @@ private static function update_commands_data( $command, &$commands_data, $parent
\WP_CLI::error( 'No callable for: ' . var_export( $static, true ) );
}
}
- $commands_data[ $full ] = array(
+
+ $commands_data[ $full ] = [
'repo_url' => $repo_url,
- );
- $len = count( $commands_data );
+ ];
+
+ $len = count( $commands_data );
+
foreach ( $command->get_subcommands() as $subcommand ) {
$sub_full = trim( $full . ' ' . $subcommand->get_name() );
self::update_commands_data( $subcommand, $commands_data, $full );
}
+
if ( isset( $sub_full ) && ! $commands_data[ $full ]['repo_url'] && ! empty( $commands_data[ $sub_full ]['repo_url'] ) ) {
$commands_data[ $full ]['repo_url'] = $commands_data[ $sub_full ]['repo_url'];
}
@@ -130,23 +169,24 @@ private static function update_commands_data( $command, &$commands_data, $parent
/**
* Generate `bin/commands-manifest.json` file from markdown in `commands` directory.
+ *
+ * @return void
*/
private function gen_commands_manifest() {
- $manifest = array();
- $paths = array(
+ $manifest = [];
+ $paths = [
$this->output_dir . '/commands/*.md',
$this->output_dir . '/commands/*/*.md',
$this->output_dir . '/commands/*/*/*.md',
- );
- $commands_data = array();
-
+ ];
+ $commands_data = [];
foreach ( $paths as $path ) {
foreach ( glob( $path ) as $file ) {
$slug = basename( $file, '.md' );
- $cmd_path = str_replace( array( $this->output_dir . '/commands/', '.md' ), '', $file );
+ $cmd_path = str_replace( [ $this->output_dir . '/commands/', '.md' ], '', $file );
$title = '';
$contents = file_get_contents( $file );
if ( preg_match( '/^#\s(.+)/', $contents, $matches ) ) {
@@ -160,13 +200,13 @@ private function gen_commands_manifest() {
$parent = implode( '/', $bits );
}
- $manifest[ $cmd_path ] = array(
+ $manifest[ $cmd_path ] = [
'title' => $title,
'slug' => $slug,
'cmd_path' => $cmd_path,
'parent' => $parent,
'markdown_source' => sprintf( '%s/commands/%s.md', $this->output_dir, $cmd_path ),
- );
+ ];
if ( ! empty( $commands_data[ $title ] ) ) {
$manifest[ $cmd_path ] = array_merge( $manifest[ $cmd_path ], $commands_data[ $title ] );
@@ -183,7 +223,17 @@ private function gen_commands_manifest() {
\WP_CLI::success( "Generated commands-manifest.json of {$count} commands" );
}
- private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $return_str = false ) {
+ /**
+ * Function to generate command pages.
+ *
+ * @param array $cmd Command details.
+ * @param array $parent Parent command.
+ * @param bool $skip_global To skip global variable.
+ * @param bool $return_str To return string.
+ *
+ * @return mixed
+ */
+ private function gen_cmd_pages( $cmd, $parent = [], $skip_global = false, $return_str = false ) {
$parent[] = $cmd['name'];
static $params;
@@ -201,31 +251,33 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
foreach ( $parent as $i => $p ) {
$path .= $p . '/';
- if ( $i < ( count( $parent ) -1 ) ) {
+ if ( $i < ( count( $parent ) - 1 ) ) {
$binding['breadcrumbs'] .= " » [{$p}]({$path})";
} else {
$binding['breadcrumbs'] .= " » {$p}";
}
}
- $binding['has-subcommands'] = isset( $cmd['subcommands'] ) ? array( true ) : false;
+ $binding['has-subcommands'] = isset( $cmd['subcommands'] ) ? [ true ] : false;
if ( $cmd['longdesc'] ) {
$docs = $cmd['longdesc'];
$docs = htmlspecialchars( $docs, ENT_COMPAT, 'UTF-8' );
- // decrease header level
+ // Decrease header level.
$docs = preg_replace( '/^## /m', '### ', $docs );
- // escape `--` so that it doesn't get converted into `—`
+ // Escape `--` so that it doesn't get converted into `—`.
$docs = preg_replace( '/^(\[?)--/m', '\1\--', $docs );
$docs = preg_replace( '/^\s\s--/m', ' \1\--', $docs );
- // Remove wordwrapping from docs
- // Match words, '().,;', and --arg before/after the newline
- $bits = explode( "\n", $docs );
- $in_yaml_doc = $in_code_bloc = false;
+ // Remove wordwrapping from docs.
+ // Match words, '().,;', and --arg before/after the newline.
+ $bits = explode( "\n", $docs );
+ $in_yaml_doc = false;
+ $in_code_bloc = false;
- for ( $i = 0; $i < count( $bits ); $i++ ) {
+ $loop_limit = count( $bits );
+ for ( $i = 0; $i < $loop_limit; $i++ ) {
if ( ! isset( $bits[ $i ] ) || ! isset( $bits[ $i + 1 ] ) ) {
continue;
}
@@ -238,8 +290,9 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
if ( $in_yaml_doc || $in_code_bloc ) {
continue;
}
- if ( preg_match( '#([\w\(\)\.\,\;]|[`]{1})$#', $bits[ $i ] )
- && preg_match( '#^([\w\(\)\.\,\;`]|\\\--[\w]|[`]{1})#', $bits[ $i + 1 ] ) ) {
+ if ( preg_match( '#([\w\(\)\.\,\;]|[`]{1})$#', $bits[ $i ] ) &&
+ preg_match( '#^([\w\(\)\.\,\;`]|\\\--[\w]|[`]{1})#', $bits[ $i + 1 ] )
+ ) {
$bits[ $i ] .= ' ' . $bits[ $i + 1 ];
unset( $bits[ $i + 1 ] );
--$i;
@@ -249,7 +302,7 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
$docs = implode( "\n", $bits );
- // hack to prevent double encoding in code blocks
+ // Hack to prevent double encoding in code blocks.
$docs = preg_replace( '/ < /', ' < ', $docs );
$docs = preg_replace( '/ > /', ' > ', $docs );
$docs = preg_replace( '/ <</', ' <<', $docs );
@@ -261,11 +314,14 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
|:----------------|:-----------------------------|
EOT;
foreach ( $params as $param => $meta ) {
- if ( false === $meta['runtime']
- || empty( $meta['desc'] )
- || ! empty( $meta['deprecated'] ) ) {
+
+ if ( false === $meta['runtime'] ||
+ empty( $meta['desc'] ) ||
+ ! empty( $meta['deprecated'] )
+ ) {
continue;
}
+
$param_arg = '--' . $param;
if ( ! empty( $meta['runtime'] ) && true !== $meta['runtime'] ) {
$param_arg .= $meta['runtime'];
@@ -286,12 +342,12 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
$replace_global = '$1' . PHP_EOL . PHP_EOL . $global_parameters;
}
}
- $docs = preg_replace( '/(#?## GLOBAL PARAMETERS).+/s', $replace_global, $docs );
+ $docs = preg_replace( '/(#?## GLOBAL PARAMETERS).+/s', $replace_global, $docs );
$binding['docs'] = $docs;
}
- $path = $this->output_dir . "/commands/" . $binding['path'];
+ $path = $this->output_dir . '/commands/' . $binding['path'];
if ( ! is_dir( dirname( "$path.md" ) ) ) {
mkdir( dirname( "$path.md" ), 0777, true );
@@ -337,7 +393,7 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
foreach ( $command as $subcommand ) {
if ( $pop['name'] === $subcommand['name'] ) {
$md_doc .= $this->gen_cmd_pages( $subcommand, $parent, false, true );
- $path = $this->output_dir . "/commands/" . implode( '/', $parent ) . "/$name";
+ $path = $this->output_dir . '/commands/' . implode( '/', $parent ) . "/$name";
if ( ! is_dir( dirname( $path ) ) ) {
mkdir( dirname( $path ) );
}
@@ -349,14 +405,22 @@ private function gen_cmd_pages( $cmd, $parent = array(), $skip_global = false, $
}
}
+ /**
+ * Function to render template.
+ *
+ * @param string $path Path of template.
+ * @param string $binding Binding content with template.
+ *
+ * @return string
+ */
private function render( $path, $binding ) {
- $m = new \Mustache_Engine;
+ $m = new \Mustache_Engine();
$template = file_get_contents( EE_MARKDOWN_PLUGIN_DIR . "/templates/$path" );
return $m->render( $template, $binding );
}
}
-if ( defined( 'WP_CLI') && WP_CLI ) {
+if ( defined( 'WP_CLI' ) && WP_CLI ) {
\WP_CLI::add_command( 'ee', '\WPOrg_Cli\Docs' );
-}
\ No newline at end of file
+}
diff --git a/inc/class-handbook.php b/inc/class-handbook.php
index b1a5e0f..b117bad 100755
--- a/inc/class-handbook.php
+++ b/inc/class-handbook.php
@@ -1,66 +1,117 @@
Edit';
+
+ return sprintf(
+ '%s
%s',
+ $title,
+ esc_url( $markdown_source ),
+ esc_url( plugins_url( '/images/github-mark.png', __DIR__ ) ),
+ esc_html__( 'Edit', 'ee-markdown-importer' )
+ );
+
}
+
/**
- * WP-CLI Handbook pages are maintained in the GitHub repo, so the edit
+ * WP-CLI Handbook pages are maintained in the GitHub repo, so the edit
* link should ridirect to there.
+ *
+ * @param string $link Git hub link.
+ * @param int $post_id Post ID.
+ * @param string $context Context using to set link.
+ *
+ * @return string
*/
public static function redirect_edit_link_to_github( $link, $post_id, $context ) {
+
if ( is_admin() ) {
return $link;
}
+
$post = get_post( $post_id );
if ( ! $post ) {
return $link;
}
+
if ( 'handbook' !== $post->post_type ) {
return $link;
}
+
$markdown_source = self::get_markdown_edit_link( $post_id );
if ( ! $markdown_source ) {
return $link;
}
+
if ( 'display' === $context ) {
$markdown_source = esc_url( $markdown_source );
}
+
return $markdown_source;
+
}
+
/**
- * o2 does inline editing, so we also need to remove the class name that it looks for.
+ * O2 does inline editing, so we also need to remove the class name that it looks for.
*
- * o2 obeys the edit_post capability for displaying the edit link, so we also need to manually
+ * O2 obeys the edit_post capability for displaying the edit link, so we also need to manually
* add the edit link if it isn't there - it always redirects to GitHub, so it doesn't need to
* obey the edit_post capability in this instance.
+ *
+ * @param array $actions For which to add edit link.
+ * @param int $post_id Post ID.
+ *
+ * @return array
*/
public static function redirect_o2_edit_link_to_github( $actions, $post_id ) {
+
$post = get_post( $post_id );
+
if ( ! $post ) {
return $actions;
}
+
if ( 'handbook' !== $post->post_type ) {
return $actions;
}
+
$markdown_source = self::get_markdown_edit_link( $post_id );
if ( ! $markdown_source ) {
return $actions;
}
+
/*
* Define our own edit post action for o2.
*
@@ -68,40 +119,57 @@ public static function redirect_o2_edit_link_to_github( $actions, $post_id ) {
* - the 'href' parameter always goes to the GitHub source.
* - the 'o2-edit' class is missing, so inline editing is disabled.
*/
- $edit_action = array(
- 'action' => 'edit',
- 'href' => $markdown_source,
- 'classes' => array( 'edit-post-link' ),
- 'rel' => $post_id,
- 'initialState' => 'default'
- );
+ $edit_action = [
+ 'action' => 'edit',
+ 'href' => $markdown_source,
+ 'classes' => [ 'edit-post-link' ],
+ 'rel' => $post_id,
+ 'initialState' => 'default',
+ ];
+
// Find and replace the existing edit action.
$replaced = false;
- foreach( $actions as &$action ) {
+ foreach ( $actions as &$action ) {
if ( 'edit' === $action['action'] ) {
- $action = $edit_action;
+ $action = $edit_action;
$replaced = true;
break;
}
}
unset( $action );
+
// If there was no edit action replaced, add it in manually.
if ( ! $replaced ) {
$actions[30] = $edit_action;
}
+
return $actions;
}
+
+ /**
+ * Function to get markdown edit link.
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return string
+ */
private static function get_markdown_edit_link( $post_id ) {
+
$markdown_source = Markdown_Import::get_markdown_source( $post_id );
+
if ( is_wp_error( $markdown_source ) ) {
return '';
}
- if ( 'github.com' !== parse_url( $markdown_source, PHP_URL_HOST )
+
+ if ( 'github.com' !== wp_parse_url( $markdown_source, PHP_URL_HOST )
|| false !== stripos( $markdown_source, '/edit/master/' ) ) {
return $markdown_source;
}
+
$markdown_source = str_replace( '/blob/master/', '/edit/master/', $markdown_source );
+
return $markdown_source;
+
}
/**
@@ -109,43 +177,55 @@ private static function get_markdown_edit_link( $post_id ) {
*
* @since 0.1.0
*
- * @param string $content The content
+ * @param string $content The content.
*
- * @return string the content, updated if the content has H1-H6
+ * @return string The content, updated if the content has H1-H6
*/
public static function add_the_anchor_links( $content ) {
- if ( ! is_singular( array( 'commands', 'handbook', 'post' ) ) || '' == $content ) {
+ if ( ! is_singular( [ 'commands', 'handbook', 'post' ] ) || '' === $content ) {
return $content;
}
- $anchors = array();
+
+ $anchors = [];
$doc = new \DOMDocument();
+
// START LibXML error management.
- // Modify state
+ // Modify state.
$libxml_previous_state = libxml_use_internal_errors( true );
$doc->loadHTML( mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' ) );
- // handle errors
+
+ // Handle errors.
libxml_clear_errors();
- // restore
+
+ // Restore.
libxml_use_internal_errors( $libxml_previous_state );
+
// END LibXML error management.
+ foreach ( [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ] as $h ) {
- foreach ( array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ) as $h ) {
$headings = $doc->getElementsByTagName( $h );
+
foreach ( $headings as $heading ) {
+
$a = $doc->createElement( 'a' );
$newnode = $heading->appendChild( $a );
+
$newnode->setAttribute( 'class', 'anchorlink dashicons-before' );
+
// @codingStandardsIgnoreStart
// $heading->nodeValue is from an external libray. Ignore the standard check sinice it doesn't fit the WordPress-Core standard
$node_value = preg_replace( "/[^A-Za-z0-9\- ]/", '', $heading->nodeValue );
$slug = $tmpslug = sanitize_title( $node_value );
// @codingStandardsIgnoreEnd
+
$i = 2;
- while ( false !== in_array( $slug, $anchors ) ) {
+ while ( false !== in_array( $slug, $anchors, true ) ) {
$slug = sprintf( '%s-%d', $tmpslug, $i ++ );
}
+
$anchors[] = $slug;
+
$heading->setAttribute( 'id', $slug );
$newnode->setAttribute( 'href', '#' . $slug );
}
@@ -155,15 +235,23 @@ public static function add_the_anchor_links( $content ) {
}
/**
- * Enable dashicons on the front-end
- * Load style
+ * Enable dashicons on the front-end.
+ * Load style.
*
* @since 0.1.0
+ *
+ * @return void
*/
public static function add_the_anchor_styles() {
if ( is_singular() ) {
wp_enqueue_style( 'dashicons' );
- wp_enqueue_style( 'anchored-header', EE_ANCHOR_CSS . '/anchored-header.css', array( 'dashicons' ) );
+ wp_enqueue_style(
+ 'anchored-header',
+ EE_ANCHOR_CSS . '/anchored-header.css',
+ [ 'dashicons' ],
+ filemtime( EE_MARKDOWN_PLUGIN_DIR . '/css/anchored-header.css' )
+ );
}
}
+
}
diff --git a/inc/class-hb-markdown.php b/inc/class-markdown-hb-import.php
similarity index 63%
rename from inc/class-hb-markdown.php
rename to inc/class-markdown-hb-import.php
index 2dece69..9aa6790 100644
--- a/inc/class-hb-markdown.php
+++ b/inc/class-markdown-hb-import.php
@@ -1,57 +1,128 @@
self::$supported_post_types,
- 'post_status' => 'publish',
- 'posts_per_page' => self::$posts_per_page,
- ) );
+
+ // Fetch all command posts for comparison.
+ $q = new WP_Query(
+ [
+ 'post_type' => self::$supported_post_types,
+ 'post_status' => 'publish',
+ 'posts_per_page' => self::$posts_per_page,
+ ]
+ );
$existing = $q->posts;
$created = 0;
+
foreach ( $manifest as $doc ) {
- // Already exists
- if ( wp_filter_object_list( $existing, array( 'post_name' => $doc['slug'] ) ) ) {
+
+ // Already exists.
+ if ( wp_filter_object_list( $existing, [ 'post_name' => $doc['slug'] ] ) ) {
continue;
}
$post_parent = null;
if ( ! empty( $doc['parent'] ) ) {
- // Find the parent in the existing set
- $parents = wp_filter_object_list( $existing, array( 'post_name' => $doc['parent'] ) );
+
+ // Find the parent in the existing set.
+ $parents = wp_filter_object_list( $existing, [ 'post_name' => $doc['parent'] ] );
+
if ( ! empty( $parents ) ) {
$parent = array_shift( $parents );
} else {
- // Create the parent and add it to the stack
+
+ // Create the parent and add it to the stack.
if ( isset( $manifest[ $doc['parent'] ] ) ) {
+
$parent_doc = $manifest[ $doc['parent'] ];
$parent = self::create_post_from_manifest_doc( $parent_doc );
+
if ( $parent ) {
+
$created++;
$existing[] = $parent;
+
} else {
continue;
}
@@ -68,6 +139,7 @@ public static function action_wporg_cli_hb_manifest_import() {
$existing[] = $post;
}
}
+
if ( class_exists( 'WP_CLI' ) ) {
\WP_CLI::success( "Successfully created {$created} command pages." );
}
@@ -78,38 +150,61 @@ public static function action_wporg_cli_hb_manifest_import() {
/**
* Create a new command page from the manifest document
+ *
+ * @param array $doc Doc details.
+ * @param mixed $post_parent Post parent ID.
+ *
+ * @return mixed
*/
private static function create_post_from_manifest_doc( $doc, $post_parent = null ) {
- $post_data = array(
+
+ $post_data = [
'post_type' => 'handbook',
'post_status' => 'publish',
'post_parent' => $post_parent,
'post_title' => sanitize_text_field( wp_slash( $doc['title'] ) ),
'post_name' => sanitize_title_with_dashes( $doc['slug'] ),
- );
- $post_id = wp_insert_post( $post_data );
+ ];
+
+ // Inserting new post.
+ $post_id = wp_insert_post( $post_data );
+
if ( ! $post_id ) {
return false;
}
+
if ( class_exists( 'WP_CLI' ) ) {
- \WP_CLI::log( "Created post {$post_id} for {$doc['title']}." );
+ \WP_CLI::log( sprintf( 'Created post %d for %s.', $post_id, $doc['title'] ) );
}
+
update_post_meta( $post_id, self::$meta_key, esc_url_raw( $doc['markdown_source'] ) );
+
return get_post( $post_id );
}
+ /**
+ * Function to handle markdown import.
+ *
+ * @return void
+ */
public static function action_wporg_cli_hb_markdown_import() {
- $q = new WP_Query( array(
- 'post_type' => self::$supported_post_types,
- 'post_status' => 'publish',
- 'fields' => 'ids',
- 'posts_per_page' => self::$posts_per_page,
- ) );
+
+ $q = new WP_Query(
+ [
+ 'post_type' => self::$supported_post_types,
+ 'post_status' => 'publish',
+ 'fields' => 'ids',
+ 'posts_per_page' => self::$posts_per_page,
+ ]
+ );
$ids = $q->posts;
$success = 0;
+
foreach ( $ids as $id ) {
$ret = self::update_post_from_markdown_source( $id );
+
if ( class_exists( 'WP_CLI' ) ) {
+
if ( is_wp_error( $ret ) ) {
\WP_CLI::warning( $ret->get_error_message() );
} else {
@@ -118,42 +213,58 @@ public static function action_wporg_cli_hb_markdown_import() {
}
}
}
+
if ( class_exists( 'WP_CLI' ) ) {
$total = count( $ids );
\WP_CLI::success( "Successfully updated {$success} of {$total} command pages." );
}
+
}
/**
* Handle a request to import from the markdown source
*/
public static function action_load_post_php() {
- if ( ! isset( $_GET[ self::$submit_name ] )
- || ! isset( $_GET[ self::$nonce_name ] )
- || ! isset( $_GET['post'] ) ) {
+
+ $submit_btn_name = filter_input( INPUT_GET, self::$submit_name, FILTER_SANITIZE_STRING );
+ $nonce_field_name = filter_input( INPUT_GET, self::$nonce_name, FILTER_SANITIZE_STRING );
+ $post_id = filter_input( INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT );
+
+ if ( empty( $submit_btn_name )
+ || empty( $nonce_field_name )
+ || empty( $post_id ) ) {
return;
}
- $post_id = (int) $_GET['post'];
+
+ $post_id = (int) $post_id;
if ( ! current_user_can( 'edit_post', $post_id )
- || ! wp_verify_nonce( $_GET[ self::$nonce_name ], self::$input_name )
+ || ! wp_verify_nonce( $nonce_field_name, self::$input_name )
|| ! in_array( get_post_type( $post_id ), self::$supported_post_types, true ) ) {
return;
}
+
$response = self::update_post_from_markdown_source( $post_id );
if ( is_wp_error( $response ) ) {
- wp_die( $response->get_error_message() );
+ wp_die( esc_html( $response->get_error_message() ) );
}
+
wp_safe_redirect( get_edit_post_link( $post_id, 'raw' ) );
exit;
}
/**
* Add an input field for specifying Markdown source
+ *
+ * @param Object $post Post Object.
+ *
+ * @return void
*/
public static function action_edit_form_after_title( $post ) {
+
if ( ! in_array( $post->post_type, self::$supported_post_types, true ) ) {
return;
}
+
$markdown_source = get_post_meta( $post->ID, self::$meta_key, true );
?>
+ 'import',
- self::$nonce_name => wp_create_nonce( self::$input_name ),
- ), get_edit_post_link( $post->ID, 'raw' ) );
+ $update_link = add_query_arg(
+ [
+ self::$submit_name => 'import',
+ self::$nonce_name => wp_create_nonce( self::$input_name ),
+ ],
+ get_edit_post_link( $post->ID, 'raw' )
+ );
?>
- Import
+
15 * MINUTE_IN_SECONDS,
'display' => '15 minutes',
- );
+ ];
+
return $schedules;
}
/**
- * Update a post from its Markdown source
+ * Update a post from its Markdown source.
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return mixed
*/
private static function update_post_from_markdown_source( $post_id ) {
+
$markdown_source = self::get_markdown_source( $post_id );
if ( is_wp_error( $markdown_source ) ) {
@@ -218,47 +365,59 @@ private static function update_post_from_markdown_source( $post_id ) {
return new WP_Error( 'missing-jetpack-require-lib', 'jetpack_require_lib() is missing on system.' );
}
- // Transform GitHub repo HTML pages into their raw equivalents
+ // Transform GitHub repo HTML pages into their raw equivalents.
$markdown_source = preg_replace( '#https?://github\.com/([^/]+/[^/]+)/blob/(.+)#', 'https://raw.githubusercontent.com/$1/$2', $markdown_source );
$markdown_source = add_query_arg( 'v', time(), $markdown_source );
$response = wp_remote_get( $markdown_source );
+
if ( is_wp_error( $response ) ) {
return $response;
- } else if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
+ } elseif ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
return new WP_Error( 'invalid-http-code', 'Markdown source returned non-200 http code.' );
}
+
$markdown = wp_remote_retrieve_body( $response );
- // Strip YAML doc from the header
+ // Strip YAML doc from the header.
$markdown = preg_replace( '#^---(.+)---#Us', '', $markdown );
$title = null;
+
if ( preg_match( '/^#\s(.+)/', $markdown, $matches ) ) {
$title = $matches[1];
$markdown = preg_replace( '/^#\s(.+)/', '', $markdown );
}
- // Transform to HTML and save the post
- $parser = new \Parsedown();
+ // Transform to HTML and save the post.
+ $parser = new \Parsedown();
$html = $parser->text( $markdown );
- $post_data = array(
+ $post_data = [
'ID' => $post_id,
'post_content' => wp_filter_post_kses( wp_slash( $html ) ),
- );
+ ];
+
if ( ! is_null( $title ) ) {
$post_data['post_title'] = sanitize_text_field( wp_slash( $title ) );
}
wp_update_post( $post_data );
+
return true;
+
}
/**
* Retrieve the markdown source URL for a given post.
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return mixed
*/
public static function get_markdown_source( $post_id ) {
$markdown_source = get_post_meta( $post_id, self::$meta_key, true );
+
if ( ! $markdown_source ) {
return new WP_Error( 'missing-markdown-source', 'Markdown source is missing for post.' );
}
+
return $markdown_source;
}
-}
\ No newline at end of file
+}
diff --git a/inc/class-markdown.php b/inc/class-markdown-import.php
similarity index 65%
rename from inc/class-markdown.php
rename to inc/class-markdown-import.php
index 611c38f..5422641 100755
--- a/inc/class-markdown.php
+++ b/inc/class-markdown-import.php
@@ -1,31 +1,90 @@
self::$supported_post_types,
- 'post_status' => 'publish',
- 'posts_per_page' => self::$posts_per_page,
- ) );
+
+ // Fetch all command posts for comparison.
+ $q = new WP_Query(
+ [
+ 'post_type' => self::$supported_post_types,
+ 'post_status' => 'publish',
+ 'posts_per_page' => self::$posts_per_page,
+ ]
+ );
$existing = $q->posts;
$created = 0;
@@ -63,18 +125,18 @@ public static function action_wporg_cli_manifest_import() {
foreach ( $manifest as $doc ) {
- // Already exists
- if ( wp_filter_object_list( $existing, array( 'post_title' => sanitize_text_field( wp_slash( $doc['title'] ) ) ) ) ) {
+ // Already exists.
+ if ( wp_filter_object_list( $existing, [ 'post_title' => sanitize_text_field( wp_slash( $doc['title'] ) ) ] ) ) {
continue;
}
$post_parent = null;
if ( ! empty( $doc['parent'] ) ) {
- // Find the parent in the existing set
- $parents = wp_filter_object_list( $existing, array( 'post_title' => sanitize_text_field( wp_slash( $manifest[ $doc['parent'] ]['title'] ) ) ) );
+ // Find the parent in the existing set.
+ $parents = wp_filter_object_list( $existing, [ 'post_title' => sanitize_text_field( wp_slash( $manifest[ $doc['parent'] ]['title'] ) ) ] );
if ( ! empty( $parents ) ) {
$parent = array_shift( $parents );
} else {
- // Create the parent and add it to the stack
+ // Create the parent and add it to the stack.
if ( isset( $manifest[ $doc['parent'] ] ) ) {
$parent_doc = $manifest[ $doc['parent'] ];
$parent = self::create_post_from_manifest_doc( $parent_doc );
@@ -97,110 +159,152 @@ public static function action_wporg_cli_manifest_import() {
}
}
if ( class_exists( 'WP_CLI' ) ) {
- \WP_CLI::success( "Successfully created {$created} command pages." );
+ \WP_CLI::success( sprintf( 'Successfully created %s command pages.', $created ) );
}
// Run markdown importer after creating successful posts.
apply_filters( 'wporg_cli_markdown_import', 'action_wporg_cli_markdown_import' );
- //@todo: remove this after code enhancement.
- apply_filters( 'wporg_cli_hb_all_import', array('WPOrg_Cli\Markdown_Hb_Import', 'action_wporg_cli_hb_manifest_import' ) );
+ // @todo: remove this after code enhancement.
+ apply_filters( 'wporg_cli_hb_all_import', [ 'WPOrg_Cli\Markdown_Hb_Import', 'action_wporg_cli_hb_manifest_import' ] );
}
/**
* Create a new command page from the manifest document
+ *
+ * @param array $doc Command document data.
+ * @param int $post_parent Parent post ID.
+ *
+ * @return mixed
*/
private static function create_post_from_manifest_doc( $doc, $post_parent = null ) {
- $post_data = array(
+ $post_data = [
'post_type' => 'commands',
'post_status' => 'publish',
'post_parent' => $post_parent,
'post_title' => sanitize_text_field( wp_slash( $doc['title'] ) ),
'post_name' => sanitize_title_with_dashes( $doc['slug'] ),
- );
+ ];
$post_id = wp_insert_post( $post_data );
if ( ! $post_id ) {
return false;
}
+
if ( class_exists( 'WP_CLI' ) ) {
\WP_CLI::log( "Created post {$post_id} for {$doc['title']}." );
}
+
update_post_meta( $post_id, self::$meta_key, esc_url_raw( $doc['markdown_source'] ) );
+
return get_post( $post_id );
+
}
+ /**
+ * Function to import markdown.
+ *
+ * @return void
+ */
public static function action_wporg_cli_markdown_import() {
- $q = new WP_Query( array(
- 'post_type' => self::$supported_post_types,
- 'post_status' => 'publish',
- 'fields' => 'ids',
- 'posts_per_page' => self::$posts_per_page,
- ) );
+ $q = new WP_Query(
+ [
+ 'post_type' => self::$supported_post_types,
+ 'post_status' => 'publish',
+ 'fields' => 'ids',
+ 'posts_per_page' => self::$posts_per_page,
+ ]
+ );
$ids = $q->posts;
$success = 0;
+
foreach ( $ids as $id ) {
+
$ret = self::update_post_from_markdown_source( $id );
+
if ( class_exists( 'WP_CLI' ) ) {
+
if ( is_wp_error( $ret ) ) {
\WP_CLI::warning( $ret->get_error_message() );
} else {
- \WP_CLI::log( "Updated {$id} from markdown source" );
+ // translators: %d: post id.
+ \WP_CLI::log( sprintf( esc_html__( 'Updated %d from markdown source', 'ee-markdown-importer' ), $id ) );
$success++;
}
}
}
+
if ( class_exists( 'WP_CLI' ) ) {
$total = count( $ids );
- \WP_CLI::success( "Successfully updated {$success} of {$total} command pages." );
+ // translators: %1$s: Success count, %2$s: Total count.
+ \WP_CLI::success( sprintf( esc_html__( 'Successfully updated %1$s of %2$s command pages.', 'ee-markdown-importer' ), $success, $total ) );
}
+
}
/**
- * Handle a request to import from the markdown source
+ * Handle a request to import from the markdown source.
+ *
+ * @return void
*/
public static function action_load_post_php() {
- if ( ! isset( $_GET[ self::$submit_name ] )
- || ! isset( $_GET[ self::$nonce_name ] )
- || ! isset( $_GET['post'] ) ) {
+
+ $submit_btn_name = filter_input( INPUT_GET, self::$submit_name, FILTER_SANITIZE_STRING );
+ $nonce_field_name = filter_input( INPUT_GET, self::$nonce_name, FILTER_SANITIZE_STRING );
+ $post_id = filter_input( INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT );
+
+ if ( empty( $submit_btn_name )
+ || empty( $nonce_field_name )
+ || empty( $post_id ) ) {
return;
}
- $post_id = (int) $_GET['post'];
+
+ $post_id = (int) $post_id;
if ( ! current_user_can( 'edit_post', $post_id )
- || ! wp_verify_nonce( $_GET[ self::$nonce_name ], self::$input_name )
+ || ! wp_verify_nonce( $nonce_field_name, self::$input_name )
|| ! in_array( get_post_type( $post_id ), self::$supported_post_types, true ) ) {
return;
}
$response = self::update_post_from_markdown_source( $post_id );
if ( is_wp_error( $response ) ) {
- wp_die( $response->get_error_message() );
+ wp_die( esc_html( $response->get_error_message() ) );
}
wp_safe_redirect( get_edit_post_link( $post_id, 'raw' ) );
exit;
}
/**
- * Add an input field for specifying Markdown source
+ * Add an input field for specifying Markdown source.
+ *
+ * @param object $post Post Object.
+ *
+ * @return void
*/
public static function action_edit_form_after_title( $post ) {
+
if ( ! in_array( $post->post_type, self::$supported_post_types, true ) ) {
return;
}
+
$markdown_source = get_post_meta( $post->ID, self::$meta_key, true );
?>
+ 'import',
- self::$nonce_name => wp_create_nonce( self::$input_name ),
- ), get_edit_post_link( $post->ID, 'raw' ) );
+ $update_link = add_query_arg(
+ [
+ self::$submit_name => 'import',
+ self::$nonce_name => wp_create_nonce( self::$input_name ),
+ ],
+ get_edit_post_link( $post->ID, 'raw' )
+ );
?>
- Import
+
15 * MINUTE_IN_SECONDS,
'display' => '15 minutes',
- );
+ ];
return $schedules;
}
/**
* Update a post from its Markdown source
+ *
+ * @param int $post_id Post ID.
+ *
+ * @return mixed
*/
private static function update_post_from_markdown_source( $post_id ) {
$markdown_source = self::get_markdown_source( $post_id );
@@ -251,16 +375,15 @@ private static function update_post_from_markdown_source( $post_id ) {
// Moved to local directory markdown file location.
$markdown_source = preg_replace( '#https?://github\.com/([^/]+/[^/]+)/blob/master/(.+)#', '$2', $markdown_source );
-// $markdown_source = EE_DOC_OUTPUT_DIR . '/' . $markdown_source;
- // Transform GitHub repo HTML pages into their raw equivalents
+ // Transform GitHub repo HTML pages into their raw equivalents.
$response = file_exists( $markdown_source ) ? file_get_contents( $markdown_source ) : '';
if ( empty( $response ) ) {
return new WP_Error( 'empty-file', 'Markdown source is empty. File: ' . $markdown_source );
}
$markdown = $response;
- // Strip YAML doc from the header
+ // Strip YAML doc from the header.
$markdown = preg_replace( '#^---(.+)---#Us', '', $markdown );
$title = null;
if ( preg_match( '/^#\s(.+)/', $markdown, $matches ) ) {
@@ -268,9 +391,9 @@ private static function update_post_from_markdown_source( $post_id ) {
$markdown = preg_replace( '/^#\s(.+)/', '', $markdown );
}
- // Transform to HTML and save the post
+ // Transform to HTML and save the post.
$parser = new \Parsedown();
- $html = $parser->text( $markdown );
+ $html = $parser->text( $markdown );
// TODO: Custom change in generated doc. Need to fix it in data/markdown generation.
$html = str_replace( '
' . esc_html( $issues->get_error_message() ) . '
' . PHP_EOL; + $out .= sprintf( '%s
', esc_html( $issues->get_error_message() ) ) . PHP_EOL; return $out; } + if ( empty( $issues ) ) { - $out .= 'No issues found.
' . PHP_EOL; + $out .= sprintf( '%s
', esc_html__( 'No issues found.', 'ee-markdown-importer' ) ) . PHP_EOL; return $out; } - $repository_issues = array( + + $repository_issues = [ // Root repository should always be first. - 'wp-cli/wp-cli' => array(), - ); + 'wp-cli/wp-cli' => [], + ]; + foreach ( $issues as $issue ) { $repo_name = $issue->repository->full_name; if ( ! isset( $repository_issues[ $repo_name ] ) ) { - $repository_issues[ $repo_name ] = array(); + $repository_issues[ $repo_name ] = []; } $repository_issues[ $repo_name ][] = $issue; } + foreach ( $repository_issues as $repo_name => $issues ) { + if ( empty( $issues ) ) { continue; } - $out .= '' . esc_html( $repos->get_error_message() ) . '
'; + $out .= sprintf( '%s
', esc_html( $repos->get_error_message() ) ); return $out; } - $repo_list = array(); - foreach( $repos as $repo ) { + + $repo_list = []; + + foreach ( $repos as $repo ) { if ( ! preg_match( '#^wp-cli/.+-command$#', $repo->full_name ) ) { continue; } $repo_list[] = $repo->full_name; } + sort( $repo_list ); array_unshift( $repo_list, 'wp-cli/wp-cli' ); + $out .= 'Status | ' . PHP_EOL; $out .= '|||
---|---|---|---|
' . esc_html( $repo_name ) . ' | ' . PHP_EOL; - // Overview + // Overview. $out .= '
| ' . PHP_EOL;
- // Status
- // dist-archive primarily uses Circle
+
+ // Status.
+ // Command dist-archive primarily uses Circle.
if ( 'wp-cli/dist-archive-command' === $repo_name ) {
$status_image = sprintf( 'https://circleci.com/gh/%s/tree/master.svg?style=svg', $repo_name );
- $status_link = sprintf( 'https://circleci.com/gh/%s/tree/master', $repo_name );
+ $status_link = sprintf( 'https://circleci.com/gh/%s/tree/master', $repo_name );
} else {
$status_image = sprintf( 'https://travis-ci.org/%s.svg?branch=master', $repo_name );
- $status_link = sprintf( 'https://travis-ci.org/%s/branches', $repo_name );
+ $status_link = sprintf( 'https://travis-ci.org/%s/branches', $repo_name );
}
- $out .= '