1<?php
2
3namespace ComboStrap\Meta\Field;
4
5use ComboStrap\ExceptionNotFound;
6use ComboStrap\FeaturedIcon;
7use ComboStrap\FirstImage;
8use ComboStrap\MarkupPath;
9use ComboStrap\Meta\Api\Metadata;
10use ComboStrap\Meta\Api\MetadataImage;
11use ComboStrap\PageImageTag;
12use ComboStrap\WikiPath;
13
14/**
15 * Retrieve the featured image of the ancestor
16 *
17 * Can be used in a {@link PageImageTag}
18 */
19class AncestorImage extends MetadataImage
20{
21
22
23    const PROPERTY_NAME = "ancestor-image";
24
25    public static function createFromResourcePage(MarkupPath $page): AncestorImage
26    {
27        return (new AncestorImage())->setResource($page);
28    }
29
30    static public function getDescription(): string
31    {
32        return "The featured image from the closest ancestor page";
33    }
34
35    static public function getLabel(): string
36    {
37        return "Ancestor Image";
38    }
39
40    public static function getName(): string
41    {
42        return self::PROPERTY_NAME;
43    }
44
45    static public function getPersistenceType(): string
46    {
47        return Metadata::DERIVED_METADATA;
48    }
49
50
51    static public function isMutable(): bool
52    {
53        return false;
54    }
55
56    /**
57     * Determination of the ancestore
58     * is really a question of taste.
59     *
60     * The algorithm goal is to find a relevant image.
61     *
62     * @return WikiPath
63     * @throws ExceptionNotFound
64     */
65    public function getValue(): WikiPath
66    {
67
68        $contextPage = $this->getResource();
69        $actual = $contextPage;
70        while (true) {
71            try {
72                $actual = $actual->getParent();
73            } catch (ExceptionNotFound $e) {
74                break;
75            }
76            try {
77                return FeaturedImage::createFromResourcePage($actual)->getValue();
78            } catch (ExceptionNotFound $e) {
79                // ok
80            }
81            try {
82                /**
83                 * If this is a index page,
84                 * the first image is generally a prominent image
85                 */
86                return FirstImage::createForPage($actual)->getValue();
87            } catch (ExceptionNotFound $e) {
88                // ok
89            }
90            try {
91                /**
92                 * The featured icon or the first icon parsed
93                 */
94                return FeaturedIcon::createForPage($actual)->getValueOrDefault();
95            } catch (ExceptionNotFound $e) {
96                // ok
97            }
98        }
99        throw new ExceptionNotFound();
100
101    }
102
103
104    static public function getDrive(): string
105    {
106        return WikiPath::MEDIA_DRIVE;
107    }
108
109
110    static public function isOnForm(): bool
111    {
112        return true;
113    }
114}
115