Save.php
79 lines
| 1 | <?php |
| 2 | |
| 3 | namespace AC\Controller\ListScreen; |
| 4 | |
| 5 | use AC\ListScreenRepository\Storage; |
| 6 | use AC\ListScreenTypes; |
| 7 | use AC\Request; |
| 8 | use AC\Type\ListScreenId; |
| 9 | |
| 10 | class Save { |
| 11 | |
| 12 | /** |
| 13 | * @var Storage |
| 14 | */ |
| 15 | private $storage; |
| 16 | |
| 17 | /** |
| 18 | * @var Sanitize\FormData |
| 19 | */ |
| 20 | private $sanitizer; |
| 21 | |
| 22 | public function __construct( Storage $storage ) { |
| 23 | $this->storage = $storage; |
| 24 | $this->sanitizer = new Sanitize\FormData(); |
| 25 | } |
| 26 | |
| 27 | public function request( Request $request ) { |
| 28 | $data = json_decode( $request->get( 'data' ), true ); |
| 29 | |
| 30 | if ( ! isset( $data['columns'] ) ) { |
| 31 | wp_send_json_error( [ 'message' => __( 'You need at least one column', 'codepress-admin-columns' ) ] ); |
| 32 | } |
| 33 | |
| 34 | $list_screen = ListScreenTypes::instance()->get_list_screen_by_key( $data['list_screen'] ); |
| 35 | |
| 36 | if ( ! $list_screen ) { |
| 37 | wp_send_json_error( [ 'message' => 'List screen not found' ] ); |
| 38 | } |
| 39 | |
| 40 | $list_id = isset( $data['list_screen_id'] ) && ListScreenId::is_valid_id( $data['list_screen_id'] ) |
| 41 | ? new ListScreenId( $data['list_screen_id'] ) |
| 42 | : ListScreenId::generate(); |
| 43 | |
| 44 | $data = $this->sanitizer->sanitize( $data ); |
| 45 | |
| 46 | $list_screen->set_title( ! empty( $data['title'] ) ? $data['title'] : $list_screen->get_label() ) |
| 47 | ->set_settings( isset( $data['columns'] ) ? $this->maybe_encode_urls( $data['columns'] ) : [] ) |
| 48 | ->set_layout_id( $list_id->get_id() ) |
| 49 | ->set_preferences( ! empty( $data['settings'] ) ? $data['settings'] : [] ); |
| 50 | |
| 51 | $this->storage->save( $list_screen ); |
| 52 | |
| 53 | do_action( 'ac/columns_stored', $list_screen ); |
| 54 | |
| 55 | wp_send_json_success( [ |
| 56 | 'message' => sprintf( |
| 57 | '%s %s', |
| 58 | sprintf( |
| 59 | __( 'Settings for %s updated successfully.', 'codepress-admin-columns' ), |
| 60 | sprintf( '<strong>%s</strong>', esc_html( $list_screen->get_title() ) ) |
| 61 | ), |
| 62 | ac_helper()->html->link( $list_screen->get_screen_link(), sprintf( __( 'View %s screen', 'codepress-admin-columns' ), $list_screen->get_label() ) ) |
| 63 | ), |
| 64 | 'list_id' => $list_id->get_id(), |
| 65 | ] |
| 66 | ); |
| 67 | } |
| 68 | |
| 69 | private function maybe_encode_urls( array $columndata ) { |
| 70 | foreach ( $columndata as $name => $data ) { |
| 71 | if ( isset( $data['label'] ) ) { |
| 72 | $columndata[ $name ]['label'] = ac_convert_site_url( $data['label'] ); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | return $columndata; |
| 77 | } |
| 78 | |
| 79 | } |