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

TranslationController::edit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 10
ccs 0
cts 7
cp 0
crap 2
rs 9.4285
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\Page;
8
use Thinktomorrow\Squanto\Services\CachedTranslationFile;
9
10
class TranslationController extends Controller
11
{
12
    public function index()
13
    {
14
        $pages = Page::sequence()->get();
0 ignored issues
show
Bug introduced by
The method sequence() does not exist on Thinktomorrow\Squanto\Domain\Page. Did you maybe mean scopeSequence()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
15
16
        return view('squanto::index', compact('pages'));
17
    }
18
19
    public function edit($id)
20
    {
21
        $available_locales = config('squanto.locales');
22
23
        $page = Page::find($id);
24
25
        $groupedLines = $this->groupLinesByKey($page);
26
27
        return view('squanto::edit', compact('page', 'available_locales', 'groupedLines'));
28
    }
29
30
    public function update(Request $request, $page_id)
31
    {
32
        $page = Page::find($page_id);
33
34
        $this->saveValueTranslations($request->get('trans'));
35
36
        // Rebuild the translations cache
37
        app(CachedTranslationFile::class)->delete()->write();
38
39
        return redirect()->route('squanto.edit', $page->id)->with('messages.success', $page->label .' translations have been updated');
40
    }
41
42
    private function saveValueTranslations(array $translations)
43
    {
44
        collect($translations)->map(function ($translation, $locale) {
45
            collect($translation)->map(function ($value, $id) use ($locale) {
46
47
                $line = Line::find($id);
48
49
                $value = squantoCleanupHTML($value);
50
51
                if(false == config('squanto.paragraphize') && !$line->areParagraphsAllowed())
52
                {
53
                    $value = $this->replaceParagraphsByLinebreaks($value);
54
                }
55
56
                // If line value is not meant to contain tags, we should strip them
57
                if (!$line->editInEditor()) {
58
                    $value = squantoCleanupString($value);
59
                }
60
61 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...
62
                    $line->removeValue($locale);
63
                } else {
64
                    $line->saveValue($locale, $value);
65
                }
66
            });
67
        });
68
    }
69
70
    /**
71
     * @param $page
72
     * @return \Illuminate\Support\Collection
73
     */
74
    private function groupLinesByKey($page)
75
    {
76
        $groupedLines = collect(['general' => []]);
77
        $groups = [];
78
79
        foreach ($page->lines as $line) {
80
            $keysegment = $this->getFirstSegmentOfKey($line);
81
82
            if (!isset($groups[$keysegment])) {
83
                $groups[$keysegment] = [];
84
            }
85
            $groups[$keysegment][] = $line;
86
        }
87
88
        // If firstkey occurs more than once, we will group it
89
        foreach ($groups as $group => $lines) {
90
            if (count($lines) < 2) {
91
                $groupedLines['general'] = array_merge($groupedLines['general'], $lines);
92
            } else {
93
                $groupedLines[$group] = $lines;
94
            }
95
        }
96
97
        return $groupedLines;
98
    }
99
100
    /**
101
     * Get suggestion for a label based on the key
102
     * e.g. foo.bar.title return bar
103
     * @return string
104
     */
105
    private function getFirstSegmentOfKey(Line $line)
106
    {
107
        // Remove first part since that part equals the page
108
        $key = substr($line->key, strpos($line->key, '.')+1);
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...
109
110
        $length = strpos($key, '.')?: strlen($key);
111
        $key = substr($key, 0, $length);
112
113
        return $key;
114
    }
115
116
    private function replaceParagraphsByLinebreaks($value)
117
    {
118
        $value = preg_replace('/<p[^>]*?>/', '', $value);
119
120
        // Last paragraph is just removed, not a linebreak
121
        if (substr($value, -mb_strlen('</p>')) === '</p>') {
122
            $value = substr($value, 0, -mb_strlen('</p>'));
123
        }
124
125
        $value = str_replace('</p>', '<br>', $value);
126
127
        return $value;
128
    }
129
}
130