xref: /webtrees/app/Statistics/Google/ChartAge.php (revision b11cdcd45131b1585d66693fab363cfeb18c51a4)
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\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;
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 function (object $row): object {
90                return (object) [
91                    'age'     => (float) $row->age,
92                    'century' => (int) $row->century,
93                    'sex'     => $row->sex,
94                ];
95            });
96    }
97
98    /**
99     * General query on ages.
100     *
101     * @return string
102     */
103    public function chartAge(): string
104    {
105        $out = [];
106        foreach ($this->queryRecords() as $record) {
107            $out[$record->century][$record->sex] = $record->age;
108        }
109
110        $data = [
111            [
112                I18N::translate('Century'),
113                I18N::translate('Males'),
114                I18N::translate('Females'),
115                I18N::translate('Average age'),
116            ]
117        ];
118
119        foreach ($out as $century => $values) {
120            $female_age  = $values['F'] ?? 0;
121            $male_age    = $values['M'] ?? 0;
122            $average_age = ($female_age + $male_age) / 2.0;
123
124            $data[] = [
125                $this->century_service->centuryName($century),
126                round($male_age, 1),
127                round($female_age, 1),
128                round($average_age, 1),
129            ];
130        }
131
132        $chart_title   = I18N::translate('Average age related to death century');
133        $chart_options = [
134            'title' => $chart_title,
135            'subtitle' => I18N::translate('Average age at death'),
136            'vAxis' => [
137                'title' => I18N::translate('Age'),
138            ],
139            'hAxis' => [
140                'showTextEvery' => 1,
141                'slantedText'   => false,
142                'title'         => I18N::translate('Century'),
143            ],
144            'colors' => [
145                '#84beff',
146                '#ffd1dc',
147                '#ff0000',
148            ],
149        ];
150
151        return view('statistics/other/charts/combo', [
152            'data'          => $data,
153            'chart_options' => $chart_options,
154            'chart_title'   => $chart_title,
155            'language'      => I18N::languageTag(),
156        ]);
157    }
158}
159