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