Completed
Push — master ( aa71cd...c3e146 )
by Andreas
21:52
created

datamanager::set_schema()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 7.8984

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 7
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 12
ccs 5
cts 8
cp 0.625
crap 7.8984
rs 9.2222
1
<?php
2
/**
3
 * @copyright CONTENT CONTROL GmbH, http://www.contentcontrol-berlin.de
4
 */
5
6
namespace midcom\datamanager;
7
8
use Symfony\Component\Form\FormFactoryBuilder;
9
use Symfony\Component\Form\Extension\Core\CoreExtension;
10
use midcom\datamanager\extension\extension;
11
use Symfony\Component\Form\Extension\Validator\ValidatorExtension;
12
use Symfony\Component\Validator\Validation;
13
use Symfony\Component\Form\FormFactoryInterface;
14
use Symfony\Component\Form\Form;
15
use midcom_core_dbaobject;
16
use midcom_core_context;
17
use midcom;
18
use Symfony\Component\Translation\Translator;
19
use Symfony\Component\Translation\Loader\XliffFileLoader;
20
use midcom\datamanager\extension\transformer\multipleTransformer;
21
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
22
use Symfony\Component\Security\Csrf\CsrfTokenManager;
23
use midcom\datamanager\storage\recreateable;
24
use midcom\datamanager\extension\type\schemaType;
25
use midcom\datamanager\extension\type\toolbarType;
26
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
27
use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
28
use midcom\datamanager\storage\container\container;
29
use midcom\datamanager\storage\container\dbacontainer;
30
31
/**
32
 * Experimental datamanager class
33
 */
34
class datamanager
35
{
36
    private $schemadb;
37
38
    /**
39
     * @var schema
40
     */
41
    private $schema;
42
43
    /**
44
     * @var storage\container\container
45
     */
46
    private $storage;
47
48
    /**
49
     * @var array
50
     */
51
    private $defaults = [];
52
53
    /**
54
     * @var renderer
55
     */
56
    private $renderer;
57
58
    /**
59
     * @var FormFactoryInterface
60
     */
61
    private static $factory;
62
63
    /**
64
     * @var Form
65
     */
66
    private $form;
67
68 233
    public function __construct(schemadb $schemadb)
69
    {
70 233
        $this->schemadb = $schemadb;
71 233
    }
72
73 142
    private static function get_factory() : FormFactoryInterface
74
    {
75 142
        if (self::$factory === null) {
76 1
            $fb = new FormFactoryBuilder();
77
78 1
            $lang = midcom::get()->i18n->get_current_language();
79 1
            $translator = new Translator($lang);
80 1
            $translator->addLoader('xlf', new XliffFileLoader);
81
82 1
            $vb = Validation::createValidatorBuilder();
83 1
            self::add_translation_resource($translator, $vb);
84 1
            self::add_translation_resource($translator, $fb);
85
86 1
            $vb->setTranslator($translator);
87
88 1
            $session_storage = new SessionTokenStorage(midcom::get()->session);
89
90 1
            $fb->addExtension(new extension())
91 1
                ->addExtension(new CoreExtension())
92 1
                ->addExtension(new HttpFoundationExtension())
93 1
                ->addExtension(new CsrfExtension(new CsrfTokenManager(null, $session_storage), $translator))
94 1
                ->addExtension(new ValidatorExtension($vb->getValidator()));
95
96 1
            self::$factory = $fb->getFormFactory();
97
        }
98 142
        return self::$factory;
99
    }
100
101 1
    private static function add_translation_resource(Translator $translator, $object)
102
    {
103 1
        $rc = new \ReflectionClass($object);
104 1
        $path = dirname($rc->getFileName());
105 1
        $lang = $translator->getLocale();
106 1
        $translator->addResource('xlf', $path . '/Resources/translations/validators.' . $lang . '.xlf', $lang);
107 1
    }
108
109 79
    public static function from_schemadb($path) : self
110
    {
111 79
        return new static(schemadb::from_path($path));
112
    }
113
114 40
    public function set_defaults(array $defaults) : self
115
    {
116 40
        $this->defaults = $defaults;
117 40
        return $this;
118
    }
119
120
    /**
121
     * @param midcom_core_dbaobject $storage
122
     * @param string $schema
123
     */
124 228
    public function set_storage(midcom_core_dbaobject $storage = null, $schemaname = null) : self
125
    {
126 228
        if (   $schemaname === null
127 228
            && !empty($storage->id)) {
128 71
            $schemaname = $storage->get_parameter('midcom.helper.datamanager2', 'schema_name');
0 ignored issues
show
Bug introduced by
The method get_parameter() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

128
            /** @scrutinizer ignore-call */ 
129
            $schemaname = $storage->get_parameter('midcom.helper.datamanager2', 'schema_name');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
129
        }
130
131 228
        $this->set_schema($schemaname);
132
133 228
        $defaults = array_merge($this->schema->get_defaults(), $this->defaults);
134 228
        if ($storage === null) {
135 12
            $this->storage = new storage\container\nullcontainer($this->schema, $defaults);
136
        } else {
137 216
            $this->storage = new storage\container\dbacontainer($this->schema, $storage, $defaults);
138
        }
139
140 228
        if ($this->form !== null) {
141 1
            if ($this->form->isSubmitted()) {
142
                $this->form = null;
143
            } else {
144 1
                $this->form->setData($this->storage);
145
            }
146
        }
147
148 228
        return $this;
149
    }
150
151 228
    private function set_schema($name)
152
    {
153 228
        if ($name && !$this->schemadb->has($name)) {
154
            debug_add("Given schema name {$name} was not found, reverting to default.", MIDCOM_LOG_INFO);
155
            $name = null;
156
        }
157
158 228
        $schema = ($name) ? $this->schemadb->get($name) : $this->schemadb->get_first();
159 228
        if ($this->schema !== null && $this->schema->get_name() !== $schema->get_name()) {
160
            $this->form = null;
161
        }
162 228
        $this->schema = $schema;
163 228
    }
164
165
    /**
166
     * @param string $name
167
     */
168 220
    public function get_schema($name = null) : schema
169
    {
170 220
        if ($name) {
171 1
            return $this->schemadb->get($name);
172
        }
173 220
        if ($this->schema === null) {
174 11
            $this->set_schema($name);
175
        }
176 220
        return $this->schema;
177
    }
178
179 144
    public function get_storage() : container
180
    {
181 144
        if (!$this->storage) {
182 11
            $this->set_storage(null);
183
        }
184 144
        return $this->storage;
185
    }
186
187 139
    public function get_renderer($template = null, $skip_empty = false) : renderer
188
    {
189 139
        if ($this->renderer === null) {
190 139
            $this->renderer = new renderer(new engine);
191 139
            $this->renderer->set_l10n($this->schema->get_l10n());
192
        }
193 139
        if ($template) {
194 139
            if (is_string($template)) {
195 139
                $config = \midcom_baseclasses_components_configuration::get('midcom.datamanager', 'config');
196 139
                $templates = $config->get('templates');
197 139
                if (!array_key_exists($template, $templates)) {
198
                    throw new \midcom_error('Template ' . $template . ' not found in config');
199
                }
200 139
                $template = new $templates[$template]($this->renderer, $skip_empty);
201
            }
202 139
            $view = $this->get_form()->createView();
203 139
            $this->renderer->set_template($view, $template);
204
        }
205 139
        return $this->renderer;
206
    }
207
208
    /**
209
     * @param string $name
210
     */
211 102
    public function get_controller($name = null) : controller
212
    {
213 102
        return new controller($this, $name);
214
    }
215
216
    /**
217
     * @param string $name
218
     * @param boolean $reset
219
     */
220 142
    public function get_form($name = null, $reset = false) : Form
221
    {
222 142
        if ($reset) {
223
            $this->form = null;
224
        }
225 142
        if ($name == null) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $name of type null|string against null; this is ambiguous if the string can be empty. Consider using a strict comparison === instead.
Loading history...
226 141
            $name = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_COMPONENT);
227
            // Replace the dots in the component name with underscores
228 141
            $name = midcom::get()->componentloader->path_to_prefix($name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type false; however, parameter $path of midcom_helper__componentloader::path_to_prefix() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

228
            $name = midcom::get()->componentloader->path_to_prefix(/** @scrutinizer ignore-type */ $name);
Loading history...
229
        }
230 142
        if (!$name) {
231
            // Fallback for componentless operation
232 3
            $name = 'midcom_helper_datamanager2';
233
        }
234
235 142
        if (   $this->form === null
236 142
            || $this->form->getName() != $name) {
237
            $config = [
238 142
                'schema' => $this->get_schema()
239
            ];
240 142
            $builder = self::get_factory()->createNamedBuilder($name, schemaType::class, null, $config);
241 142
            $storage = $this->get_storage();
242
243
            $config = [
244 142
                'operations' => $this->schema->get('operations'),
245 142
                'index_method' => 'noindex',
246 142
                'is_create' => $storage instanceof dbacontainer && empty($storage->get_value()->id)
247
            ];
248
249 142
            $builder->add('form_toolbar', toolbarType::class, $config);
250
251 142
            $this->form = $builder->getForm()
252 142
                ->setData($storage);
253
        }
254 142
        return $this->form;
255
    }
256
257 10
    public function get_content_raw() : array
258
    {
259 10
        $ret = [];
260
261 10
        foreach ($this->storage as $field => $value)
262
        {
263 10
            $ret[$field] = $value->get_value();
264 10
            $config = $this->schema->get_field($field);
265 10
            if (!empty($config['type_config']['allow_multiple'])) {
266 1
                $transformer = new multipleTransformer($config);
267 1
                $ret[$field] = $transformer->transform($ret[$field]);
268
            }
269
        }
270
271 10
        return $ret;
272
    }
273
274 2
    public function get_content_csv() : array
275
    {
276 2
        $ret = [];
277
278 2
        $renderer = $this->get_renderer('csv');
279 2
        foreach ($renderer->get_view()->children as $name => $value) {
280 2
            if ($name == 'form_toolbar') {
281 2
                continue;
282
            }
283 2
            $ret[$name] = $renderer->widget($value);
284
        }
285
286 2
        return $ret;
287
    }
288
289 34
    public function get_content_html() : array
290
    {
291 34
        $ret = [];
292
293 34
        $renderer = $this->get_renderer('view');
294 34
        foreach ($renderer->get_view()->children as $name => $value) {
295 34
            if ($name == 'form_toolbar') {
296 34
                continue;
297
            }
298 34
            $ret[$name] = $renderer->widget($value);
299
        }
300 34
        return $ret;
301
    }
302
303 11
    public function display_view($skip_empty = false)
304
    {
305 11
        $renderer = $this->get_renderer('view', $skip_empty);
306 11
        echo $renderer->block($renderer->get_view(), 'form');
307 11
    }
308
309
    public function recreate() : bool
310
    {
311
        $ret = true;
312
        foreach ($this->storage as $field) {
313
            if (   $field instanceof recreateable
314
                && !$field->recreate()) {
315
                $ret = false;
316
            }
317
        }
318
        return $ret;
319
    }
320
}
321