Projekt

Obecné

Profil

Stáhnout (12.6 KB) Statistiky
| Větev: | Tag: | Revize:
1
<?php
2

    
3

    
4
namespace App\AdminModule\Components;
5

    
6

    
7
use App\Enum\EFlashMessage;
8
use App\Enum\ESurfaceTypes;
9
use App\Model\Repository\BookRepository;
10
use App\Model\Repository\BookTypeRepository;
11
use App\Model\Repository\LineRepository;
12
use App\Model\Repository\MuseumRepository;
13
use App\Model\Repository\OriginRepository;
14
use App\Model\Repository\TransliterationRepository;
15
use App\Utils\DataGrid\DataGrid;
16
use Nette\Database\Table\ActiveRow;
17
use Nette\Database\Table\Selection;
18
use Tracy\Debugger;
19
use Ublaboo\DataGrid\Exception\DataGridException;
20

    
21
class TransliterationGrid extends DataGrid
22
{
23
    /**
24
     * @var TransliterationRepository
25
     */
26
    private $transliterationRepository;
27
    /**
28
     * @var BookRepository
29
     */
30
    private $bookRepository;
31
    /**
32
     * @var MuseumRepository
33
     */
34
    private $museumRepository;
35
    /**
36
     * @var OriginRepository
37
     */
38
    private $originRepository;
39
    /**
40
     * @var BookTypeRepository
41
     */
42
    private $bookTypeRepository;
43
    /**
44
     * @var LineRepository
45
     */
46
    private $lineRepository;
47

    
48
    const EXPORT_FILE_PATH = __DIR__ . '/../../../../temp/export/';
49
    const EXPORT_FILE_TYPE = '.txt';
50

    
51
    public function __construct(TransliterationRepository $transliterationRepository,
52
                                BookRepository $bookRepository,
53
                                MuseumRepository $museumRepository,
54
                                OriginRepository $originRepository,
55
                                BookTypeRepository $bookTypeRepository,
56
                                LineRepository $lineRepository
57
    )
58
    {
59
        $this->transliterationRepository = $transliterationRepository;
60
        $this->bookRepository = $bookRepository;
61
        $this->museumRepository = $museumRepository;
62
        $this->originRepository = $originRepository;
63
        $this->bookTypeRepository = $bookTypeRepository;
64
        $this->lineRepository = $lineRepository;
65

    
66
        parent::__construct(FALSE);
67
    }
68

    
69
    /**
70
     * Abstraktní metoda, slouží k nastavení primárního klíče a nastavení datasource
71
     *  1. $this->setPrimaryKey();
72
     *  2. $this->setDataSource();
73
     *
74
     * @throws DataGridException
75
     */
76
    public function init()
77
    {
78
        $this->setPrimaryKey(TransliterationRepository::COLUMN_ID);
79
        $this->setDataSource($this->transliterationRepository->findAll());
80
    }
81

    
82
    /**
83
     * Definice sloupečků, akcí, vyhledávácích filtrů gridu
84
     *
85
     * @throws DataGridException
86
     */
87
    public function define()
88
    {
89
        $bookRepository = $this->bookRepository;
90
        $museumRepository = $this->museumRepository;
91

    
92
        // ==================
93
        // Definice sloupečků
94
        // ==================
95
        $this->addColumnNumber(TransliterationRepository::COLUMN_ID, 'ID')->setDefaultHide(TRUE);
96
        $this->addColumnLink(TransliterationRepository::COLUMN_BOOK_ID, 'Book')
97
            ->setRenderer(function (ActiveRow $activeRow)
98
            {
99
                return $this->getRenderer(
100
                    $activeRow,
101
                    BookRepository::TABLE_NAME,
102
                    BookRepository::COLUMN_ID,
103
                    BookRepository::COLUMN_BOOK_ABBREV,
104
                    TransliterationRepository::COLUMN_BOOK_ID,
105
                    'Book:edit'
106
                );
107
            });
108
        $this->addColumnNumber(TransliterationRepository::COLUMN_CHAPTER, 'Chapter');
109
        $this->addColumnLink(TransliterationRepository::COLUMN_MUSEUM_ID, 'Museum')
110
            ->setRenderer(function (ActiveRow $activeRow)
111
            {
112
                return $this->getRenderer(
113
                    $activeRow,
114
                    MuseumRepository::TABLE_NAME,
115
                    MuseumRepository::COLUMN_ID,
116
                    MuseumRepository::COLUMN_NAME,
117
                    TransliterationRepository::COLUMN_MUSEUM_ID,
118
                    'Museum:edit'
119
                );
120
            });
121
        $this->addColumnText(TransliterationRepository::COLUMN_MUSEUM_NO, 'Museum No');
122
        $this->addColumnLink(TransliterationRepository::COLUMN_ORIGIN_ID, 'Origin')
123
            ->setRenderer(function (ActiveRow $activeRow)
124
            {
125
                return $this->getRenderer(
126
                    $activeRow,
127
                    OriginRepository::TABLE_NAME,
128
                    OriginRepository::COLUMN_ID,
129
                    OriginRepository::COLUMN_ORIGIN,
130
                    TransliterationRepository::COLUMN_ORIGIN_ID,
131
                    'Origin:edit'
132
                );
133
            });
134
        $this->addColumnLink(TransliterationRepository::COLUMN_BOOK_TYPE_ID, 'Book Type')
135
            ->setRenderer(function (ActiveRow $activeRow)
136
            {
137
                return $this->getRenderer(
138
                    $activeRow,
139
                    BookTypeRepository::TABLE_NAME,
140
                    BookTypeRepository::COLUMN_ID,
141
                    BookTypeRepository::COLUMN_BOOK_TYPE,
142
                    TransliterationRepository::COLUMN_BOOK_TYPE_ID,
143
                    'BookType:edit'
144
                );
145
            });
146
        $this->addColumnText(TransliterationRepository::COLUMN_REG_NO, 'Reg No');
147
        $this->addColumnText(TransliterationRepository::COLUMN_DATE, 'Date');
148

    
149
        // ===============
150
        // Definice filtrů
151
        // ===============
152
        $allFilter = ['' => 'All'];
153
        $this->addFilterText(TransliterationRepository::COLUMN_BOOK_ID, 'Book')
154
            ->setCondition(function (Selection $selection, $value) use ($bookRepository)
155
            {
156
                $bookIds = $bookRepository->getBooksLikeBookAbbrev($value)->fetchField(BookRepository::COLUMN_ID);
157
                $bookIds = $bookIds ? $bookIds : NULL;
158

    
159
                $selection->where(BookRepository::COLUMN_ID, $bookIds);
160
            });
161
        $this->addFilterText(TransliterationRepository::COLUMN_CHAPTER, 'Chapter');
162
        $this->addFilterSelect(TransliterationRepository::COLUMN_MUSEUM_ID, 'Museum', $allFilter + $this->museumRepository->getMuseumNameForSelect());
163
        $this->addFilterText(TransliterationRepository::COLUMN_MUSEUM_NO, 'Museum No');
164
        $this->addFilterSelect(TransliterationRepository::COLUMN_ORIGIN_ID, 'Origin', $allFilter + $this->getOriginFilterArray());
165
        $this->addFilterSelect(TransliterationRepository::COLUMN_BOOK_TYPE_ID, 'Book Type', $allFilter + $this->getBookTypeFilterArray());
166
        $this->addFilterText(TransliterationRepository::COLUMN_REG_NO, 'Reg No');
167
        $this->addFilterText(TransliterationRepository::COLUMN_DATE, 'Date');
168

    
169
        // Zakázání zobrazení všech položek, protože jinak se grid sekne a nelze resetovat
170
        $this->setItemsPerPageList([10, 20, 50, 100], FALSE);
171

    
172
        // =============
173
        // Definice akcí
174
        // =============
175
        $this->addAction('edit', 'edit', 'Transliteration:edit', ['id' => TransliterationRepository::COLUMN_ID])
176
            ->setTitle('Edit');
177

    
178
        $this->addAction('delete', 'delete', 'deleteTransliteration!', ['id' => TransliterationRepository::COLUMN_ID])
179
            ->setConfirm('Do you really want to delete transliteration?')
180
            ->setTitle('Delete')
181
            ->setClass('btn btn-xs btn-danger ajax');
182

    
183
        $this->addExportCallback(
184
            'Export data',
185
            function ($dataSource, $grid)
186
            {
187
                $this->exportData($dataSource, $grid);
188
            },
189
            TRUE);
190
    }
191

    
192
    /**
193
     * Vrací pole s možnostmi pro combobox filtr místa původu
194
     *
195
     * @return array
196
     */
197
    private function getOriginFilterArray()
198
    {
199
        $array = $this->originRepository->findAll()->order(OriginRepository::COLUMN_ORIGIN)->fetchPairs(OriginRepository::COLUMN_ID, OriginRepository::COLUMN_ORIGIN);
200
        return $array;
201
    }
202

    
203
    /**
204
     * Vrací pole s možnostmi pro combobox filtr typu knihy
205
     *
206
     * @return array
207
     */
208
    private function getBookTypeFilterArray()
209
    {
210
        $array = $this->bookTypeRepository->findAll()->order(BookTypeRepository::COLUMN_BOOK_TYPE)->fetchPairs(BookTypeRepository::COLUMN_ID, BookTypeRepository::COLUMN_BOOK_TYPE);
211
        return $array;
212
    }
213

    
214
    /**
215
     * Vrací renderer pro vlastní zobrazení názvu místo ID cizího klíče v gridu
216
     *
217
     * @param ActiveRow $activeRow
218
     * @param string $key
219
     * @param string $throughColumn
220
     * @param string $titleColumn
221
     * @param string $idColumn
222
     * @param string $destination
223
     * @return string
224
     * @throws \Nette\Application\UI\InvalidLinkException
225
     */
226
    private function getRenderer(ActiveRow $activeRow, string $key, string $throughColumn, string $titleColumn, string $idColumn, string $destination)
227
    {
228
        $ref = $activeRow->ref($key, $throughColumn);
229

    
230
        if ($ref)
231
        {
232
            $title = $ref->{$titleColumn};
233
            return $this->getRendererWithLink($activeRow, $title, $destination, $activeRow->{$idColumn});
234
        } else
235
        {
236
            return "";
237
        }
238
    }
239

    
240
    /**
241
     * @param $dataSource
242
     * @param DataGrid $grid
243
     */
244
    private function exportData($dataSource, $grid)
245
    {
246
        $exportData = [];
247

    
248
        try
249
        {
250
            /** @var ActiveRow $activeRow */
251
            foreach ($dataSource as $activeRow)
252
            {
253
                //Přeskočí transliterace které nejsou přiřazené k žádné knížce
254
                if(!$activeRow->ref('id_book'))
255
                {
256
                    continue;
257
                }
258
                $lines = $this->lineRepository->getAllLinesForTransliteration($activeRow->getPrimary());
259
                $chapterLines = [];
260
                foreach ($lines as $line)
261
                {
262
                    $chapterLines[$line->object_type][$line->surface_type][] = array('transliteration' => $line->transliteration, 'line_number' => $line->line_number);
263
                }
264
                $exportData[] = [
265
                    'bookName' => $activeRow->ref('id_book')->book_abrev,
266
                    'chapter' => $activeRow->chapter,
267
                    'transliterationData' => $chapterLines
268
                ];
269
            }
270

    
271
            $uniqueBooks = array_unique(array_map(function ($i) { return $i['bookName']; }, $exportData));
272

    
273
            $currentDate = new \DateTime();
274
            $exportFileName =  'text-export-' .
275
                $currentDate->format('Y-m-d-H-i-s') .
276
                self::EXPORT_FILE_TYPE;
277

    
278
            if (!file_exists(self::EXPORT_FILE_PATH)) {
279
                mkdir(self::EXPORT_FILE_PATH, 0777, true);
280
            }
281
            $exportFile = fopen(self::EXPORT_FILE_PATH . $exportFileName, 'w');
282
            foreach ($uniqueBooks as $book)
283
            {
284
                $bookData = [];
285
                foreach ($exportData as $data)
286
                {
287
                    if ($data['bookName'] == $book)
288
                    {
289
                        $bookData[] = $data;
290
                    }
291
                }
292
                fwrite($exportFile, "|" . $book . "\n");
293
                foreach ($bookData as $chapterData)
294
                {
295
                    fwrite($exportFile, "|" . $chapterData['chapter'] . "\n");
296
                    foreach ($chapterData['transliterationData'] as $surfaces)
297
                    {
298
                        foreach ($surfaces as $type => $surface)
299
                        {
300
                            for ($i = 0; $i < sizeof($surface); $i++)
301
                            {
302
                                $line =
303
                                    $surface[$i][LineRepository::COLUMN_LINE_NUMBER] .
304
                                    " " .
305
                                    $surface[$i][LineRepository::COLUMN_TRANSLITERATION];
306
                                if($i == 0 && $type != ESurfaceTypes::OBVERSE) {
307
                                    $line .= " " . ESurfaceTypes::getTypeAbbrevForExport($type);
308
                                }
309
                                fwrite($exportFile, $line . "\n");
310
                            }
311
                        }
312
                    }
313
                }
314
                fwrite($exportFile, "\n");
315
            }
316

    
317
            fclose($exportFile);
318
            header("Content-type: text/plain");
319
            header("Content-disposition: attachment; filename = " . $exportFileName);
320
            readfile(self::EXPORT_FILE_PATH . $exportFileName);
321
            die();
322
        }
323
        catch (\Exception $e)
324
        {
325
            $this->presenter->flashMessage('There was an error creating the export file', EFlashMessage::ERROR);
326
            Debugger::log($e, 'export-error');
327
        }
328

    
329
        $this->presenter->flashMessage('There was an error downloading the export file', EFlashMessage::ERROR);
330
    }
331
}
332

    
333
interface ITransliterationGridFactory
334
{
335
    /**
336
     * @return TransliterationGrid
337
     */
338
    public function create();
339
}
(5-5/7)