class-link-column-count.php 2.1 KB

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