summaryrefslogtreecommitdiff
path: root/app/Statistics/Google/ChartDistribution.php
blob: fd09c6c9b7fe6b03149e33190f8b1417e47b766c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2019 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
declare(strict_types=1);

namespace Fisharebest\Webtrees\Statistics\Google;

use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Module\ModuleThemeInterface;
use Fisharebest\Webtrees\Statistics\Repository\IndividualRepository;
use Fisharebest\Webtrees\Statistics\Repository\PlaceRepository;
use Fisharebest\Webtrees\Statistics\Service\CountryService;
use Fisharebest\Webtrees\Tree;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Query\JoinClause;

/**
 * A chart showing the distribution of different events on a map.
 */
class ChartDistribution
{
    /**
     * @var Tree
     */
    private $tree;

    /**
     * @var ModuleThemeInterface
     */
    private $theme;

    /**
     * @var CountryService
     */
    private $country_service;

    /**
     * @var IndividualRepository
     */
    private $individualRepository;

    /**
     * @var PlaceRepository
     */
    private $placeRepository;

    /**
     * @var string[]
     */
    private $country_to_iso3166;

    /**
     * Constructor.
     *
     * @param Tree $tree
     */
    public function __construct(Tree $tree)
    {
        $this->tree                 = $tree;
        $this->theme                = app()->make(ModuleThemeInterface::class);
        $this->country_service      = new CountryService();
        $this->individualRepository = new IndividualRepository($tree);
        $this->placeRepository      = new PlaceRepository($tree);

        // Get the country names for each language
        $this->country_to_iso3166 = $this->getIso3166Countries();
    }

    /**
     * Returns the country names for each language.
     *
     * @return string[]
     */
    private function getIso3166Countries(): array
    {
        $countries = $this->country_service->getAllCountries();

        // Get the country names for each language
        $country_to_iso3166 = [];

        foreach (I18N::activeLocales() as $locale) {
            I18N::init($locale->languageTag());

            foreach ($this->country_service->iso3166() as $three => $two) {
                $country_to_iso3166[$three]             = $two;
                $country_to_iso3166[$countries[$three]] = $two;
            }
        }

        return $country_to_iso3166;
    }

    /**
     * Returns the data structure required by google geochart.
     *
     * @param array $places
     *
     * @return array
     */
    private function createChartData(array $places): array
    {
        $data = [
            [
                I18N::translate('Country'),
                I18N::translate('Total'),
            ],
        ];

        // webtrees uses 3 letter country codes and localised country names, but google uses 2 letter codes.
        foreach ($places as $country => $count) {
            $data[] = [
                [
                    'v' => $country,
                    'f' => $this->country_service->mapTwoLetterToName($country),
                ],
                $count
            ];
        }

        return $data;
    }

    /**
     * Returns the google geochart data for birth fact.
     *
     * @return array
     */
    private function getBirthChartData(): array
    {
        // Count how many people were born in each country
        $surn_countries = [];
        $b_countries    = $this->placeRepository->statsPlaces('INDI', 'BIRT', 0, true);

        foreach ($b_countries as $country => $count) {
            // Consolidate places (Germany, DEU => DE)
            if (\array_key_exists($country, $this->country_to_iso3166)) {
                $country_code = $this->country_to_iso3166[$country];

                if (\array_key_exists($country_code, $surn_countries)) {
                    $surn_countries[$country_code] += $count;
                } else {
                    $surn_countries[$country_code] = $count;
                }
            }
        }

        return $this->createChartData($surn_countries);
    }

    /**
     * Returns the google geochart data for death fact.
     *
     * @return array
     */
    private function getDeathChartData(): array
    {
        // Count how many people were death in each country
        $surn_countries = [];
        $d_countries    = $this->placeRepository->statsPlaces('INDI', 'DEAT', 0, true);

        foreach ($d_countries as $country => $count) {
            // Consolidate places (Germany, DEU => DE)
            if (\array_key_exists($country, $this->country_to_iso3166)) {
                $country_code = $this->country_to_iso3166[$country];

                if (\array_key_exists($country_code, $surn_countries)) {
                    $surn_countries[$country_code] += $count;
                } else {
                    $surn_countries[$country_code] = $count;
                }
            }
        }

        return $this->createChartData($surn_countries);
    }

    /**
     * Returns the google geochart data for marriages.
     *
     * @return array
     */
    private function getMarriageChartData(): array
    {
        // Count how many families got marriage in each country
        $surn_countries = [];
        $m_countries    = $this->placeRepository->statsPlaces('FAM');

        // webtrees uses 3 letter country codes and localised country names, but google uses 2 letter codes.
        foreach ($m_countries as $place) {
            // Consolidate places (Germany, DEU => DE)
            if (\array_key_exists($place->country, $this->country_to_iso3166)) {
                $country_code = $this->country_to_iso3166[$place->country];

                if (\array_key_exists($country_code, $surn_countries)) {
                    $surn_countries[$country_code] += $place->tot;
                } else {
                    $surn_countries[$country_code] = $place->tot;
                }
            }
        }

        return $this->createChartData($surn_countries);
    }

    /**
     * Returns the related database records.
     *
     * @param string $surname
     *
     * @return \stdClass[]
     */
    private function queryRecords(string $surname): array
    {
        $query = DB::table('individuals')
            ->select(['i_gedcom'])
            ->join('name', function (JoinClause $join): void {
                $join->on('n_id', '=', 'i_id')
                    ->on('n_file', '=', 'i_file');
            })
            ->where('n_file', '=', $this->tree->id())
            ->where(DB::raw('n_surn /*! COLLATE ' . I18N::collation() . ' */'), '=', $surname);

        return $query->get()->all();
    }

    /**
     * Returns the google geochart data for surnames.
     *
     * @param string $surname The surname used to create the chart
     *
     * @return array
     */
    private function getSurnameChartData(string $surname): array
    {
        if ($surname === '') {
            $surname = $this->individualRepository->getCommonSurname();
        }

        // Count how many people are events in each country
        $surn_countries = [];
        $records        = $this->queryRecords($surname);

        foreach ($records as $row) {
            /** @var string[][] $matches */
            if (preg_match_all('/^2 PLAC (?:.*, *)*(.*)/m', $row->i_gedcom, $matches)) {
                // webtrees uses 3 letter country codes and localised country names,
                // but google uses 2 letter codes.
                foreach ($matches[1] as $country) {
                    // Consolidate places (Germany, DEU => DE)
                    if (\array_key_exists($country, $this->country_to_iso3166)) {
                        $country_code = $this->country_to_iso3166[$country];

                        if (\array_key_exists($country_code, $surn_countries)) {
                            $surn_countries[$country_code]++;
                        } else {
                            $surn_countries[$country_code] = 1;
                        }
                    }
                }
            }
        }

        return $this->createChartData($surn_countries);
    }

    /**
     * Returns the google geochart data for individuals.
     *
     * @return array
     */
    private function getIndivdualChartData(): array
    {
        // Count how many people have events in each country
        $surn_countries = [];
        $a_countries    = $this->placeRepository->statsPlaces('INDI');

        // webtrees uses 3 letter country codes and localised country names, but google uses 2 letter codes.
        foreach ($a_countries as $place) {
            // Consolidate places (Germany, DEU => DE)
            if (\array_key_exists($place->country, $this->country_to_iso3166)) {
                $country_code = $this->country_to_iso3166[$place->country];

                if (\array_key_exists($country_code, $surn_countries)) {
                    $surn_countries[$country_code] += $place->tot;
                } else {
                    $surn_countries[$country_code] = $place->tot;
                }
            }
        }

        return $this->createChartData($surn_countries);
    }

    /**
     * Create a chart showing where events occurred.
     *
     * @param string $chart_shows The type of chart map to show
     * @param string $chart_type  The type of chart to show
     * @param string $surname     The surname for surname based distribution chart
     *
     * @return string
     */
    public function chartDistribution(
        string $chart_shows = 'world',
        string $chart_type  = '',
        string $surname     = ''
    ): string {
        I18N::init(WT_LOCALE);

        switch ($chart_type) {
            case 'surname_distribution_chart':
                $chart_title = I18N::translate('Surname distribution chart') . ': ' . $surname;
                $data        = $this->getSurnameChartData($surname);
                break;

            case 'birth_distribution_chart':
                $chart_title = I18N::translate('Birth by country');
                $data        = $this->getBirthChartData();
                break;

            case 'death_distribution_chart':
                $chart_title = I18N::translate('Death by country');
                $data        = $this->getDeathChartData();
                break;

            case 'marriage_distribution_chart':
                $chart_title = I18N::translate('Marriage by country');
                $data        = $this->getMarriageChartData();
                break;

            case 'indi_distribution_chart':
            default:
                $chart_title = I18N::translate('Individual distribution chart');
                $data        = $this->getIndivdualChartData();
                break;
        }

        $chart_color2 = $this->theme->parameter('distribution-chart-high-values');
        $chart_color3 = $this->theme->parameter('distribution-chart-low-values');

        return view(
            'statistics/other/charts/geo',
            [
                'chart_title'  => $chart_title,
                'chart_color2' => $chart_color2,
                'chart_color3' => $chart_color3,
                'region'       => $chart_shows,
                'data'         => $data,
            ]
        );
    }
}