Completed
Push — master ( 780648...a93e4f )
by Daniel
06:19
created

AnchorSelectorField::anchors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace SilverStripe\CMS\Forms;
4
5
use Page;
6
use SilverStripe\Control\HTTPRequest;
7
use SilverStripe\Forms\TextField;
8
9
/**
10
 * Assists with selecting anchors on a given page
11
 */
12
class AnchorSelectorField extends TextField
13
{
14
    protected $schemaComponent = 'AnchorSelectorField';
15
16
    private static $allowed_actions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
17
        'anchors',
18
    ];
19
20
    private static $url_handlers = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
21
        'anchors/$PageID' => 'anchors',
22
    ];
23
24
    public function getSchemaDataDefaults()
25
    {
26
        $schema = parent::getSchemaDataDefaults();
27
        $schema['data']['endpoint'] = $this->Link('anchors/:id');
28
        return $schema;
29
    }
30
31
    /**
32
     * Find all anchors available on the given page.
33
     *
34
     * @param HTTPRequest $request
35
     * @return array
36
     */
37
    public function anchors(HTTPRequest $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
38
    {
39
        $id = (int)$this->getRequest()->param('PageID');
40
        $anchors = $this->getAnchorsInPage($id);
41
        return json_encode($anchors);
42
    }
43
44
    /**
45
     * Get anchors in the given page ID
46
     *
47
     * @param int $id
48
     * @return array
49
     */
50
    protected function getAnchorsInPage($id)
51
    {
52
        // Check page is accessible
53
        $page = Page::get()->byID($id);
54
        if (!$page || !$page->canView()) {
55
            return [];
56
        }
57
58
        // Similar to the regex found in HtmlEditorField.js / getAnchors method.
59
        $parseSuccess = preg_match_all(
60
            "/\\s+(name|id)\\s*=\\s*([\"'])([^\\2\\s>]*?)\\2|\\s+(name|id)\\s*=\\s*([^\"']+)[\\s +>]/im",
61
            $page->Content,
62
            $matches
63
        );
64
        if (!$parseSuccess) {
65
            return [];
66
        }
67
68
        // Cleanup results
69
        return array_values(array_unique(array_filter(array_merge($matches[3], $matches[5]))));
70
    }
71
}
72