Completed
Push — master ( 129f66...473e30 )
by Werner
12:18
created

RootFolder::getOrCreateURLSegment()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 27
rs 6.7273
cc 7
eloc 14
nc 8
nop 0
1
<?php
2
3
/**
4
 * Adds a RootFolder to a Page for using it as default upload folder for all related stuff.
5
 *
6
 *
7
 * @package FolderPerPage
8
 * @author Werner Krauß
9
 */
10
class RootFolder 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...
11
{
12
    private static $has_one = array(
0 ignored issues
show
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
        'RootFolder' => 'Folder',
14
    );
15
16
    /**
17
     * @var array exclude this page types and class names
18
     */
19
    private static $ignored_classes = array('VirtualPage', 'ErrorPage');
0 ignored issues
show
Unused Code introduced by
The property $ignored_classes is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
20
21
    /**
22
     * @var bool should folders be created for translated objects?
23
     */
24
    private static $create_folder_for_translations = false;
0 ignored issues
show
Unused Code introduced by
The property $create_folder_for_translations is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
25
26
    /**
27
     * @var string default root for all folders; may be overwritten in config of decorated class
28
     */
29
    private static $folder_root = 'Articles';
0 ignored issues
show
Unused Code introduced by
The property $folder_root is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
30
31
    /**
32
     * create folder and set relation
33
     */
34
    public function onBeforeWrite()
35
    {
36
            $this->checkFolder();
37
    }
38
39
    /**
40
     * check updates and rename folder if needed
41
     */
42
    public function onAfterWrite()
43
    {
44
            $this->checkFolder();
45
    }
46
47
    /**
48
     * reset $RootFolderID on a duplicated page
49
     */
50
    public function onBeforeDuplicate($originalOrClone)
0 ignored issues
show
Unused Code introduced by
The parameter $originalOrClone 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...
51
    {
52
        if ($this->owner->ID == 0) {
53
            $this->owner->RootFolderID = 0;
54
        }
55
    }
56
57
    /**
58
     * Creates a folder for a page as a subfolder of the parent page
59
     * You can exclude page types by setting $ignored_classes in config
60
     *
61
     * Doesn't create folders for translated pages by default.
62
     *
63
     * @TODO doesn't check if page is moved to another parent
64
     */
65
    public function checkFolder()
66
    {
67
        $ignoredPageTypes = Config::inst()->get($this->class, 'ignored_classes');
68
69
        foreach ($ignoredPageTypes as $pagetype) {
0 ignored issues
show
Bug introduced by
The expression $ignoredPageTypes of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
70
            if (is_a($this->owner, $pagetype)) {
71
                return;
72
            }
73
        }
74
75
        if (class_exists('Translatable')
76
            && $this->owner->Locale !== Translatable::default_locale()
77
            && !Config::inst()->get($this->class, 'create_folder_for_translations')
78
        ) {
79
            return;
80
        }
81
82
        if (!$this->owner->RootFolderID) {
83
            $this->createRootFolder();
84
        } else {
85
            $this->updateRootFolder();
86
        }
87
    }
88
89
    /**
90
     * Does the work of creating a new RootFolder, saves the relation in the extended DataObject
91
     */
92
    protected function createRootFolder()
93
    {
94
        //get path to parent folder
95
        $parent = $this->owner->hasExtension('Hierarchy')
96
            ? $this->owner->getParent()
97
            : null;
98
        if (is_a($parent, 'Page') && $parentFolder = $parent->RootFolder()) {
99
            $folderRoot = $parent->getRootFolderName();
100
        } else {
101
            //fallback to classes folder_root which is defined in your config.yml
102
            $folderRoot = $this->getFolderRoot() . '/';
103
        }
104
105
        if ($folderRoot == '/') {
106
            $folderRoot = getFolderRoot() . '/';
107
        }
108
109
        $folder = Folder::find_or_make($folderRoot . $this->getOrCreateURLSegment());
110
        $folder->Title = $this->owner->Title;
111
        $folder->setName($this->owner->URLSegment);
112
        $folder->write();
113
114
        $this->owner->RootFolderID = $folder->ID;
115
    }
116
117
    /**
118
     * Does the work of updating the folder if the URLSegment or ParentID is changed.
119
     * if both it does two writes...
120
     *
121
     * @todo: rethink moving subfolders as it may timeout on real large trees
122
     */
123
    protected function updateRootFolder()
124
    {
125
        $rootFolder = $this->owner->RootFolder();
126
        if ($this->owner->isChanged('URLSegment') && $this->owner->URLSegment) {
127
            $rootFolder->setName($this->owner->URLSegment);
128
            $rootFolder->write();
129
        }
130
131
        if ($this->owner->isChanged('ParentID') && $this->owner->ParentID > 0) {
132
            $oldParentID = $rootFolder->ParentID;
133
            $newParentID = $this->owner->Parent()->RootFolderID;
134
            if ($oldParentID !== $newParentID && $newParentID !== $rootFolder->ID) {
135
                $rootFolder->setParentID($newParentID);
136
                $rootFolder->write();
137
            }
138
        }
139
    }
140
141
    /**
142
     * Returns the folder root for the current root folder, e.g. 'Articles',
143
     * if a config $folder_root is defined in the decorated class.
144
     *
145
     * Falls back to global config
146
     */
147
    public function getFolderRoot()
148
    {
149
        return ($this->owner->config()->get('folder_root'))
150
            ? $this->owner->config()->get('folder_root')
151
            : Config::inst()->get($this->class, 'folder_root');
152
    }
153
154
155
    /**
156
     * Helper function to return the name of the RootFolder for setting in @link UploadField or @link GridFieldBulkUpload
157
     * By default relative to /assets/
158
     *
159
     * @param bool $relativeToAssetsDir
160
     */
161
    public function getRootFolderName($relativeToAssetsDir = true)
162
    {
163
        if ($this->owner->RootFolderID) {
164
            return $relativeToAssetsDir
165
                ? str_replace(ASSETS_DIR . '/', '', $this->owner->RootFolder()->getRelativePath())
166
                : $this->owner->RootFolder()->getRelativePath();
167
        } else {
168
            //use folder root as fallback for now
169
            return $this->getFolderRoot();
170
        }
171
    }
172
173
    /**
174
     * code taken from SiteTree::onBeforeWrite()
175
     *
176
     * we need $URLSegment already created and checked before there
177
     *
178
     * @return mixed
179
     */
180
    private function getOrCreateURLSegment()
181
    {
182
        // If there is no URLSegment set, generate one from Title
183
        if ((!$this->owner->URLSegment || $this->owner->URLSegment == 'new-page') && $this->owner->Title) {
184
            $this->owner->URLSegment = $this->owner->generateURLSegment($this->owner->Title);
185
        } else {
186
            if ($this->owner->isChanged('URLSegment', 2)) {
187
                // Do a strict check on change level, to avoid double encoding caused by
188
                // bogus changes through forceChange()
189
                $filter = URLSegmentFilter::create();
190
                $this->owner->URLSegment = $filter->filter($this->owner->URLSegment);
191
                // If after sanitising there is no URLSegment, give it a reasonable default
192
                if (!$this->owner->URLSegment) {
193
                    $this->owner->URLSegment = "page-$this->owner->ID";
194
                }
195
            }
196
        }
197
198
        // Ensure that this object has a non-conflicting URLSegment value.
199
        $count = 2;
200
        while (!$this->owner->validURLSegment()) {
201
            $this->owner->URLSegment = preg_replace('/-[0-9]+$/', null, $this->owner->URLSegment) . '-' . $count;
202
            $count++;
203
        }
204
205
        return $this->owner->URLSegment;
206
    }
207
}
208
209