Template::apply()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace SoufieneSlimi\LaravelFormTemplate\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Session;
7
8
class Template extends Model
9
{
10
    protected $guarded = ['id'];
11
    protected $table = 'form_templates';
12
13
    /**
14
     * Apply a template
15
     *
16
     * @return \SoufieneSlimi\LaravelFormTemplate\Models\Template
17
     */
18
    public function apply()
19
    {
20
        if (! Session::has('_old_input')) {
21
            Session::now('_old_input', json_decode($this->form, true));
22
        }
23
    }
24
25
    /**
26
     * Create a new template using an array
27
     *
28
     * @param string $name the template name
29
     * @param array  $data the template data
30
     *
31
     * @return void
32
     */
33
    public static function make(string $name, array $data, $modelFqn = null)
34
    {
35
        return self::create([
36
            'name' => $name,
37
            'model_fqn' => $modelFqn,
38
            'form' => json_encode($data),
39
        ]);
40
    }
41
42
    /**
43
     * Create a new template using a model instance
44
     *
45
     * @param string                              $name                the template name
46
     * @param \Illuminate\Database\Eloquent\Model $model               the model to extract data from
47
     * @param array                               $extra               [optional] any extra data to save with this
48
     *                                                                 template
49
     * @param bool                                $withDefaultExcluded [optional] whether to remove some default data
50
     *                                                                 from the model or not
51
     *
52
     * @return \SoufieneSlimi\LaravelFormTemplate\Models\Template
53
     */
54
    public static function makeForModel(string $name, Model $model, array $extra = [], bool $withDefaultExcluded = true)
55
    {
56
        if ($withDefaultExcluded) {
57
            $excluded = config('laravel-form-template.excluded');
58
        }
59
60
        return self::make($name, array_merge($extra, $model->makeHidden(array_merge(
61
            $excluded ?? [],
62
            ['_token']
63
        ))->toArray()), get_class($model));
64
    }
65
}
66