ColumnReplacement.php
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace ACA\Polylang\Service;
use AC;
use AC\Registerable;
use ACA\Polylang\Column;
class ColumnReplacement implements Registerable {
/**
* @var AC\ListScreen
*/
private $list_screen;
/**
* @var []
*/
private $polylang_columns;
public function __construct( AC\ListScreen $list_screen ) {
$this->list_screen = $list_screen;
$this->polylang_columns = [];
}
public function register() {
add_filter( $this->list_screen->get_heading_hookname(), [ $this, 'set_dynamic_columns' ], 199 );
add_filter( $this->list_screen->get_heading_hookname(), [ $this, 're_add_dynamic_columns' ], 201 );
add_filter( $this->list_screen->get_heading_hookname(), [ $this, 'remove_placeholder_columns' ], 202 );
}
public function set_dynamic_columns( $headings ) {
foreach ( $headings as $key => $label ) {
if ( strpos( $key, 'language_' ) !== false ) {
$this->polylang_columns[ $key ] = $label;
}
}
return $headings;
}
private function get_placeholder_column_key() {
$columns = $this->get_placeholder_columns();
return empty( $columns ) ? null : reset( $columns );
}
private function get_placeholder_columns() {
$columns = array_filter( $this->list_screen->get_columns(), function ( $column ) {
return $column instanceof Column\Language;
} );
return array_keys( $columns );
}
public function remove_placeholder_columns( $headings ) {
foreach ( $this->get_placeholder_columns() as $key ) {
if ( array_key_exists( $key, $headings ) ) {
unset( $headings[ $key ] );
}
}
return $headings;
}
public function re_add_dynamic_columns( $headings ) {
$replacement_key = $this->get_placeholder_column_key();
return $replacement_key ? $this->replace_placeholder_column( $headings, $replacement_key ) : $headings;
}
private function replace_placeholder_column( $headings, $replacement_key ) {
foreach ( $headings as $key => $label ) {
if ( $replacement_key === $key ) {
$index = array_search( $replacement_key, array_keys( $headings ) );
$headings = array_slice( $headings, 0, $index, true ) + $this->polylang_columns + array_slice( $headings, $index, count( $headings ) - $index, true );
}
}
return $headings;
}
}