Completed
Push — master ( 37f53e...78a185 )
by Werner
16:32
created

RootFolder::onBeforeDuplicate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 6
rs 9.4286
cc 2
eloc 3
nc 2
nop 1
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
    public function onAfterWrite()
32
    {
33
        if ($this->owner->ID) {
34
            $this->checkFolder();
35
        }
36
    }
37
38
    /**
39
     * reset $RootFolderID on a duplicated page
40
     */
41
    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...
42
    {
43
        if ($this->owner->ID == 0) {
44
            $this->owner->RootFolderID = 0;
45
        }
46
    }
47
48
    /**
49
     * Creates a folder for a page as a subfolder of the parent page
50
     * You can exclude page types by setting $ignored_classes in config
51
     *
52
     * Doesn't create folders for translated pages by default.
53
     *
54
     * @TODO doesn't check if page is moved to another parent
55
     */
56
    public function checkFolder()
57
    {
58
        $ignoredPageTypes = Config::inst()->get($this->class, 'ignored_classes');
59
60
        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...
61
            if (is_a($this->owner, $pagetype)) {
62
                return;
63
            }
64
        }
65
66
        if (class_exists('Translatable')
67
            && $this->owner->Locale !== Translatable::default_locale()
68
            && !Config::inst()->get($this->class, 'create_folder_for_translations')
69
        ) {
70
            return;
71
        }
72
73
        if (!$this->owner->RootFolderID) {
74
            $this->createRootFolder();
75
        } else {
76
            $this->updateRootFolder();
77
        }
78
    }
79
80
    /**
81
     * Does the work of creating a new RootFolder, saves the relation in the extended DataObject
82
     */
83
    protected function createRootFolder()
84
    {
85
        //get path to parent folder
86
        $parent = $this->owner->hasExtension('Hierarchy')
87
            ? $this->owner->getParent()
88
            : null;
89
        if (is_a($parent, 'Page') && $parentFolder = $parent->RootFolder()) {
90
            $folderRoot = $parent->getRootFolderName();
91
        } else {
92
            //fallback to classes folder_root which is defined in your config.yml
93
            $folderRoot = $this->getFolderRoot() . '/';
94
        }
95
96
        if ($folderRoot == '/') {
97
            $folderRoot = getFolderRoot() . '/';
98
        }
99
100
        $folder = Folder::find_or_make($folderRoot . $this->owner->URLSegment);
101
        $folder->Title = $this->owner->Title;
102
        $folder->setName($this->owner->URLSegment);
103
        $folder->write();
104
105
        $this->owner->RootFolderID = $folder->ID;
106
        $this->owner->write();
107
    }
108
109
    /**
110
     * Does the work of updating the folder if the URLSegment or ParentID is changed.
111
     * if both it does two writes...
112
     *
113
     * @todo: rethink moving subfolders as it may timeout on real large trees
114
     */
115
    protected function updateRootFolder()
116
    {
117
        $rootFolder = $this->owner->RootFolder();
118
        if ($this->owner->isChanged('URLSegment') && $this->owner->URLSegment) {
119
            $rootFolder->setName($this->owner->URLSegment);
120
            $rootFolder->write();
121
        }
122
123
        if ($this->owner->isChanged('ParentID') && $this->owner->ParentID > 0) {
124
            $oldParentID = $rootFolder->ParentID;
125
            $newParentID = $this->owner->Parent()->RootFolderID;
126
            if ($oldParentID !== $newParentID && $newParentID !== $rootFolder->ID) {
127
                $rootFolder->setParentID($newParentID);
128
                $rootFolder->write();
129
            }
130
        }
131
    }
132
133
    /**
134
     * Returns the folder root for the current root folder, e.g. 'Articles',
135
     * if a config $folder_root is defined in the decorated class.
136
     *
137
     * Falls back to global config
138
     */
139
    public function getFolderRoot()
140
    {
141
        return ($this->owner->config()->get('folder_root'))
142
            ? $this->owner->config()->get('folder_root')
143
            : Config::inst()->get($this->class, 'folder_root');
144
    }
145
146
147
    /**
148
     * Helper function to return the name of the RootFolder for setting in @link UploadField or @link GridFieldBulkUpload
149
     * By default relative to /assets/
150
     *
151
     * @param bool $relativeToAssetsDir
152
     */
153
    public function getRootFolderName($relativeToAssetsDir = true)
154
    {
155
        if ($this->owner->RootFolderID) {
156
            return $relativeToAssetsDir
157
                ? str_replace(ASSETS_DIR . '/', '', $this->owner->RootFolder()->getRelativePath())
158
                : $this->owner->RootFolder()->getRelativePath();
159
        } else {
160
            //use folder root as fallback for now
161
            return $this->getFolderRoot();
162
        }
163
    }
164
}
165