AddLinkToHasOneField   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
eloc 16
c 8
b 0
f 0
dl 0
loc 22
rs 10
wmc 6

1 Method

Rating   Name   Duplication   Size   Complexity  
A add_link() 0 20 6
1
<?php
2
3
namespace Sunnysideup\CMSNiceties\Api;
4
5
use SilverStripe\Forms\FormField;
6
use SilverStripe\ORM\DataObject;
7
use SilverStripe\ORM\FieldType\DBHTMLVarchar;
8
9
class AddLinkToHasOneField
10
{
11
    public static function add_link(FormField $field, DataObject $object)
12
    {
13
        $dbFieldNameWithID = $field->getName();
14
        $dbFieldName = substr((string) $dbFieldNameWithID, 0, -2);
15
        $options = $object->config()->get('has_one');
16
        $className = $options[$dbFieldName] ?? '';
17
        if ($className) {
18
            $linkedObject = $object->{$dbFieldName}();
19
            if ($linkedObject->canEdit()) {
20
                $link = '';
21
                $linkAsHtml = '';
22
                //@TODO: add other methods... see Sunnysideup\CmsEditLinkField\Forms\Fields\CMSEditLinkField
23
                if ($linkedObject->exists() && $linkedObject->hasMethod('CMSEditLink')) {
24
                    $link = $linkedObject->CMSEditLink();
25
                    $linkAsHtml = '
26
                        <a href="' . $link . '" style="text-decoration: none!important;">✎ edit ' . $linkedObject->getTitle() . '</a><br />';
27
                }
28
29
                if ($link) {
30
                    $field->setRightTitle(DBHTMLVarchar::create_field(DBHTMLVarchar::class, $linkAsHtml));
31
                }
32
            }
33
        }
34
    }
35
}
36