class-link-factory.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. /**
  12. * Represents the classifier for a link. Determines of a link is an outbound or internal one.
  13. *
  14. * @var WPSEO_Link_Type_Classifier
  15. */
  16. protected $classifier;
  17. /**
  18. * Represents the internal link lookup. This class tries get the postid for a given internal link.
  19. *
  20. * @var WPSEO_Link_Internal_Lookup
  21. */
  22. protected $internal_lookup;
  23. /**
  24. * Represents the filter for filtering links.
  25. *
  26. * @var WPSEO_Link_Filter
  27. */
  28. protected $filter;
  29. /**
  30. * Sets the dependencies for this object.
  31. *
  32. * @param WPSEO_Link_Type_Classifier $classifier The classifier to use.
  33. * @param WPSEO_Link_Internal_Lookup $internal_lookup The internal lookup to use.
  34. * @param WPSEO_Link_Filter $filter The link filter.
  35. */
  36. public function __construct( WPSEO_Link_Type_Classifier $classifier, WPSEO_Link_Internal_Lookup $internal_lookup, WPSEO_Link_Filter $filter ) {
  37. $this->classifier = $classifier;
  38. $this->internal_lookup = $internal_lookup;
  39. $this->filter = $filter;
  40. }
  41. /**
  42. * Formats an array of links to WPSEO_Link object.
  43. *
  44. * @param array $extracted_links The links for format.
  45. *
  46. * @return WPSEO_Link[] The formatted links.
  47. */
  48. public function build( array $extracted_links ) {
  49. $extracted_links = array_map( [ $this, 'build_link' ], $extracted_links );
  50. $filtered_links = array_filter(
  51. $extracted_links,
  52. [ $this->filter, 'internal_link_with_fragment_filter' ]
  53. );
  54. return $filtered_links;
  55. }
  56. /**
  57. * Builds the link.
  58. *
  59. * @param string $link The link to build.
  60. *
  61. * @return WPSEO_Link The built link.
  62. */
  63. public function build_link( $link ) {
  64. $link_type = $this->classifier->classify( $link );
  65. $target_post_id = 0;
  66. if ( $link_type === WPSEO_Link::TYPE_INTERNAL ) {
  67. $target_post_id = $this->internal_lookup->lookup( $link );
  68. }
  69. return self::get_link( $link, $target_post_id, $link_type );
  70. }
  71. /**
  72. * Returns the link object.
  73. *
  74. * @param string $url The URL of the link.
  75. * @param int $target_post_id The target post ID.
  76. * @param string $type The link type.
  77. *
  78. * @return WPSEO_Link Generated link object.
  79. */
  80. public static function get_link( $url, $target_post_id, $type ) {
  81. return new WPSEO_Link( $url, $target_post_id, $type );
  82. }
  83. }