Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like WPCOM_JSON_API often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use WPCOM_JSON_API, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 5 | class WPCOM_JSON_API { |
||
| 6 | static $self = null; |
||
| 7 | |||
| 8 | public $endpoints = array(); |
||
| 9 | |||
| 10 | public $token_details = array(); |
||
| 11 | |||
| 12 | public $method = ''; |
||
| 13 | public $url = ''; |
||
| 14 | public $path = ''; |
||
| 15 | public $version = null; |
||
| 16 | public $query = array(); |
||
| 17 | public $post_body = null; |
||
| 18 | public $files = null; |
||
| 19 | public $content_type = null; |
||
| 20 | public $accept = ''; |
||
| 21 | |||
| 22 | public $_server_https; |
||
| 23 | public $exit = true; |
||
| 24 | public $public_api_scheme = 'https'; |
||
| 25 | |||
| 26 | public $output_status_code = 200; |
||
| 27 | |||
| 28 | public $trapped_error = null; |
||
| 29 | public $did_output = false; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @return WPCOM_JSON_API instance |
||
| 33 | */ |
||
| 34 | static function init( $method = null, $url = null, $post_body = null ) { |
||
| 35 | if ( !self::$self ) { |
||
| 36 | $class = function_exists( 'get_called_class' ) ? get_called_class() : __CLASS__; |
||
| 37 | self::$self = new $class( $method, $url, $post_body ); |
||
| 38 | } |
||
| 39 | return self::$self; |
||
| 40 | } |
||
| 41 | |||
| 42 | function add( WPCOM_JSON_API_Endpoint $endpoint ) { |
||
| 43 | $path_versions = serialize( array ( |
||
| 44 | $endpoint->path, |
||
| 45 | $endpoint->min_version, |
||
| 46 | $endpoint->max_version, |
||
| 47 | ) ); |
||
| 48 | if ( !isset( $this->endpoints[$path_versions] ) ) { |
||
| 49 | $this->endpoints[$path_versions] = array(); |
||
| 50 | } |
||
| 51 | $this->endpoints[$path_versions][$endpoint->method] = $endpoint; |
||
| 52 | } |
||
| 53 | |||
| 54 | static function is_truthy( $value ) { |
||
| 64 | |||
| 65 | static function is_falsy( $value ) { |
||
| 75 | |||
| 76 | function __construct() { |
||
| 80 | |||
| 81 | function setup_inputs( $method = null, $url = null, $post_body = null ) { |
||
| 82 | if ( is_null( $method ) ) { |
||
| 83 | $this->method = strtoupper( $_SERVER['REQUEST_METHOD'] ); |
||
| 84 | } else { |
||
| 85 | $this->method = strtoupper( $method ); |
||
| 86 | } |
||
| 87 | if ( is_null( $url ) ) { |
||
| 88 | $this->url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); |
||
| 89 | } else { |
||
| 90 | $this->url = $url; |
||
| 91 | } |
||
| 92 | |||
| 93 | $parsed = parse_url( $this->url ); |
||
| 94 | $this->path = $parsed['path']; |
||
| 95 | |||
| 96 | if ( !empty( $parsed['query'] ) ) { |
||
| 97 | wp_parse_str( $parsed['query'], $this->query ); |
||
| 98 | } |
||
| 99 | |||
| 100 | if ( isset( $_SERVER['HTTP_ACCEPT'] ) && $_SERVER['HTTP_ACCEPT'] ) { |
||
| 101 | $this->accept = $_SERVER['HTTP_ACCEPT']; |
||
| 102 | } |
||
| 103 | |||
| 104 | if ( 'POST' === $this->method ) { |
||
| 105 | if ( is_null( $post_body ) ) { |
||
| 106 | $this->post_body = file_get_contents( 'php://input' ); |
||
| 107 | |||
| 108 | if ( isset( $_SERVER['HTTP_CONTENT_TYPE'] ) && $_SERVER['HTTP_CONTENT_TYPE'] ) { |
||
| 109 | $this->content_type = $_SERVER['HTTP_CONTENT_TYPE']; |
||
| 110 | } elseif ( isset( $_SERVER['CONTENT_TYPE'] ) && $_SERVER['CONTENT_TYPE'] ) { |
||
| 111 | $this->content_type = $_SERVER['CONTENT_TYPE'] ; |
||
| 112 | } elseif ( '{' === $this->post_body[0] ) { |
||
| 113 | $this->content_type = 'application/json'; |
||
| 114 | } else { |
||
| 115 | $this->content_type = 'application/x-www-form-urlencoded'; |
||
| 116 | } |
||
| 117 | |||
| 118 | if ( 0 === strpos( strtolower( $this->content_type ), 'multipart/' ) ) { |
||
| 119 | $this->post_body = http_build_query( stripslashes_deep( $_POST ) ); |
||
| 120 | $this->files = $_FILES; |
||
| 121 | $this->content_type = 'multipart/form-data'; |
||
| 122 | } |
||
| 123 | } else { |
||
| 124 | $this->post_body = $post_body; |
||
| 125 | $this->content_type = '{' === isset( $this->post_body[0] ) && $this->post_body[0] ? 'application/json' : 'application/x-www-form-urlencoded'; |
||
| 126 | } |
||
| 127 | } else { |
||
| 128 | $this->post_body = null; |
||
| 129 | $this->content_type = null; |
||
| 130 | } |
||
| 131 | |||
| 132 | $this->_server_https = array_key_exists( 'HTTPS', $_SERVER ) ? $_SERVER['HTTPS'] : '--UNset--'; |
||
| 133 | } |
||
| 134 | |||
| 135 | function initialize() { |
||
| 138 | |||
| 139 | function serve( $exit = true ) { |
||
| 339 | |||
| 340 | function process_request( WPCOM_JSON_API_Endpoint $endpoint, $path_pieces ) { |
||
| 344 | |||
| 345 | function output_early( $status_code, $response = null, $content_type = 'application/json' ) { |
||
| 357 | |||
| 358 | function set_output_status_code( $code = 200 ) { |
||
| 361 | |||
| 362 | function output( $status_code, $response = null, $content_type = 'application/json' ) { |
||
| 363 | // In case output() was called before the callback returned |
||
| 364 | if ( $this->did_output ) { |
||
| 365 | if ( $this->exit ) |
||
| 366 | exit; |
||
| 367 | return $content_type; |
||
| 368 | } |
||
| 369 | $this->did_output = true; |
||
| 370 | |||
| 371 | // 400s and 404s are allowed for all origins |
||
| 372 | if ( 404 == $status_code || 400 == $status_code ) |
||
| 373 | header( 'Access-Control-Allow-Origin: *' ); |
||
| 374 | |||
| 375 | if ( is_null( $response ) ) { |
||
| 376 | $response = new stdClass; |
||
| 377 | } |
||
| 378 | |||
| 379 | if ( 'text/plain' === $content_type ) { |
||
| 380 | status_header( (int) $status_code ); |
||
| 381 | header( 'Content-Type: text/plain' ); |
||
| 382 | echo $response; |
||
| 383 | if ( $this->exit ) { |
||
| 384 | exit; |
||
| 385 | } |
||
| 386 | |||
| 387 | return $content_type; |
||
| 388 | } |
||
| 389 | |||
| 390 | $response = $this->filter_fields( $response ); |
||
| 391 | |||
| 392 | if ( isset( $this->query['http_envelope'] ) && self::is_truthy( $this->query['http_envelope'] ) ) { |
||
| 393 | $response = array( |
||
| 394 | 'code' => (int) $status_code, |
||
| 395 | 'headers' => array( |
||
| 396 | array( |
||
| 397 | 'name' => 'Content-Type', |
||
| 398 | 'value' => $content_type, |
||
| 399 | ), |
||
| 400 | ), |
||
| 401 | 'body' => $response, |
||
| 402 | ); |
||
| 403 | $status_code = 200; |
||
| 404 | $content_type = 'application/json'; |
||
| 405 | } |
||
| 406 | |||
| 407 | status_header( (int) $status_code ); |
||
| 408 | header( "Content-Type: $content_type" ); |
||
| 409 | if ( isset( $this->query['callback'] ) && is_string( $this->query['callback'] ) ) { |
||
| 410 | $callback = preg_replace( '/[^a-z0-9_.]/i', '', $this->query['callback'] ); |
||
| 411 | } else { |
||
| 412 | $callback = false; |
||
| 413 | } |
||
| 414 | |||
| 415 | if ( $callback ) { |
||
| 416 | // Mitigate Rosetta Flash [1] by setting the Content-Type-Options: nosniff header |
||
| 417 | // and by prepending the JSONP response with a JS comment. |
||
| 418 | // [1] http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/ |
||
| 419 | echo "/**/$callback("; |
||
| 420 | |||
| 421 | } |
||
| 422 | echo $this->json_encode( $response ); |
||
| 423 | if ( $callback ) { |
||
| 424 | echo ");"; |
||
| 425 | } |
||
| 426 | |||
| 427 | if ( $this->exit ) { |
||
| 428 | exit; |
||
| 429 | } |
||
| 430 | |||
| 431 | return $content_type; |
||
| 432 | } |
||
| 433 | |||
| 434 | public static function serializable_error ( $error ) { |
||
| 435 | |||
| 436 | $status_code = $error->get_error_data(); |
||
| 437 | |||
| 438 | if ( is_array( $status_code ) ) |
||
| 439 | $status_code = $status_code['status_code']; |
||
| 440 | |||
| 441 | if ( !$status_code ) { |
||
| 442 | $status_code = 400; |
||
| 443 | } |
||
| 444 | $response = array( |
||
| 445 | 'error' => $error->get_error_code(), |
||
| 446 | 'message' => $error->get_error_message(), |
||
| 447 | ); |
||
| 448 | return array( |
||
| 449 | 'status_code' => $status_code, |
||
| 450 | 'errors' => $response |
||
| 451 | ); |
||
| 452 | } |
||
| 453 | |||
| 454 | function output_error( $error ) { |
||
| 455 | if ( function_exists( 'bump_stats_extra' ) ) { |
||
| 456 | $client_id = ! empty( $this->token_details['client_id'] ) ? $this->token_details['client_id'] : 0; |
||
| 457 | bump_stats_extra( 'rest-api-errors', $client_id ); |
||
| 458 | } |
||
| 459 | |||
| 460 | $error_response = $this->serializable_error( $error ); |
||
| 461 | |||
| 462 | return $this->output( $error_response[ 'status_code'], $error_response['errors'] ); |
||
| 463 | } |
||
| 464 | |||
| 465 | function filter_fields( $response ) { |
||
| 466 | if ( empty( $this->query['fields'] ) || ( is_array( $response ) && ! empty( $response['error'] ) ) || ! empty( $this->endpoint->custom_fields_filtering ) ) |
||
| 467 | return $response; |
||
| 468 | |||
| 469 | $fields = array_map( 'trim', explode( ',', $this->query['fields'] ) ); |
||
| 470 | |||
| 471 | if ( is_object( $response ) ) { |
||
| 472 | $response = (array) $response; |
||
| 473 | } |
||
| 474 | |||
| 475 | $has_filtered = false; |
||
| 476 | if ( is_array( $response ) && empty( $response['ID'] ) ) { |
||
| 477 | $keys_to_filter = array( |
||
| 478 | 'categories', |
||
| 479 | 'comments', |
||
| 480 | 'connections', |
||
| 481 | 'domains', |
||
| 482 | 'groups', |
||
| 483 | 'likes', |
||
| 484 | 'media', |
||
| 485 | 'notes', |
||
| 486 | 'posts', |
||
| 487 | 'services', |
||
| 488 | 'sites', |
||
| 489 | 'suggestions', |
||
| 490 | 'tags', |
||
| 491 | 'themes', |
||
| 492 | 'topics', |
||
| 493 | 'users', |
||
| 494 | ); |
||
| 495 | |||
| 496 | foreach ( $keys_to_filter as $key_to_filter ) { |
||
| 497 | if ( ! isset( $response[ $key_to_filter ] ) || $has_filtered ) |
||
| 498 | continue; |
||
| 499 | |||
| 500 | foreach ( $response[ $key_to_filter ] as $key => $values ) { |
||
| 501 | if ( is_object( $values ) ) { |
||
| 502 | $response[ $key_to_filter ][ $key ] = (object) array_intersect_key( (array) $values, array_flip( $fields ) ); |
||
| 503 | } elseif ( is_array( $values ) ) { |
||
| 504 | $response[ $key_to_filter ][ $key ] = array_intersect_key( $values, array_flip( $fields ) ); |
||
| 505 | } |
||
| 506 | } |
||
| 507 | |||
| 508 | $has_filtered = true; |
||
| 509 | } |
||
| 510 | } |
||
| 511 | |||
| 512 | if ( ! $has_filtered ) { |
||
| 513 | if ( is_object( $response ) ) { |
||
| 514 | $response = (object) array_intersect_key( (array) $response, array_flip( $fields ) ); |
||
| 515 | } else if ( is_array( $response ) ) { |
||
| 516 | $response = array_intersect_key( $response, array_flip( $fields ) ); |
||
| 517 | } |
||
| 518 | } |
||
| 519 | |||
| 520 | return $response; |
||
| 521 | } |
||
| 522 | |||
| 523 | function ensure_http_scheme_of_home_url( $url, $path, $original_scheme ) { |
||
| 524 | if ( $original_scheme ) { |
||
| 525 | return $url; |
||
| 526 | } |
||
| 527 | |||
| 528 | return preg_replace( '#^https:#', 'http:', $url ); |
||
| 529 | } |
||
| 530 | |||
| 531 | function comment_edit_pre( $comment_content ) { |
||
| 534 | |||
| 535 | function json_encode( $data ) { |
||
| 538 | |||
| 539 | function ends_with( $haystack, $needle ) { |
||
| 542 | |||
| 543 | // Returns the site's blog_id in the WP.com ecosystem |
||
| 544 | function get_blog_id_for_output() { |
||
| 547 | |||
| 548 | // Returns the site's local blog_id |
||
| 549 | function get_blog_id( $blog_id ) { |
||
| 552 | |||
| 553 | function switch_to_blog_and_validate_user( $blog_id = 0, $verify_token_for_blog = true ) { |
||
| 564 | |||
| 565 | // Returns true if the specified blog ID is a restricted blog |
||
| 566 | function is_restricted_blog( $blog_id ) { |
||
| 567 | /** |
||
| 568 | * Filters all REST API access and return a 403 unauthorized response for all Restricted blog IDs. |
||
| 569 | * |
||
| 570 | * @module json-api |
||
| 571 | * |
||
| 572 | * @since 3.4.0 |
||
| 573 | * |
||
| 574 | * @param array $array Array of Blog IDs. |
||
| 575 | */ |
||
| 576 | $restricted_blog_ids = apply_filters( 'wpcom_json_api_restricted_blog_ids', array() ); |
||
| 577 | return true === in_array( $blog_id, $restricted_blog_ids ); |
||
| 578 | } |
||
| 579 | |||
| 580 | function post_like_count( $blog_id, $post_id ) { |
||
| 583 | |||
| 584 | function is_liked( $blog_id, $post_id ) { |
||
| 587 | |||
| 588 | function is_reblogged( $blog_id, $post_id ) { |
||
| 591 | |||
| 592 | function is_following( $blog_id ) { |
||
| 595 | |||
| 596 | function add_global_ID( $blog_id, $post_id ) { |
||
| 599 | |||
| 600 | function get_avatar_url( $email, $avatar_size = 96 ) { |
||
| 601 | add_filter( 'pre_option_show_avatars', '__return_true', 999 ); |
||
| 602 | $_SERVER['HTTPS'] = 'off'; |
||
| 603 | |||
| 604 | $avatar_img_element = get_avatar( $email, $avatar_size, '' ); |
||
| 605 | |||
| 606 | if ( !$avatar_img_element || is_wp_error( $avatar_img_element ) ) { |
||
| 607 | $return = ''; |
||
| 608 | } elseif ( !preg_match( '#src=([\'"])?(.*?)(?(1)\\1|\s)#', $avatar_img_element, $matches ) ) { |
||
| 609 | $return = ''; |
||
| 610 | } else { |
||
| 611 | $return = esc_url_raw( htmlspecialchars_decode( $matches[2] ) ); |
||
| 612 | } |
||
| 613 | |||
| 614 | remove_filter( 'pre_option_show_avatars', '__return_true', 999 ); |
||
| 615 | if ( '--UNset--' === $this->_server_https ) { |
||
| 616 | unset( $_SERVER['HTTPS'] ); |
||
| 617 | } else { |
||
| 618 | $_SERVER['HTTPS'] = $this->_server_https; |
||
| 619 | } |
||
| 620 | |||
| 621 | return $return; |
||
| 622 | } |
||
| 623 | |||
| 624 | /** |
||
| 625 | * Traps `wp_die()` calls and outputs a JSON response instead. |
||
| 626 | * The result is always output, never returned. |
||
| 627 | * |
||
| 628 | * @param string|null $error_code. Call with string to start the trapping. Call with null to stop. |
||
| 629 | */ |
||
| 630 | function trap_wp_die( $error_code = null ) { |
||
| 631 | // Stop trapping |
||
| 632 | if ( is_null( $error_code ) ) { |
||
| 633 | $this->trapped_error = null; |
||
| 634 | remove_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) ); |
||
| 635 | return; |
||
| 636 | } |
||
| 637 | |||
| 638 | // If API called via PHP, bail: don't do our custom wp_die(). Do the normal wp_die(). |
||
| 639 | if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) { |
||
| 640 | if ( ! defined( 'REST_API_REQUEST' ) || ! REST_API_REQUEST ) { |
||
| 641 | return; |
||
| 642 | } |
||
| 643 | } else { |
||
| 644 | if ( ! defined( 'XMLRPC_REQUEST' ) || ! XMLRPC_REQUEST ) { |
||
| 645 | return; |
||
| 646 | } |
||
| 647 | } |
||
| 648 | |||
| 649 | // Start trapping |
||
| 650 | $this->trapped_error = array( |
||
| 651 | 'status' => 500, |
||
| 652 | 'code' => $error_code, |
||
| 653 | 'message' => '', |
||
| 654 | ); |
||
| 655 | |||
| 656 | add_filter( 'wp_die_handler', array( $this, 'wp_die_handler_callback' ) ); |
||
| 657 | } |
||
| 658 | |||
| 659 | function wp_die_handler_callback() { |
||
| 662 | |||
| 663 | function wp_die_handler( $message, $title = '', $args = array() ) { |
||
| 664 | $args = wp_parse_args( $args, array( |
||
| 665 | 'response' => 500, |
||
| 666 | ) ); |
||
| 667 | |||
| 668 | if ( $title ) { |
||
| 669 | $message = "$title: $message"; |
||
| 670 | } |
||
| 671 | |||
| 672 | switch ( $this->trapped_error['code'] ) { |
||
| 673 | case 'comment_failure' : |
||
| 674 | if ( did_action( 'comment_duplicate_trigger' ) ) { |
||
| 675 | $this->trapped_error['code'] = 'comment_duplicate'; |
||
| 676 | } else if ( did_action( 'comment_flood_trigger' ) ) { |
||
| 677 | $this->trapped_error['code'] = 'comment_flood'; |
||
| 678 | } |
||
| 679 | break; |
||
| 680 | } |
||
| 681 | |||
| 682 | $this->trapped_error['status'] = $args['response']; |
||
| 683 | $this->trapped_error['message'] = wp_kses( $message, array() ); |
||
| 684 | |||
| 685 | // We still want to exit so that code execution stops where it should. |
||
| 686 | // Attach the JSON output to WordPress' shutdown handler |
||
| 687 | add_action( 'shutdown', array( $this, 'output_trapped_error' ), 0 ); |
||
| 688 | exit; |
||
| 689 | } |
||
| 690 | |||
| 691 | function output_trapped_error() { |
||
| 692 | $this->exit = false; // We're already exiting once. Don't do it twice. |
||
| 693 | $this->output( $this->trapped_error['status'], (object) array( |
||
| 694 | 'error' => $this->trapped_error['code'], |
||
| 695 | 'message' => $this->trapped_error['message'], |
||
| 696 | ) ); |
||
| 697 | } |
||
| 698 | |||
| 699 | function finish_request() { |
||
| 703 | } |
||
| 704 |
PHP has two types of connecting operators (logical operators, and boolean operators):
and&&or||The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like
&&, or||.Let’s take a look at a few examples:
Logical Operators are used for Control-Flow
One case where you explicitly want to use logical operators is for control-flow such as this:
Since
dieintroduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined withthrowat this point:These limitations lead to logical operators rarely being of use in current PHP code.