diff --git a/assets/js/editor-podcast.js b/assets/js/editor-podcast.js new file mode 100644 index 0000000..15d14a3 --- /dev/null +++ b/assets/js/editor-podcast.js @@ -0,0 +1,139 @@ +( function ( factory ) { + if ( typeof module === 'object' && module.exports ) { + module.exports = factory(); + } else { + factory().initialize( window.wp ); + } +} )( function () { + 'use strict'; + + function participantsFromText( value ) { + return String( value || '' ) + .split( /\r?\n/ ) + .map( function ( name ) { + return name.trim(); + } ) + .filter( Boolean ); + } + + function participantsToText( value ) { + return Array.isArray( value ) ? value.join( '\n' ) : ''; + } + + function updateMeta( editPost, currentMeta, key, value ) { + if ( typeof editPost !== 'function' ) { + return; + } + + editPost( { meta: { ...( currentMeta || {} ), [ key ]: value } } ); + } + + function hasRequiredGlobals( wp ) { + return Boolean( + wp && + wp.components && + wp.components.TextControl && + wp.components.TextareaControl && + wp.data && + typeof wp.data.select === 'function' && + typeof wp.data.dispatch === 'function' && + typeof wp.data.useDispatch === 'function' && + typeof wp.data.useSelect === 'function' && + wp.editPost && + wp.editPost.PluginDocumentSettingPanel && + wp.element && + typeof wp.element.createElement === 'function' && + wp.plugins && + typeof wp.plugins.registerPlugin === 'function', + ); + } + + function initialize( wp ) { + if ( ! hasRequiredGlobals( wp ) ) { + return false; + } + + const editor = wp.data.select( 'core/editor' ); + if ( ! editor || editor.getCurrentPostType() !== 'post' ) { + return false; + } + + function PodcastPanel() { + const editorState = wp.data.useSelect( function ( select ) { + const currentEditor = select( 'core/editor' ); + const core = select( 'core' ); + if ( ! currentEditor || ! core || typeof core.getEntityRecord !== 'function' ) { + return null; + } + + const topicIds = currentEditor.getEditedPostAttribute( 'topic' ); + return { + meta: currentEditor.getEditedPostAttribute( 'meta' ) || {}, + postType: currentEditor.getCurrentPostType(), + topic: + Array.isArray( topicIds ) && topicIds.length === 1 + ? core.getEntityRecord( 'taxonomy', 'chrnx_topic', topicIds[ 0 ] ) + : null, + }; + }, [] ); + const editorDispatch = wp.data.useDispatch( 'core/editor' ); + if ( ! editorState || editorState.postType !== 'post' || ! editorDispatch?.editPost ) { + return null; + } + + if ( ! editorState.topic || editorState.topic.slug !== 'podcasts' ) { + return null; + } + + const meta = editorState.meta; + const setMeta = function ( key, value ) { + updateMeta( editorDispatch.editPost, meta, key, value ); + }; + + return wp.element.createElement( + wp.editPost.PluginDocumentSettingPanel, + { name: 'chrnx-podcast', title: 'Podcast episode' }, + wp.element.createElement( wp.components.TextControl, { + label: 'Episode number', + type: 'number', + min: 0, + value: meta.chrnx_episode_number ?? '', + onChange( value ) { + const number = Number.parseInt( value, 10 ); + setMeta( + 'chrnx_episode_number', + Number.isInteger( number ) ? Math.max( 0, number ) : 0, + ); + }, + } ), + wp.element.createElement( wp.components.TextControl, { + label: 'Duration', + value: meta.chrnx_episode_duration || '', + onChange( value ) { + setMeta( 'chrnx_episode_duration', value ); + }, + } ), + wp.element.createElement( wp.components.TextareaControl, { + label: 'Participants (one per line)', + value: participantsToText( meta.chrnx_episode_participants ), + onChange( value ) { + setMeta( 'chrnx_episode_participants', participantsFromText( value ) ); + }, + } ), + wp.element.createElement( wp.components.TextControl, { + label: 'Canonical episode URL', + type: 'url', + value: meta.canonical_episode_url || '', + onChange( value ) { + setMeta( 'canonical_episode_url', value ); + }, + } ), + ); + } + + wp.plugins.registerPlugin( 'chrnx-podcast-meta', { render: PodcastPanel } ); + return true; + } + + return { initialize, participantsFromText, participantsToText, updateMeta }; +} ); diff --git a/assets/js/editor-taxonomies.js b/assets/js/editor-taxonomies.js new file mode 100644 index 0000000..7484d77 --- /dev/null +++ b/assets/js/editor-taxonomies.js @@ -0,0 +1,138 @@ +( function ( factory ) { + if ( typeof module === 'object' && module.exports ) { + module.exports = factory(); + } else { + factory().initialize( window.wp ); + } +} )( function () { + 'use strict'; + + const taxonomies = [ + { name: 'chrnx_topic', restBase: 'topic', title: 'Topic' }, + { name: 'chrnx_language', restBase: 'language', title: 'Language' }, + { name: 'chrnx_show', restBase: 'show', title: 'Show' }, + ]; + + function orderTerms( terms ) { + if ( ! Array.isArray( terms ) ) { + return []; + } + + return terms.slice().sort( function ( left, right ) { + const byName = String( left.name || '' ).localeCompare( String( right.name || '' ) ); + return byName || Number( left.id ) - Number( right.id ); + } ); + } + + function writeSelection( editPost, restBase, value ) { + if ( typeof editPost !== 'function' ) { + return; + } + + const termId = Number.parseInt( value, 10 ); + editPost( { [ restBase ]: Number.isInteger( termId ) ? [ termId ] : [] } ); + } + + function hasRequiredGlobals( wp ) { + return Boolean( + wp && + wp.components && + wp.components.RadioControl && + wp.data && + typeof wp.data.select === 'function' && + typeof wp.data.dispatch === 'function' && + typeof wp.data.useDispatch === 'function' && + typeof wp.data.useSelect === 'function' && + wp.editPost && + wp.editPost.PluginDocumentSettingPanel && + wp.element && + typeof wp.element.createElement === 'function' && + wp.plugins && + typeof wp.plugins.registerPlugin === 'function', + ); + } + + function initialize( wp ) { + if ( ! hasRequiredGlobals( wp ) ) { + return false; + } + + const editor = wp.data.select( 'core/editor' ); + if ( ! editor || editor.getCurrentPostType() !== 'post' ) { + return false; + } + + const panelDispatch = wp.data.dispatch( 'core/edit-post' ); + if ( panelDispatch && typeof panelDispatch.removeEditorPanel === 'function' ) { + taxonomies.forEach( function ( taxonomy ) { + panelDispatch.removeEditorPanel( 'taxonomy-panel-' + taxonomy.name ); + } ); + } + + function EditorialTaxonomyPanels() { + const editorState = wp.data.useSelect( function ( select ) { + const currentEditor = select( 'core/editor' ); + const core = select( 'core' ); + if ( ! currentEditor || ! core || typeof core.getEntityRecords !== 'function' ) { + return null; + } + + return { + postType: currentEditor.getCurrentPostType(), + taxonomies: taxonomies.map( function ( taxonomy ) { + return { + selected: currentEditor.getEditedPostAttribute( taxonomy.restBase ), + terms: core.getEntityRecords( 'taxonomy', taxonomy.name, { + per_page: -1, + orderby: 'name', + order: 'asc', + } ), + }; + } ), + }; + }, [] ); + const editorDispatch = wp.data.useDispatch( 'core/editor' ); + if ( ! editorState || editorState.postType !== 'post' || ! editorDispatch?.editPost ) { + return null; + } + + const panels = taxonomies.map( function ( taxonomy, index ) { + const terms = orderTerms( editorState.taxonomies[ index ].terms ); + if ( ! terms.length ) { + return null; + } + + const selected = editorState.taxonomies[ index ].selected; + const options = [ { label: 'Not set', value: '' } ].concat( + terms.map( function ( term ) { + return { label: term.name, value: String( term.id ) }; + } ), + ); + + return wp.element.createElement( + wp.editPost.PluginDocumentSettingPanel, + { + key: taxonomy.name, + name: 'chrnx-' + taxonomy.restBase, + title: taxonomy.title, + }, + wp.element.createElement( wp.components.RadioControl, { + label: taxonomy.title, + selected: Array.isArray( selected ) && selected.length ? String( selected[ 0 ] ) : '', + options, + onChange( value ) { + writeSelection( editorDispatch.editPost, taxonomy.restBase, value ); + }, + } ), + ); + } ); + + return wp.element.createElement( 'div', null, ...panels.filter( Boolean ) ); + } + + wp.plugins.registerPlugin( 'chrnx-editorial-taxonomies', { render: EditorialTaxonomyPanels } ); + return true; + } + + return { initialize, orderTerms, writeSelection }; +} ); diff --git a/inc/editor.php b/inc/editor.php new file mode 100644 index 0000000..fdabc8c --- /dev/null +++ b/inc/editor.php @@ -0,0 +1,33 @@ +base || 'post' !== $screen->post_type || ! $screen->is_block_editor() ) { + return; + } + + wp_enqueue_script( + 'chrnx-editor-taxonomies', + get_theme_file_uri( 'assets/js/editor-taxonomies.js' ), + array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-plugins' ), + CHRNX_VERSION, + true + ); + + wp_enqueue_script( + 'chrnx-editor-podcast', + get_theme_file_uri( 'assets/js/editor-podcast.js' ), + array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-plugins' ), + CHRNX_VERSION, + true + ); +} +add_action( 'enqueue_block_editor_assets', 'chrnx_enqueue_editor_assets' ); diff --git a/inc/podcast-meta.php b/inc/podcast-meta.php new file mode 100644 index 0000000..2015863 --- /dev/null +++ b/inc/podcast-meta.php @@ -0,0 +1,149 @@ + array( + 'type' => 'integer', + 'sanitize_callback' => 'chrnx_sanitize_episode_number', + 'schema' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + ), + 'chrnx_episode_duration' => array( + 'type' => 'string', + 'sanitize_callback' => 'chrnx_sanitize_episode_duration', + 'schema' => array( 'type' => 'string' ), + ), + 'chrnx_episode_participants' => array( + 'type' => 'array', + 'sanitize_callback' => 'chrnx_sanitize_episode_participants', + 'schema' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + ), + 'canonical_episode_url' => array( + 'type' => 'string', + 'sanitize_callback' => 'chrnx_sanitize_canonical_episode_url', + 'schema' => array( + 'type' => 'string', + 'format' => 'uri', + ), + ), + ); + + foreach ( $definitions as $meta_key => $definition ) { + register_post_meta( + 'post', + $meta_key, + array( + 'type' => $definition['type'], + 'single' => true, + 'show_in_rest' => array( 'schema' => $definition['schema'] ), + 'sanitize_callback' => $definition['sanitize_callback'], + 'auth_callback' => 'chrnx_auth_podcast_meta', + ) + ); + } +} +add_action( 'init', 'chrnx_register_podcast_meta' ); diff --git a/inc/taxonomies.php b/inc/taxonomies.php new file mode 100644 index 0000000..98cf178 --- /dev/null +++ b/inc/taxonomies.php @@ -0,0 +1,172 @@ +> Taxonomy definitions. + */ +function chrnx_get_editorial_taxonomies() { + return array( + 'chrnx_topic' => array( + 'singular' => 'Topic', + 'plural' => 'Topics', + 'rest_base' => 'topic', + 'terms' => array( + 'research' => 'Research', + 'code' => 'Code', + 'literature' => 'Literature', + 'music' => 'Music', + 'podcasts' => 'Podcasts', + 'life' => 'Life', + 'gaming' => 'Gaming', + ), + ), + 'chrnx_language' => array( + 'singular' => 'Language', + 'plural' => 'Languages', + 'rest_base' => 'language', + 'terms' => array( + 'en' => 'English', + 'es' => 'Español', + ), + ), + 'chrnx_show' => array( + 'singular' => 'Show', + 'plural' => 'Shows', + 'rest_base' => 'show', + 'terms' => array( + 'silicon-ranch' => 'Silicon Ranch', + ), + ), + ); +} + +/** + * Register one editorial taxonomy with the shared contract. + * + * @param string $taxonomy_name Taxonomy name. + * @param array $definition Taxonomy definition. + */ +function chrnx_register_editorial_taxonomy( $taxonomy_name, $definition ) { + register_taxonomy( + $taxonomy_name, + array( 'post' ), + array( + 'labels' => array( + 'name' => $definition['plural'], + 'singular_name' => $definition['singular'], + ), + 'public' => true, + 'hierarchical' => false, + 'show_in_rest' => true, + 'rest_base' => $definition['rest_base'], + 'rewrite' => array( 'slug' => $definition['rest_base'] ), + 'show_admin_column' => true, + ) + ); +} + +/** + * Register all editorial taxonomies. + */ +function chrnx_register_editorial_taxonomies() { + foreach ( chrnx_get_editorial_taxonomies() as $taxonomy_name => $definition ) { + chrnx_register_editorial_taxonomy( $taxonomy_name, $definition ); + } +} +add_action( 'init', 'chrnx_register_editorial_taxonomies' ); + +/** + * Insert initial editorial terms when the theme is activated. + */ +function chrnx_seed_editorial_terms() { + foreach ( chrnx_get_editorial_taxonomies() as $taxonomy_name => $definition ) { + if ( ! taxonomy_exists( $taxonomy_name ) ) { + chrnx_register_editorial_taxonomy( $taxonomy_name, $definition ); + } + + foreach ( $definition['terms'] as $slug => $name ) { + if ( ! term_exists( $slug, $taxonomy_name ) ) { + wp_insert_term( $name, $taxonomy_name, array( 'slug' => $slug ) ); + } + } + } +} +add_action( 'after_switch_theme', 'chrnx_seed_editorial_terms' ); + +/** + * Add or read request-local normalization notices. + * + * @param string $taxonomy_name Optional taxonomy name to add. + * @return string[] Taxonomies normalized during this request. + */ +function chrnx_editorial_taxonomy_notices( $taxonomy_name = '' ) { + static $notices = array(); + $supported = array_keys( chrnx_get_editorial_taxonomies() ); + + if ( in_array( $taxonomy_name, $supported, true ) ) { + $notices[ $taxonomy_name ] = $taxonomy_name; + } + + return array_values( $notices ); +} + +/** + * Enforce one editorial term per taxonomy. + * + * @param int $object_id Object ID. + * @param mixed $terms Assigned terms. + * @param int[] $term_taxonomy_ids Term taxonomy IDs. + * @param string $taxonomy_name Taxonomy name. + */ +function chrnx_normalize_editorial_taxonomy_terms( $object_id, $terms, $term_taxonomy_ids, $taxonomy_name ) { + static $normalizing = array(); + $supported = array_keys( chrnx_get_editorial_taxonomies() ); + + if ( ! in_array( $taxonomy_name, $supported, true ) || ! empty( $normalizing[ $taxonomy_name ] ) ) { + return; + } + + $term_ids = wp_get_object_terms( $object_id, $taxonomy_name, array( 'fields' => 'ids' ) ); + if ( is_wp_error( $term_ids ) || count( $term_ids ) <= 1 ) { + return; + } + + $term_ids = array_map( 'absint', $term_ids ); + sort( $term_ids, SORT_NUMERIC ); + + $normalizing[ $taxonomy_name ] = true; + wp_set_object_terms( $object_id, array( $term_ids[0] ), $taxonomy_name, false ); + unset( $normalizing[ $taxonomy_name ] ); + + chrnx_editorial_taxonomy_notices( $taxonomy_name ); +} +add_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10, 4 ); + +/** + * Display a concise request-local normalization notice. + */ +function chrnx_editorial_taxonomy_admin_notice() { + $definitions = chrnx_get_editorial_taxonomies(); + + foreach ( chrnx_editorial_taxonomy_notices() as $taxonomy_name ) { + if ( ! isset( $definitions[ $taxonomy_name ] ) ) { + continue; + } + + $message = sprintf( + /* translators: %s: taxonomy singular label. */ + __( '%s supports one value. The lowest existing term was kept.', 'chrnx' ), + $definitions[ $taxonomy_name ]['singular'] + ); + ?> +

+ mapper( wp.data.select ) ); + const useDispatch = jest.fn( ( store ) => wp.data.dispatch( store ) ); + const state = { + meta: { unrelated: 'keep', chrnx_episode_number: 4 }, + topic: [ 12 ], + }; + const wp = { + components: { TextControl: 'TextControl', TextareaControl: 'TextareaControl' }, + data: { + select: ( store ) => { + if ( store === 'core/editor' ) { + return { + getCurrentPostType: () => 'post', + getEditedPostAttribute: ( key ) => state[ key ], + }; + } + return { + getEntityRecord: () => ( topicSlug ? { id: 12, slug: topicSlug } : undefined ), + }; + }, + dispatch: () => ( { editPost } ), + useDispatch, + useSelect, + }, + editPost: { PluginDocumentSettingPanel: 'PluginDocumentSettingPanel' }, + element: { + createElement: ( type, props, ...children ) => ( { type, props: props || {}, children } ), + }, + plugins: { registerPlugin }, + }; + return { wp, editPost, registerPlugin, state, useSelect }; +} + +describe( 'podcast editor helpers', () => { + test( 'converts participant lines to an ordered trimmed transport array', () => { + const helpers = require( modulePath ); + expect( helpers.participantsFromText( ' Ada Example\n\n Bob Example \n' ) ).toEqual( [ + 'Ada Example', + 'Bob Example', + ] ); + expect( helpers.participantsToText( [ 'Ada Example', 'Bob Example' ] ) ).toBe( + 'Ada Example\nBob Example', + ); + } ); + + test( 'updates one meta key while preserving unrelated metadata', () => { + const helpers = require( modulePath ); + const editPost = jest.fn(); + helpers.updateMeta( + editPost, + { unrelated: 'keep', chrnx_episode_number: 4 }, + 'chrnx_episode_duration', + '1:18:23', + ); + expect( editPost ).toHaveBeenCalledWith( { + meta: { unrelated: 'keep', chrnx_episode_number: 4, chrnx_episode_duration: '1:18:23' }, + } ); + } ); + + test( 'renders four controls only for the exact podcasts topic', () => { + const helpers = require( modulePath ); + const { wp, registerPlugin, useSelect } = createWp( 'podcasts' ); + expect( helpers.initialize( wp ) ).toBe( true ); + const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render(); + expect( useSelect ).toHaveBeenCalled(); + expect( tree.type ).toBe( 'PluginDocumentSettingPanel' ); + const controls = flatten( tree ).filter( + ( node ) => node.type === 'TextControl' || node.type === 'TextareaControl', + ); + expect( controls ).toHaveLength( 4 ); + expect( controls.map( ( control ) => control.props.label ) ).toEqual( [ + 'Episode number', + 'Duration', + 'Participants (one per line)', + 'Canonical episode URL', + ] ); + expect( JSON.stringify( tree ) ).not.toContain( 'embed' ); + + const nonPodcast = createWp( 'research' ); + helpers.initialize( nonPodcast.wp ); + expect( nonPodcast.registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull(); + } ); + + test( 'gracefully handles missing globals, post data, meta, and unresolved topic terms', () => { + const helpers = require( modulePath ); + expect( helpers.initialize() ).toBe( false ); + expect( helpers.initialize( {} ) ).toBe( false ); + const unresolved = createWp( null ); + expect( () => helpers.initialize( unresolved.wp ) ).not.toThrow(); + expect( unresolved.registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull(); + } ); +} ); diff --git a/tests/js/editor-taxonomies.test.js b/tests/js/editor-taxonomies.test.js new file mode 100644 index 0000000..b6ddbc6 --- /dev/null +++ b/tests/js/editor-taxonomies.test.js @@ -0,0 +1,102 @@ +const modulePath = '../../assets/js/editor-taxonomies.js'; + +function createWp( overrides = {} ) { + const editPost = jest.fn(); + const removeEditorPanel = jest.fn(); + const registerPlugin = jest.fn(); + const useSelect = jest.fn( ( mapper ) => mapper( wp.data.select ) ); + const useDispatch = jest.fn( ( store ) => wp.data.dispatch( store ) ); + const terms = { + chrnx_topic: [ + { id: 9, name: 'Zulu' }, + { id: 3, name: 'Alpha' }, + ], + chrnx_language: [ { id: 4, name: 'English' } ], + chrnx_show: [ { id: 7, name: 'Silicon Ranch' } ], + }; + const attributes = { type: 'post', topic: [ 3 ], language: [], show: [] }; + const wp = { + components: { RadioControl: 'RadioControl' }, + compose: { + compose: + ( ...funcs ) => + ( component ) => + funcs.reduceRight( ( value, func ) => func( value ), component ), + }, + data: { + select: ( store ) => { + if ( store === 'core/editor' ) { + return { + getCurrentPostType: () => attributes.type, + getEditedPostAttribute: ( key ) => attributes[ key ], + }; + } + return { getEntityRecords: ( _kind, name ) => terms[ name ] }; + }, + dispatch: ( store ) => ( store === 'core/editor' ? { editPost } : {} ), + useDispatch, + useSelect, + withDispatch: ( mapper ) => ( Component ) => ( props ) => + Component( { ...props, ...mapper( () => ( { editPost } ), props ) } ), + withSelect: ( mapper ) => ( Component ) => ( props ) => + Component( { ...props, ...mapper( wp.data.select, props ) } ), + }, + editPost: { PluginDocumentSettingPanel: 'PluginDocumentSettingPanel' }, + element: { + createElement: ( type, props, ...children ) => ( { type, props: props || {}, children } ), + }, + plugins: { registerPlugin }, + ...overrides, + }; + return { wp, editPost, removeEditorPanel, registerPlugin, attributes, terms, useSelect }; +} + +describe( 'editor taxonomy helpers', () => { + test( 'orders terms stably and writes one selected value or Not set', () => { + const helpers = require( modulePath ); + const editPost = jest.fn(); + expect( + helpers + .orderTerms( [ + { id: 9, name: 'Zulu' }, + { id: 3, name: 'Alpha' }, + ] ) + .map( ( term ) => term.id ), + ).toEqual( [ 3, 9 ] ); + helpers.writeSelection( editPost, 'topic', '9' ); + expect( editPost ).toHaveBeenLastCalledWith( { topic: [ 9 ] } ); + helpers.writeSelection( editPost, 'topic', '' ); + expect( editPost ).toHaveBeenLastCalledWith( { topic: [] } ); + } ); + + test( 'removes native panels and registers three radio setting panels', () => { + const helpers = require( modulePath ); + const { wp, removeEditorPanel, registerPlugin, useSelect } = createWp(); + wp.data.dispatch = ( store ) => + store === 'core/edit-post' ? { removeEditorPanel } : { editPost: jest.fn() }; + + expect( helpers.initialize( wp ) ).toBe( true ); + expect( removeEditorPanel ).toHaveBeenCalledTimes( 3 ); + expect( registerPlugin ).toHaveBeenCalledTimes( 1 ); + const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render(); + expect( useSelect ).toHaveBeenCalled(); + expect( tree.children ).toHaveLength( 3 ); + tree.children.forEach( ( panel ) => { + expect( panel.type ).toBe( 'PluginDocumentSettingPanel' ); + expect( panel.children[ 0 ].type ).toBe( 'RadioControl' ); + } ); + } ); + + test( 'does nothing safely outside post editors or without usable globals or terms', () => { + const helpers = require( modulePath ); + expect( helpers.initialize() ).toBe( false ); + expect( helpers.initialize( {} ) ).toBe( false ); + const { wp, registerPlugin, attributes, terms } = createWp(); + attributes.type = 'page'; + expect( helpers.initialize( wp ) ).toBe( false ); + expect( registerPlugin ).not.toHaveBeenCalled(); + attributes.type = 'post'; + terms.chrnx_topic = undefined; + expect( () => helpers.initialize( wp ) ).not.toThrow(); + } ); +} ); diff --git a/tests/php/PodcastMetaTest.php b/tests/php/PodcastMetaTest.php new file mode 100644 index 0000000..e97a7d4 --- /dev/null +++ b/tests/php/PodcastMetaTest.php @@ -0,0 +1,124 @@ +assertSame( 'integer', $registered['chrnx_episode_number']['type'] ); + $this->assertSame( 0, $registered['chrnx_episode_number']['show_in_rest']['schema']['minimum'] ); + $this->assertSame( 'string', $registered['chrnx_episode_duration']['show_in_rest']['schema']['type'] ); + $this->assertSame( + array( 'type' => 'string' ), + $registered['chrnx_episode_participants']['show_in_rest']['schema']['items'] + ); + $this->assertSame( 'array', $registered['chrnx_episode_participants']['show_in_rest']['schema']['type'] ); + $this->assertSame( 'string', $registered['canonical_episode_url']['show_in_rest']['schema']['type'] ); + $this->assertArrayNotHasKey( 'chrnx_buzzsprout_embed', $registered ); + $this->assertArrayNotHasKey( 'chrnx_episode_player', $registered ); + + $podcast_keys = array( 'chrnx_episode_number', 'chrnx_episode_duration', 'chrnx_episode_participants', 'canonical_episode_url' ); + foreach ( $podcast_keys as $key ) { + $this->assertTrue( $registered[ $key ]['single'] ); + $this->assertIsCallable( $registered[ $key ]['sanitize_callback'] ); + $this->assertIsCallable( $registered[ $key ]['auth_callback'] ); + } + $page_meta = get_registered_meta_keys( 'post', 'page' ); + foreach ( $podcast_keys as $key ) { + $this->assertArrayNotHasKey( $key, $page_meta ); + } + } + + /** + * Episode numbers are nonnegative integers. + */ + public function test_episode_number_sanitizer_clamps_to_zero() { + $this->assertSame( 12, chrnx_sanitize_episode_number( '12' ) ); + $this->assertSame( 0, chrnx_sanitize_episode_number( '-9' ) ); + $this->assertSame( 0, chrnx_sanitize_episode_number( 'unsafe' ) ); + } + + /** + * Duration accepts display time only and rejects markup or malformed values. + */ + public function test_episode_duration_sanitizer_rejects_unsafe_or_malformed_values() { + $this->assertSame( '1:18:23', chrnx_sanitize_episode_duration( ' 1:18:23 ' ) ); + $this->assertSame( '42:05', chrnx_sanitize_episode_duration( '42:05' ) ); + $this->assertSame( '', chrnx_sanitize_episode_duration( '1:18:23' ) ); + $this->assertSame( '', chrnx_sanitize_episode_duration( '1:99:23' ) ); + $this->assertSame( '', chrnx_sanitize_episode_duration( 'soon' ) ); + } + + /** + * Participant order is preserved while unsafe and empty names are removed. + */ + public function test_participants_are_sanitized_trimmed_and_ordered() { + $this->assertSame( + array( 'Ada Example', 'Bob & Sons' ), + chrnx_sanitize_episode_participants( array( ' Ada Example ', '', 'Bob & Sons', ' ' ) ) + ); + $this->assertSame( array(), chrnx_sanitize_episode_participants( 'Ada Example' ) ); + } + + /** + * Canonical URLs allow HTTPS only. + */ + public function test_canonical_url_sanitizer_accepts_only_https() { + $this->assertSame( 'https://example.test/episode?ref=1', chrnx_sanitize_canonical_episode_url( ' https://example.test/episode?ref=1 ' ) ); + $this->assertSame( '', chrnx_sanitize_canonical_episode_url( 'http://example.test/episode' ) ); + $this->assertSame( '', chrnx_sanitize_canonical_episode_url( 'javascript:alert(1)' ) ); + $this->assertSame( '', chrnx_sanitize_canonical_episode_url( 'not a url' ) ); + } + + /** + * Authorization follows edit_post for the actual post. + */ + public function test_meta_authorization_requires_edit_post_capability() { + $author_id = self::factory()->user->create( array( 'role' => 'author' ) ); + $other_id = self::factory()->user->create( array( 'role' => 'author' ) ); + $post_id = self::factory()->post->create( array( 'post_author' => $author_id ) ); + $callback = get_registered_meta_keys( 'post', 'post' )['chrnx_episode_number']['auth_callback']; + + wp_set_current_user( $author_id ); + $this->assertTrue( (bool) call_user_func( $callback, false, 'chrnx_episode_number', $post_id ) ); + + wp_set_current_user( $other_id ); + $this->assertFalse( (bool) call_user_func( $callback, false, 'chrnx_episode_number', $post_id ) ); + } + + /** + * Stored metadata is sanitized and independent of topic assignment. + */ + public function test_metadata_persists_without_assigning_a_topic() { + $post_id = self::factory()->post->create(); + + update_post_meta( $post_id, 'chrnx_episode_number', -3 ); + update_post_meta( $post_id, 'chrnx_episode_duration', '1:02' ); + update_post_meta( $post_id, 'chrnx_episode_participants', array( ' First ', 'Second' ) ); + update_post_meta( $post_id, 'canonical_episode_url', 'http://example.test' ); + + $this->assertSame( '0', get_post_meta( $post_id, 'chrnx_episode_number', true ) ); + $this->assertSame( '', get_post_meta( $post_id, 'chrnx_episode_duration', true ) ); + $this->assertSame( array( 'First', 'Second' ), get_post_meta( $post_id, 'chrnx_episode_participants', true ) ); + $this->assertSame( '', get_post_meta( $post_id, 'canonical_episode_url', true ) ); + $this->assertSame( array(), wp_get_object_terms( $post_id, 'chrnx_topic', array( 'fields' => 'ids' ) ) ); + } +} diff --git a/tests/php/TaxonomiesTest.php b/tests/php/TaxonomiesTest.php new file mode 100644 index 0000000..87b2d15 --- /dev/null +++ b/tests/php/TaxonomiesTest.php @@ -0,0 +1,165 @@ +> + */ + private $definitions; + + /** + * Register taxonomies before each test. + */ + public function set_up() { + parent::set_up(); + do_action( 'init' ); + $this->definitions = array( + 'chrnx_topic' => array( + 'rest_base' => 'topic', + 'terms' => array( + 'research' => 'Research', + 'code' => 'Code', + 'literature' => 'Literature', + 'music' => 'Music', + 'podcasts' => 'Podcasts', + 'life' => 'Life', + 'gaming' => 'Gaming', + ), + ), + 'chrnx_language' => array( + 'rest_base' => 'language', + 'terms' => array( + 'en' => 'English', + 'es' => 'Español', + ), + ), + 'chrnx_show' => array( + 'rest_base' => 'show', + 'terms' => array( + 'silicon-ranch' => 'Silicon Ranch', + ), + ), + ); + } + + /** + * Taxonomies are post-only, public, REST-visible, and stable. + */ + public function test_taxonomies_have_stable_public_post_only_registration() { + $this->assertTrue( function_exists( 'chrnx_register_editorial_taxonomy' ) ); + $this->assertNotFalse( has_action( 'init', 'chrnx_register_editorial_taxonomies' ) ); + + foreach ( $this->definitions as $taxonomy_name => $definition ) { + $taxonomy = get_taxonomy( $taxonomy_name ); + + $this->assertInstanceOf( WP_Taxonomy::class, $taxonomy ); + $this->assertSame( array( 'post' ), $taxonomy->object_type ); + $this->assertTrue( $taxonomy->public ); + $this->assertTrue( $taxonomy->show_in_rest ); + $this->assertFalse( $taxonomy->hierarchical ); + $this->assertSame( $definition['rest_base'], $taxonomy->rest_base ); + $this->assertSame( $definition['rest_base'], $taxonomy->rewrite['slug'] ); + } + } + + /** + * The source definitions remain exact and explicit. + */ + public function test_taxonomy_definitions_include_exact_initial_terms() { + $this->assertTrue( function_exists( 'chrnx_get_editorial_taxonomies' ) ); + $actual = chrnx_get_editorial_taxonomies(); + + foreach ( $this->definitions as $taxonomy_name => $definition ) { + $this->assertSame( $definition['terms'], $actual[ $taxonomy_name ]['terms'] ); + } + } + + /** + * Terms are seeded only by theme activation and only when absent. + */ + public function test_terms_are_seeded_only_on_after_switch_theme_without_overwriting_existing_terms() { + $slug = 'silicon-ranch'; + $term = get_term_by( 'slug', $slug, 'chrnx_show' ); + if ( $term ) { + wp_delete_term( $term->term_id, 'chrnx_show' ); + } + + do_action( 'init' ); + $this->assertFalse( get_term_by( 'slug', $slug, 'chrnx_show' ) ); + + do_action( 'after_switch_theme' ); + $seeded = get_term_by( 'slug', $slug, 'chrnx_show' ); + $this->assertInstanceOf( WP_Term::class, $seeded ); + $this->assertSame( 'Silicon Ranch', $seeded->name ); + + wp_update_term( $seeded->term_id, 'chrnx_show', array( 'name' => 'Existing Name' ) ); + do_action( 'after_switch_theme' ); + $this->assertSame( 'Existing Name', get_term( $seeded->term_id, 'chrnx_show' )->name ); + } + + /** + * Missing values remain missing and legacy categories are untouched. + */ + public function test_missing_metadata_stays_empty_and_categories_are_not_rewritten() { + $post_id = self::factory()->post->create(); + $category_id = self::factory()->category->create( array( 'name' => 'Legacy' ) ); + wp_set_post_categories( $post_id, array( $category_id ) ); + + do_action( 'after_switch_theme' ); + + $this->assertSame( array(), wp_get_object_terms( $post_id, 'chrnx_topic', array( 'fields' => 'ids' ) ) ); + $this->assertSame( array(), wp_get_object_terms( $post_id, 'chrnx_language', array( 'fields' => 'ids' ) ) ); + $this->assertSame( array(), wp_get_object_terms( $post_id, 'chrnx_show', array( 'fields' => 'ids' ) ) ); + $this->assertSame( array( $category_id ), wp_get_post_categories( $post_id ) ); + } + + /** + * Multiple values normalize deterministically and expose a safe notice. + */ + public function test_multiple_terms_normalize_to_lowest_term_id_without_recursion() { + $post_id = self::factory()->post->create(); + $high = self::factory()->term->create( + array( + 'taxonomy' => 'chrnx_topic', + 'name' => 'Zulu', + ) + ); + $low = self::factory()->term->create( + array( + 'taxonomy' => 'chrnx_topic', + 'name' => 'Alpha', + ) + ); + $ids = array( min( $low, $high ), max( $low, $high ) ); + $calls = 0; + $counter = static function ( $object_id, $terms, $term_taxonomy_ids, $taxonomy ) use ( $post_id, &$calls ) { + if ( $post_id === $object_id && 'chrnx_topic' === $taxonomy ) { + ++$calls; + } + }; + add_action( 'set_object_terms', $counter, 20, 4 ); + + wp_set_object_terms( $post_id, array( $ids[1], $ids[0] ), 'chrnx_topic' ); + remove_action( 'set_object_terms', $counter, 20 ); + + $this->assertSame( array( $ids[0] ), wp_get_object_terms( $post_id, 'chrnx_topic', array( 'fields' => 'ids' ) ) ); + $this->assertLessThanOrEqual( 2, $calls, 'Normalization should make at most one guarded corrective assignment.' ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $notice = ob_get_clean(); + $this->assertStringContainsString( 'is-dismissible', $notice ); + $this->assertStringContainsString( 'Topic', $notice ); + $this->assertStringNotContainsString( 'Zulu', $notice ); + $this->assertStringNotContainsString( 'Alpha', $notice ); + } +}