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