Completed
Push — master ( 6a01eb...ed3330 )
by Ben
02:27
created

TranslationController::saveValueTranslations()   A

Complexity

Conditions 5
Paths 1

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5.0113

Importance

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