Completed
Branch master (e8947e)
by Andreas
15:09
created

net_nemein_wiki_handler_create   C

Complexity

Total Complexity 20

Size/Duplication

Total Lines 208
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 19

Importance

Changes 0
Metric Value
dl 0
loc 208
rs 6.875
c 0
b 0
f 0
wmc 20
lcom 1
cbo 19

7 Methods

Rating   Name   Duplication   Size   Complexity  
A load_schemadb() 0 4 1
A get_schema_name() 0 4 1
A get_schema_defaults() 0 4 1
A dm2_create_callback() 0 18 2
C _check_unique_wikiword() 0 82 9
B _handler_create() 0 48 5
A save_callback() 0 9 1
1
<?php
2
/**
3
 * @package net.nemein.wiki
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
/**
10
 * Wikipage creation handler
11
 *
12
 * @package net.nemein.wiki
13
 */
14
class net_nemein_wiki_handler_create extends midcom_baseclasses_components_handler
1 ignored issue
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...
15
implements midcom_helper_datamanager2_interfaces_create
1 ignored issue
show
Coding Style introduced by
The implements keyword must be on the same line as the class name
Loading history...
16
{
17
    /**
18
     * Wiki word we're creating page for
19
     *
20
     * @var string
21
     */
22
    private $_wikiword = '';
23
24
    /**
25
     * The wikipage we're creating
26
     *
27
     * @var net_nemein_wiki_wikipage
28
     */
29
    private $_page = null;
30
31
    /**
32
     * The schema to use for the new page.
33
     *
34
     * @var string
35
     */
36
    private $_schema = 'default';
37
38
    public function load_schemadb()
39
    {
40
        return $this->_request_data['schemadb'];
41
    }
42
43
    public function get_schema_name()
44
    {
45
        return $this->_schema;
46
    }
47
48
    public function get_schema_defaults()
49
    {
50
        return array('title' => $this->_wikiword);
51
    }
52
53
    /**
54
     * DM2 creation callback, binds to the current content topic.
55
     */
56
    public function & dm2_create_callback (&$controller)
57
    {
58
        $this->_page = new net_nemein_wiki_wikipage();
59
        $this->_page->topic = $this->_topic->id;
60
        $this->_page->title = $this->_wikiword;
61
        $this->_page->author = midcom_connection::get_user();
62
63
        // We can clear the session now
64
        $this->_request_data['session']->remove('wikiword');
65
66
        if (! $this->_page->create())
67
        {
68
            debug_print_r('We operated on this object:', $this->_page);
69
            throw new midcom_error('Failed to create a new page. Last Midgard error was: '. midcom_connection::get_error_string());
70
        }
71
72
        return $this->_page;
73
    }
74
75
    private function _check_unique_wikiword($wikiword)
76
    {
77
        $resolver = new net_nemein_wiki_resolver($this->_topic->id);
78
        $resolved = $resolver->path_to_wikipage($wikiword, true, true);
79
80
        if (!empty($resolved['latest_parent']))
81
        {
82
            $to_node = $resolved['latest_parent'];
83
        }
84
        else
85
        {
86
            $to_node = $resolved['folder'];
87
        }
88
        switch (true)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing strstr($resolved['remaining_path'], '/') of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
89
        {
90
            case (strstr($resolved['remaining_path'], '/')):
91
                // One or more namespaces left, find first, create it and recurse
92
                $paths = explode('/', $resolved['remaining_path']);
93
                $folder_title = array_shift($paths);
94
                $topic = new midcom_db_topic();
95
                $topic->up = $to_node[MIDCOM_NAV_ID];
96
                $topic->extra = trim($folder_title);
97
                $topic->title = $topic->extra;
98
                $generator = midcom::get()->serviceloader->load('midcom_core_service_urlgenerator');
99
                $topic->name = $generator->from_string($folder_title);
100
                $topic->component = 'net.nemein.wiki';
101
                if (!$topic->create())
102
                {
103
                    throw new midcom_error("Could not create wiki namespace '{$folder_title}', last Midgard error was: " . midcom_connection::get_error_string());
104
                }
105
                // refresh
106
                $topic = new midcom_db_topic($topic->id);
107
108
                // See if we have article with same title in immediate parent
109
                $qb = net_nemein_wiki_wikipage::new_query_builder();
110
                $qb->add_constraint('title', '=', $folder_title);
111
                $qb->add_constraint('topic', '=', $topic->up);
112
                $results = $qb->execute();
113
114
                if (count($results) == 1)
115
                {
116
                    $article = $results[0];
117
                    $article->name = 'index';
118
                    $article->topic = $topic->id;
119
                    if (!$article->update())
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
120
                    {
121
                        // Could not move article, do something ?
122
                    }
123
                }
124
                else
125
                {
126
                    try
127
                    {
128
                        net_nemein_wiki_viewer::initialize_index_article($topic);
129
                    }
130
                    catch (midcom_error $e)
131
                    {
132
                        // Could not create index
133
                        $topic->delete();
134
                        throw $e;
135
                    }
136
                }
137
                // We have created a new topic, now recurse to create the rest of the path.
138
                return $this->_check_unique_wikiword($wikiword);
139
140
            case (is_object($resolved['wikipage'])):
141
                // Page exists
142
                throw new midcom_error('Wiki page with that name already exists.');
143
144
            default:
145
                // No more namespaces left, create the page to latest parent
146
                if ($to_node[MIDCOM_NAV_ID] != $this->_topic->id)
147
                {
148
                    // Last parent is not this topic, redirect there
149
                    $wikiword_url = rawurlencode($resolved['remaining_path']);
150
                    midcom::get()->relocate($to_node[MIDCOM_NAV_ABSOLUTEURL] . "create/{$this->_schema}?wikiword={$wikiword_url}");
151
                    // This will exit()
152
                }
153
                break;
154
        }
155
        return true;
156
    }
157
158
    /**
159
     * @param mixed $handler_id The ID of the handler.
160
     * @param array $args The argument list.
161
     * @param array &$data The local request data.
162
     */
163
    public function _handler_create($handler_id, array $args, array &$data)
0 ignored issues
show
Coding Style introduced by
_handler_create uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
164
    {
165
        // Initialize sessioning first
166
        $data['session'] = new midcom_services_session();
167
168
        if (!array_key_exists('wikiword', $_GET))
169
        {
170
            if (!$data['session']->exists('wikiword'))
171
            {
172
                throw new midcom_error_notfound('No wiki word given');
173
            }
174
            $this->_wikiword = $data['session']->get('wikiword');
175
        }
176
        else
177
        {
178
            $this->_wikiword = $_GET['wikiword'];
179
            $data['session']->set('wikiword', $this->_wikiword);
180
        }
181
182
        $this->_topic->require_do('midgard:create');
183
184
        if ($handler_id == 'create_by_word_schema')
185
        {
186
            $this->_schema = $args[0];
187
        }
188
        else
189
        {
190
            $this->_schema = $this->_config->get('default_schema');
191
        }
192
193
        if (!array_key_exists($this->_schema, $data['schemadb']))
194
        {
195
            throw new midcom_error_notfound('Schema ' . $this->_schema . ' not found in schemadb');
196
        }
197
198
        $this->_check_unique_wikiword($this->_wikiword);
199
200
        $data['controller'] = $this->get_controller('create');
201
202
        midcom::get()->head->set_pagetitle(sprintf($this->_l10n->get('create wikipage %s'), $this->_wikiword));
203
204
        $workflow = $this->get_workflow('datamanager2', array
205
        (
206
            'controller' => $data['controller'],
207
            'save_callback' => array($this, 'save_callback')
208
        ));
209
        return $workflow->run();
210
    }
211
212
    public function save_callback(midcom_helper_datamanager2_controller $controller)
213
    {
214
        $indexer = midcom::get()->indexer;
215
        net_nemein_wiki_viewer::index($controller->datamanager, $indexer, $this->_topic);
216
217
        midcom::get()->uimessages->add($this->_l10n->get('net.nemein.wiki'), sprintf($this->_l10n->get('page %s added'), $this->_wikiword));
218
219
        return "{$this->_page->name}/";
220
    }
221
}
222