class-link-column-count.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Admin\Links
  6. */
  7. /**
  8. * Represents the link column count. This class contains the count for each post id on the current page.
  9. */
  10. class WPSEO_Link_Column_Count {
  11. /**
  12. * The link counts for each post id on the current page.
  13. *
  14. * @var array
  15. */
  16. protected $count = [];
  17. /**
  18. * Sets the counts for the set target field.
  19. *
  20. * @param array $post_ids The posts to get the count for.
  21. */
  22. public function set( $post_ids ) {
  23. if ( empty( $post_ids ) ) {
  24. return;
  25. }
  26. $this->count = $this->get_results( $post_ids );
  27. }
  28. /**
  29. * Gets the link count for given post id.
  30. *
  31. * @param int $post_id The post id.
  32. * @param string $target_field The field to show.
  33. *
  34. * @return int|null The total amount of links or null if the target field
  35. * does not exist for the given post id.
  36. */
  37. public function get( $post_id, $target_field = 'internal_link_count' ) {
  38. if ( array_key_exists( $post_id, $this->count ) && array_key_exists( $target_field, $this->count[ $post_id ] ) ) {
  39. return $this->count[ $post_id ][ $target_field ];
  40. }
  41. return null;
  42. }
  43. /**
  44. * Gets the link count for the given post ids.
  45. *
  46. * @param array $post_ids Array with post_ids.
  47. *
  48. * @return array
  49. */
  50. protected function get_results( $post_ids ) {
  51. global $wpdb;
  52. $storage = new WPSEO_Meta_Storage();
  53. $results = $wpdb->get_results(
  54. $wpdb->prepare(
  55. '
  56. SELECT internal_link_count, incoming_link_count, object_id
  57. FROM ' . $storage->get_table_name() . '
  58. WHERE object_id IN (' . implode( ',', array_fill( 0, count( $post_ids ), '%d' ) ) . ')',
  59. $post_ids
  60. ),
  61. ARRAY_A
  62. );
  63. $output = [];
  64. foreach ( $results as $result ) {
  65. $output[ (int) $result['object_id'] ] = [
  66. 'internal_link_count' => $result['internal_link_count'],
  67. 'incoming_link_count' => (int) $result['incoming_link_count'],
  68. ];
  69. }
  70. // Set unfound items to zero.
  71. foreach ( $post_ids as $post_id ) {
  72. if ( ! array_key_exists( $post_id, $output ) ) {
  73. $output[ $post_id ] = [
  74. 'internal_link_count' => null,
  75. 'incoming_link_count' => 0,
  76. ];
  77. }
  78. }
  79. return $output;
  80. }
  81. }