xref: /webtrees/app/Statistics/Google/ChartAge.php (revision f25fc0f929f69ab8124cf0cecde45e457db7574a)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 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\DB;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Statistics\Service\CenturyService;
25use Fisharebest\Webtrees\Tree;
26use Illuminate\Database\Query\Expression;
27use Illuminate\Database\Query\JoinClause;
28use Illuminate\Support\Collection;
29use stdClass;
30
31use function round;
32use function view;
33
34/**
35 * A chart showing the average age of individuals related to the death century.
36 */
37class ChartAge
38{
39    private Tree $tree;
40
41    private CenturyService $century_service;
42
43    /**
44     * @param CenturyService $century_service
45     * @param Tree           $tree
46     */
47    public function __construct(CenturyService $century_service, Tree $tree)
48    {
49        $this->century_service = $century_service;
50        $this->tree            = $tree;
51    }
52
53    /**
54     * Returns the related database records.
55     *
56     * @return Collection<array-key,stdClass>
57     */
58    private function queryRecords(): Collection
59    {
60        $prefix = DB::connection()->getTablePrefix();
61
62        return DB::table('individuals')
63            ->select([
64                new Expression('AVG(' . $prefix . 'death.d_julianday2 - ' . $prefix . 'birth.d_julianday1) / 365.25 AS age'),
65                new Expression('ROUND((' . $prefix . 'death.d_year + 49) / 100, 0) AS century'),
66                'i_sex AS sex'
67            ])
68            ->join('dates AS birth', static function (JoinClause $join): void {
69                $join
70                    ->on('birth.d_file', '=', 'i_file')
71                    ->on('birth.d_gid', '=', 'i_id');
72            })
73            ->join('dates AS death', static function (JoinClause $join): void {
74                $join
75                    ->on('death.d_file', '=', 'i_file')
76                    ->on('death.d_gid', '=', 'i_id');
77            })
78            ->where('i_file', '=', $this->tree->id())
79            ->where('birth.d_fact', '=', 'BIRT')
80            ->where('death.d_fact', '=', 'DEAT')
81            ->whereIn('birth.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
82            ->whereIn('death.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
83            ->whereColumn('death.d_julianday1', '>=', 'birth.d_julianday2')
84            ->where('birth.d_julianday2', '<>', 0)
85            ->groupBy(['century', 'sex'])
86            ->orderBy('century')
87            ->orderBy('sex')
88            ->get()
89            ->map(static fn(object $row): object => (object) [
90                'age'     => (float) $row->age,
91                'century' => (int) $row->century,
92                'sex'     => $row->sex,
93            ]);
94    }
95
96    /**
97     * General query on ages.
98     *
99     * @return string
100     */
101    public function chartAge(): string
102    {
103        $out = [];
104        foreach ($this->queryRecords() as $record) {
105            $out[$record->century][$record->sex] = $record->age;
106        }
107
108        $data = [
109            [
110                I18N::translate('Century'),
111                I18N::translate('Males'),
112                I18N::translate('Females'),
113                I18N::translate('Average age'),
114            ]
115        ];
116
117        foreach ($out as $century => $values) {
118            $female_age  = $values['F'] ?? 0;
119            $male_age    = $values['M'] ?? 0;
120            $average_age = ($female_age + $male_age) / 2.0;
121
122            $data[] = [
123                $this->century_service->centuryName($century),
124                round($male_age, 1),
125                round($female_age, 1),
126                round($average_age, 1),
127            ];
128        }
129
130        $chart_title   = I18N::translate('Average age related to death century');
131        $chart_options = [
132            'title' => $chart_title,
133            'subtitle' => I18N::translate('Average age at death'),
134            'vAxis' => [
135                'title' => I18N::translate('Age'),
136            ],
137            'hAxis' => [
138                'showTextEvery' => 1,
139                'slantedText'   => false,
140                'title'         => I18N::translate('Century'),
141            ],
142            'colors' => [
143                '#84beff',
144                '#ffd1dc',
145                '#ff0000',
146            ],
147        ];
148
149        return view('statistics/other/charts/combo', [
150            'data'          => $data,
151            'chart_options' => $chart_options,
152            'chart_title'   => $chart_title,
153            'language'      => I18N::languageTag(),
154        ]);
155    }
156}
157