xref: /webtrees/app/Statistics/Google/ChartAge.php (revision f70bcff589628705e50ed72a6fc6cbad68558677)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Statistics\Google;
21
22use Fisharebest\Webtrees\I18N;
23use Fisharebest\Webtrees\Statistics\Service\CenturyService;
24use Fisharebest\Webtrees\Tree;
25use Illuminate\Database\Capsule\Manager as DB;
26use Illuminate\Database\Query\Expression;
27use Illuminate\Database\Query\JoinClause;
28use Illuminate\Support\Collection;
29
30/**
31 * A chart showing the average age of individuals related to the death century.
32 */
33class ChartAge
34{
35    /**
36     * @var Tree
37     */
38    private $tree;
39
40    /**
41     * @var CenturyService
42     */
43    private $century_service;
44
45    /**
46     * Constructor.
47     *
48     * @param Tree $tree
49     */
50    public function __construct(Tree $tree)
51    {
52        $this->tree            = $tree;
53        $this->century_service = new CenturyService();
54    }
55
56    /**
57     * Returns the related database records.
58     *
59     * @return Collection<object>
60     */
61    private function queryRecords(): Collection
62    {
63        $prefix = DB::connection()->getTablePrefix();
64
65        return DB::table('individuals')
66            ->select([
67                new Expression('AVG(' . $prefix . 'death.d_julianday2 - ' . $prefix . 'birth.d_julianday1) / 365.25 AS age'),
68                new Expression('ROUND((' . $prefix . 'death.d_year + 49) / 100) AS century'),
69                'i_sex AS sex'
70            ])
71            ->join('dates AS birth', static function (JoinClause $join): void {
72                $join
73                    ->on('birth.d_file', '=', 'i_file')
74                    ->on('birth.d_gid', '=', 'i_id');
75            })
76            ->join('dates AS death', static function (JoinClause $join): void {
77                $join
78                    ->on('death.d_file', '=', 'i_file')
79                    ->on('death.d_gid', '=', 'i_id');
80            })
81            ->where('i_file', '=', $this->tree->id())
82            ->where('birth.d_fact', '=', 'BIRT')
83            ->where('death.d_fact', '=', 'DEAT')
84            ->whereIn('birth.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
85            ->whereIn('death.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
86            ->whereColumn('death.d_julianday1', '>=', 'birth.d_julianday2')
87            ->where('birth.d_julianday2', '<>', 0)
88            ->groupBy(['century', 'sex'])
89            ->orderBy('century')
90            ->orderBy('sex')
91            ->get()
92            ->map(static function (object $row): object {
93                return (object) [
94                    'age'     => (float) $row->age,
95                    'century' => (int) $row->century,
96                    'sex'     => $row->sex,
97                ];
98            });
99    }
100
101    /**
102     * General query on ages.
103     *
104     * @return string
105     */
106    public function chartAge(): string
107    {
108        $out = [];
109        foreach ($this->queryRecords() as $record) {
110            $out[$record->century][$record->sex] = $record->age;
111        }
112
113        $data = [
114            [
115                I18N::translate('Century'),
116                I18N::translate('Males'),
117                I18N::translate('Females'),
118                I18N::translate('Average age'),
119            ]
120        ];
121
122        foreach ($out as $century => $values) {
123            $female_age  = $values['F'] ?? 0;
124            $male_age    = $values['M'] ?? 0;
125            $average_age = ($female_age + $male_age) / 2.0;
126
127            $data[] = [
128                $this->century_service->centuryName($century),
129                round($male_age, 1),
130                round($female_age, 1),
131                round($average_age, 1),
132            ];
133        }
134
135        $chart_title   = I18N::translate('Average age related to death century');
136        $chart_options = [
137            'title' => $chart_title,
138            'subtitle' => I18N::translate('Average age at death'),
139            'vAxis' => [
140                'title' => I18N::translate('Age'),
141            ],
142            'hAxis' => [
143                'title' => I18N::translate('Century'),
144            ],
145            'colors' => [
146                '#84beff',
147                '#ffd1dc',
148                '#ff0000',
149            ],
150        ];
151
152        return view('statistics/other/charts/combo', [
153            'data'          => $data,
154            'chart_options' => $chart_options,
155            'chart_title'   => $chart_title,
156            'language'      => I18N::languageTag(),
157        ]);
158    }
159}
160