class-link-factory.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Admin\Links
  6. */
  7. /**
  8. * Represents the conversion from array with string links into WPSEO_Link objects.
  9. */
  10. class WPSEO_Link_Factory {
  11. /** @var WPSEO_Link_Type_Classifier */
  12. protected $classifier;
  13. /** @var WPSEO_Link_Internal_Lookup */
  14. protected $internal_lookup;
  15. /** @var WPSEO_Link_Filter */
  16. protected $filter;
  17. /**
  18. * Sets the dependencies for this object.
  19. *
  20. * @param WPSEO_Link_Type_Classifier $classifier The classifier to use.
  21. * @param WPSEO_Link_Internal_Lookup $internal_lookup The internal lookup to use.
  22. * @param WPSEO_Link_Filter $filter The link filter.
  23. */
  24. public function __construct( WPSEO_Link_Type_Classifier $classifier, WPSEO_Link_Internal_Lookup $internal_lookup, WPSEO_Link_Filter $filter ) {
  25. $this->classifier = $classifier;
  26. $this->internal_lookup = $internal_lookup;
  27. $this->filter = $filter;
  28. }
  29. /**
  30. * Formats an array of links to WPSEO_Link object.
  31. *
  32. * @param array $extracted_links The links for format.
  33. *
  34. * @return WPSEO_Link[] The formatted links.
  35. */
  36. public function build( array $extracted_links ) {
  37. $extracted_links = array_map( array( $this, 'build_link' ), $extracted_links );
  38. $filtered_links = array_filter( $extracted_links, array(
  39. $this->filter,
  40. 'internal_link_with_fragment_filter',
  41. ) );
  42. return $filtered_links;
  43. }
  44. /**
  45. * Builds the link.
  46. *
  47. * @param string $link The link to build.
  48. *
  49. * @return WPSEO_Link The built link.
  50. */
  51. public function build_link( $link ) {
  52. $link_type = $this->classifier->classify( $link );
  53. $target_post_id = 0;
  54. if ( $link_type === WPSEO_Link::TYPE_INTERNAL ) {
  55. $target_post_id = $this->internal_lookup->lookup( $link );
  56. }
  57. return self::get_link( $link, $target_post_id, $link_type );
  58. }
  59. /**
  60. * Returns the link object.
  61. *
  62. * @param string $url The URL of the link.
  63. * @param int $target_post_id The target post ID.
  64. * @param string $type The link type.
  65. *
  66. * @return WPSEO_Link Generated link object.
  67. */
  68. public static function get_link( $url, $target_post_id, $type ) {
  69. return new WPSEO_Link( $url, $target_post_id, $type );
  70. }
  71. }