| 1 |
<?php |
| 2 |
|
| 3 |
namespace PageImages\Hooks; |
| 4 |
|
| 5 |
use MediaWiki\Page\PageIdentity; |
| 6 |
use MediaWiki\Page\PageProps; |
| 7 |
use MediaWiki\Search\Hook\SearchResultProvideThumbnailHook; |
| 8 |
use MediaWiki\Search\SearchResultThumbnailProvider; |
| 9 |
use PageImages\PageImages; |
| 10 |
use RepoGroup; |
| 11 |
|
| 12 |
class SearchResultProvideThumbnailHookHandler implements SearchResultProvideThumbnailHook { |
| 13 |
|
| 14 |
|
| 15 |
private $thumbnailProvider; |
| 16 |
|
| 17 |
|
| 18 |
private $pageProps; |
| 19 |
|
| 20 |
|
| 21 |
private $repoGroup; |
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
public function __construct( |
| 29 |
SearchResultThumbnailProvider $thumbnailProvider, |
| 30 |
PageProps $pageProps, |
| 31 |
RepoGroup $repoGroup |
| 32 |
) { |
| 33 |
$this->thumbnailProvider = $thumbnailProvider; |
| 34 |
$this->pageProps = $pageProps; |
| 35 |
$this->repoGroup = $repoGroup; |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
private function getFileNamesByPageId( array $identitiesByPageId ): array { |
| 46 |
$nonFileIdentitiesByPageId = array_filter( |
| 47 |
$identitiesByPageId, |
| 48 |
static function ( PageIdentity $pageIdentity ) { |
| 49 |
return $pageIdentity->getNamespace() !== NS_FILE; |
| 50 |
} |
| 51 |
); |
| 52 |
|
| 53 |
$propValues = $this->pageProps->getProperties( |
| 54 |
$nonFileIdentitiesByPageId, |
| 55 |
|
| 56 |
(array)PageImages::getPropNames( PageImages::LICENSE_FREE ) |
| 57 |
); |
| 58 |
$fileNames = array_map( static function ( $prop ) { |
| 59 |
return $prop[ PageImages::getPropName( false ) ] |
| 60 |
?? $prop[ PageImages::getPropName( true ) ] |
| 61 |
?? null; |
| 62 |
}, $propValues ); |
| 63 |
|
| 64 |
return array_filter( $fileNames, static function ( $fileName ) { |
| 65 |
return $fileName !== null; |
| 66 |
} ); |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
public function onSearchResultProvideThumbnail( array $pageIdentities, &$results, ?int $size = null ): void { |
| 75 |
$fileNamesByPageId = $this->getFileNamesByPageId( $pageIdentities ); |
| 76 |
$results ??= []; |
| 77 |
foreach ( $fileNamesByPageId as $pageId => $fileName ) { |
| 78 |
$file = $this->repoGroup->findFile( $fileName ); |
| 79 |
if ( !$file ) { |
| 80 |
continue; |
| 81 |
} |
| 82 |
$thumbnail = $this->thumbnailProvider->buildSearchResultThumbnailFromFile( $file, $size ); |
| 83 |
if ( $thumbnail ) { |
| 84 |
$results[$pageId] = $thumbnail; |
| 85 |
} |
| 86 |
} |
| 87 |
} |
| 88 |
} |