| 1 |
<?php |
| 2 |
/** |
| 3 |
* Desktop Mode — `term` file type. Covers any taxonomy term |
| 4 |
* (category, tag, custom). Reference shape: `"<taxonomy>:<term_id>"`. |
| 5 |
* |
| 6 |
* @package WPDesktopMode |
| 7 |
* @since 0.9.0 |
| 8 |
*/ |
| 9 |
|
| 10 |
defined( 'ABSPATH' ) || exit; |
| 11 |
|
| 12 |
/** |
| 13 |
* @since 0.9.0 |
| 14 |
*/ |
| 15 |
class Desktop_Mode_Term_File extends Desktop_Mode_File { |
| 16 |
|
| 17 |
public static function type(): string { |
| 18 |
return 'term'; |
| 19 |
} |
| 20 |
|
| 21 |
public function exists(): bool { |
| 22 |
return $this->term() instanceof WP_Term; |
| 23 |
} |
| 24 |
|
| 25 |
public function title(): string { |
| 26 |
$term = $this->term(); |
| 27 |
if ( ! $term ) { |
| 28 |
return __( '(missing term)', 'desktop-mode' ); |
| 29 |
} |
| 30 |
return wp_strip_all_tags( $term->name ); |
| 31 |
} |
| 32 |
|
| 33 |
public function icon(): string { |
| 34 |
$term = $this->term(); |
| 35 |
if ( ! $term ) { |
| 36 |
return 'dashicons-warning'; |
| 37 |
} |
| 38 |
switch ( $term->taxonomy ) { |
| 39 |
case 'category': |
| 40 |
return 'dashicons-category'; |
| 41 |
case 'post_tag': |
| 42 |
return 'dashicons-tag'; |
| 43 |
default: |
| 44 |
return 'dashicons-tagcloud'; |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
public function can_read( int $user_id ): bool { |
| 49 |
$term = $this->term(); |
| 50 |
if ( ! $term ) { |
| 51 |
return false; |
| 52 |
} |
| 53 |
$tax = get_taxonomy( $term->taxonomy ); |
| 54 |
if ( ! $tax ) { |
| 55 |
return false; |
| 56 |
} |
| 57 |
return user_can( $user_id, $tax->cap->edit_terms ) || user_can( $user_id, 'read' ); |
| 58 |
} |
| 59 |
|
| 60 |
public function serialize(): array { |
| 61 |
$shape = parent::serialize(); |
| 62 |
$term = $this->term(); |
| 63 |
$shape['taxonomy'] = $term ? (string) $term->taxonomy : ''; |
| 64 |
$shape['count'] = $term ? (int) $term->count : 0; |
| 65 |
return $shape; |
| 66 |
} |
| 67 |
|
| 68 |
private function term(): ?WP_Term { |
| 69 |
[ $taxonomy, $term_id ] = $this->parse_ref(); |
| 70 |
if ( '' === $taxonomy || $term_id <= 0 ) { |
| 71 |
return null; |
| 72 |
} |
| 73 |
$term = get_term( $term_id, $taxonomy ); |
| 74 |
return $term instanceof WP_Term ? $term : null; |
| 75 |
} |
| 76 |
|
| 77 |
/** |
| 78 |
* @return array{0: string, 1: int} |
| 79 |
*/ |
| 80 |
private function parse_ref(): array { |
| 81 |
$parts = explode( ':', $this->ref, 2 ); |
| 82 |
if ( count( $parts ) !== 2 ) { |
| 83 |
return array( '', 0 ); |
| 84 |
} |
| 85 |
return array( (string) $parts[0], (int) $parts[1] ); |
| 86 |
} |
| 87 |
} |
| 88 |
|