MetaTagFileExtension::onBeforeWrite()   F
last analyzed

Complexity

Conditions 29
Paths 363

Size

Total Lines 94
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 94
rs 3.4833
c 0
b 0
f 0
cc 29
eloc 69
nc 363
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * add functionality to files
5
 *
6
 *
7
 */
8
9
class MetaTagFileExtension extends DataExtension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
{
11
    private $stillNeedsToReplace = true;
12
13
    private $imageTrackingAddAgain = array();
14
15
    public function onBeforeWrite()
16
    {
17
        if ($this->stillNeedsToReplace && $this->owner instanceof Image && $this->owner->ID) {
18
            $this->stillNeedsToReplace = false;
19
            $oldObject = File::get()->byID($this->owner->ID);
20
            $oldFileName = "";
21
            if ($oldObject->Name) {
22
                $oldFileName = $oldObject->Name;
23
            }
24
            if ($oldFileName) {
25
                $oldPath = "";
26
                if (isset($oldObject->Filename)) {
27
                    $oldPath = $oldObject->Filename;
28
                }
29
                if (!$oldPath) {
30
                    $oldPath = $oldObject->getFilename();
31
                }
32
                $oldPath = str_replace($oldFileName, "", $oldPath);
33
                $newFileName = $this->owner->Name;
34
                $newPath = $this->owner->getRelativePath();
35
                $newPath = str_replace($newFileName, "", $newPath);
36
                if (($oldFileName != $newFileName) || ($oldPath != $oldPath)) {
37
                    $checks = MetaTagCMSControlFileUse::get()
38
                        ->filter(
39
                            array(
40
                                "ConnectionType" => "DB",
41
                                "IsLiveVersion" => "0"
42
                            )
43
                        );
44
                    $siteTreeItemsToChange = SiteTree::get()
45
                        ->where("\"SiteTree_ImageTracking\".\"FileID\" = ".$this->owner->ID)
46
                        ->innerJoin("SiteTree_ImageTracking", "\"SiteTree_ImageTracking\".\"SiteTreeID\" = \"SiteTree\".\"ID\"");
47
                    if ($siteTreeItemsToChange && $siteTreeItemsToChange->count()) {
48
                        foreach ($siteTreeItemsToChange as $siteTreeItemToChange) {
49
                            $trackings = $siteTreeItemToChange->ImageTracking();
50
                            if ($trackings && $trackings->count()) {
51
                                foreach ($trackings as $tracking) {
52
                                    $array = array(
53
                                        "DataObjectClassName" => "SiteTree",
54
                                        "DataObjectFieldName" => $tracking->FieldName,
55
                                        "FileID" => $tracking->ID,
56
                                        "TrackedID" => $siteTreeItemToChange->ID,
57
                                        "IsImageTracking" => true
58
                                    );
59
                                    $item = new ArrayData($array);
60
                                    $this->imageTrackingAddAgain[] = $array;
61
                                    $checks->push($item);
62
                                }
63
                            }
64
                        }
65
                    }
66
                    if ($checks && $checks->count()) {
67
                        foreach ($checks as $check) {
68
                            $className = $check->DataObjectClassName;
69
                            $fieldName = $check->DataObjectFieldName;
70
                            if (isset($check->IsImageTracking) && $check->IsImageTracking) {
71
                                $dosToChange = $className::get()->filter(array("ID" => $check->TrackedID));
72
                            } else {
73
                                $dosToChange = $className::get()->where("LOCATE('$oldFileName', \"".$fieldName."\") > 0");
74
                            }
75
                            if ($dosToChange && $dosToChange->count()) {
76
                                foreach ($dosToChange as $doToChange) {
77
                                    $dom = new DOMDocument;
78
                                    $dom->loadHTML('<?xml encoding="UTF-8">'.$doToChange->$fieldName);
79
                                    foreach ($dom->getElementsByTagName('img') as $node) {
80
                                        $oldSrc = $node->getAttribute('src');
81
                                        $newSrc = preg_replace('/'.str_replace("/", "\/", $oldPath).'(.*?)'.$oldFileName.'/', ''.$newPath.'$1'.$newFileName, $oldSrc);
82
                                        if ($oldSrc != $newSrc) {
83
                                            $oldFilePath = Director::baseFolder()."/".$oldSrc;
84
                                            $newFilePath = Director::baseFolder()."/".$newSrc;
85
                                            if (file_exists($oldFilePath) && !file_exists($newFilePath)) {
86
                                                rename($oldFilePath, $newFilePath);
87
                                            }
88
                                            $node->setAttribute('src', $newSrc);
89
                                        }
90
                                    }
91
                                    $doToChange->encoding = 'UTF-8';
92
                                    $doToChange->$fieldName = $dom->saveHTML();
93
                                    $data = preg_replace('/'.str_replace("/", "\/", $oldPath).'(.*?)'.$oldFileName.'/', ''.$newPath.'$1'.$newFileName, $doToChange->$fieldName);
0 ignored issues
show
Unused Code introduced by
$data is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
94
                                    //$this->owner->generateFormattedImage($format, $arg1, $arg2)
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
95
                                    if ($doToChange instanceof SiteTree) {
96
                                        $doToChange->writeToStage('Stage');
97
                                        $doToChange->publish('Stage', 'Live');
0 ignored issues
show
Bug introduced by
The method publish() does not exist on SiteTree. Did you maybe mean canPublish()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
98
                                    } else {
99
                                        $doToChange->write();
100
                                    }
101
                                }
102
                            }
103
                        }
104
                    }
105
                }
106
            }
107
        }
108
    }
109
110
    public function onAfterWrite()
111
    {
112
        if (is_array($this->imageTrackingAddAgain) && count($this->imageTrackingAddAgain)) {
113
            foreach ($this->imageTrackingAddAgain as $key => $array) {
114
                DB::query("
115
					INSERT IGNORE INTO  \"".$array["DataObjectClassName"]."_ImageTracking\" (
116
						\"ID\" ,
117
						\"SiteTreeID\" ,
118
						\"FileID\" ,
119
						\"FieldName\"
120
					)
121
					VALUES (
122
						NULL ,  '".$array["TrackedID"]."',  '".$array["FileID"]."',  '".$array["DataObjectFieldName"]."'
123
					);
124
				");
125
                unset($this->imageTrackingAddAgain[$key]);
126
            }
127
        }
128
    }
129
}
130