Completed
Push — master ( 96e036...eed5cf )
by Ben
02:47
created

LineController::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 6
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Squanto\Manager\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use Thinktomorrow\Squanto\Domain\Line;
7
use Thinktomorrow\Squanto\Domain\LineKey;
8
use Thinktomorrow\Squanto\Domain\Page;
9
use Thinktomorrow\Squanto\Exceptions\InvalidLineKeyException;
10
use Thinktomorrow\Squanto\Services\CachedTranslationFile;
11
12
class LineController extends Controller
13
{
14
    /**
15
     * Create new line
16
     *
17
     * @param null $page_id
18
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
19
     */
20
    public function create($page_id = null)
21
    {
22
        // If pageid is passed, the first key (pagekey) is prefilled
23
        $page = $page_id ? Page::find($page_id) : null;
24
        $line = new Line();
25
        $available_locales = config('squanto.locales');
26
27
        return view('squanto::create', compact('page', 'line', 'available_locales'));
28
    }
29
30
    public function store(Request $request)
31
    {
32
        $this->validate($request, [
33
            'key' => 'required|min:3|max:100|unique:squanto_lines,key',
34
        ]);
35
36
        try {
37
            $linekey = new LineKey($request->get('key'));
38
39
            $page_is_created = !(Page::findByKey($linekey->getPageKey()));
40
41
            $line = Line::make($linekey->get());
42
            $this->saveValueTranslations($line, $request->get('trans'));
43
44
            $line->saveSuggestedType();
45
46
            $message = $line->key. ' translation line created!' . (($page_is_created) ? ' Since the '.$linekey->getPageKey(). ' page didn\'t exist, it was added as well' : null);
0 ignored issues
show
Documentation introduced by
The property key does not exist on object<Thinktomorrow\Squanto\Domain\Line>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
47
48
            // Rebuild the translations cache
49
            app(CachedTranslationFile::class)->delete()->write();
50
51
            return redirect()->route('squanto.edit', $line->page_id)->with('messages.success', $message);
0 ignored issues
show
Documentation introduced by
The property page_id does not exist on object<Thinktomorrow\Squanto\Domain\Line>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
52
        } catch (InvalidLineKeyException $e) {
53
            return redirect()->back()->withInput()->withErrors('Invalid format for key. Must contain at least one dot as divider of the page identifier and the key itself: e.g. foo.bar');
54
        }
55
56
        return redirect()->back()->withInput()->withErrors('The line could not be created due to an unknown error.');
0 ignored issues
show
Unused Code introduced by
return redirect()->back(...to an unknown error.'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
57
    }
58
59
    public function edit($id)
60
    {
61
        $available_locales = config('squanto.locales');
62
        $line = Line::find($id);
63
64
        return view('squanto::lines.edit', compact('line', 'available_locales'));
65
    }
66
67
    public function update(Request $request, $id)
68
    {
69
        $line = Line::find($id);
70
71
        $this->validate($request, [
72
            'key' => 'required|min:3|max:100|unique:squanto_lines,key,'.$line->id,
73
        ]);
74
75
        try {
76
            $line->key = $request->get('key'); // Note that the page connection will not get updated!
77
            $line->type = $request->get('type');
78
            $line->label = $request->get('label');
79
            $line->description = $request->get('description');
80
            $line->save();
81
            $this->saveValueTranslations($line, $request->get('trans'));
82
83
            $linekey = new LineKey($line->key);
84
            $page_is_created = !(Page::findByKey($linekey->getPageKey()));
85
86
            // TODO: alert developer that keys will need be be changed as well / or autosuggest this with easy CONFIRM TO CHANGE IN FOLLOWING FILES:
87
88
            $message = $line->key. ' translation line updated!' . (($page_is_created) ? ' Since the '.$linekey->getPageKey(). ' page didn\'t exist, it was added as well' : null);
89
90
            // Rebuild the translations cache
91
            app(CachedTranslationFile::class)->delete()->write();
92
93
            return redirect()->route('squanto.lines.edit', $line->id)->with('messages.success', $message);
94
        } catch (InvalidLineKeyException $e) {
95
            return redirect()->back()->withInput()->withErrors('Invalid format for key. Must contain at least one dot as divider of the page identifier and the key itself: e.g. foo.bar');
96
        }
97
98
        return redirect()->back()->withInput()->withErrors('The line could not be updated due to an unknown error.');
0 ignored issues
show
Unused Code introduced by
return redirect()->back(...to an unknown error.'); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
99
    }
100
101
    public function destroy($id)
102
    {
103
        $line = Line::findOrFail($id);
104
        $key = $line->key;
105
        $page = Page::find($line->page_id);
106
107
        $line->delete();
108
109
        // Rebuild the translations cache
110
        app(CachedTranslationFile::class)->delete()->write();
111
112
        // If page has no more lines, we delete it as well
113
        if ($page->lines()->count() < 1) {
114
            $page->delete();
115
            return redirect()->route('squanto.index')->with('messages.warning', 'Line '.$key.' is verwijderd');
116
        }
117
118
        return redirect()->route('squanto.edit', $page->id)->with('messages.warning', 'Line '.$key.' is verwijderd');
119
    }
120
121
    private function saveValueTranslations(Line $line, array $translations)
122
    {
123
        collect($translations)->map(function ($value, $locale) use ($line) {
124
125
            $value = squantoCleanupHTML($value);
126
127 View Code Duplication
            if (is_null($value) || "" === $value) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
128
                $line->removeValue($locale);
129
            } else {
130
                $line->saveValue($locale, $value);
131
            }
132
        });
133
    }
134
}
135