xref: /webtrees/app/Statistics/Google/ChartMarriageAge.php (revision 24931b29a0237a5f5f1b8620af661ea530451af0)
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 marriage ages by century.
36 */
37class ChartMarriageAge
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->tree            = $tree;
50        $this->century_service = $century_service;
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        $male = DB::table('dates as married')
63            ->select([
64                new Expression('AVG(' . $prefix . 'married.d_julianday2 - ' . $prefix . 'birth.d_julianday1 - 182.5) / 365.25 AS age'),
65                new Expression('ROUND((' . $prefix . 'married.d_year + 49) / 100, 0) AS century'),
66                new Expression("'M' as sex")
67            ])
68            ->join('families as fam', static function (JoinClause $join): void {
69                $join->on('fam.f_id', '=', 'married.d_gid')
70                    ->on('fam.f_file', '=', 'married.d_file');
71            })
72            ->join('dates as birth', static function (JoinClause $join): void {
73                $join->on('birth.d_gid', '=', 'fam.f_husb')
74                    ->on('birth.d_file', '=', 'fam.f_file');
75            })
76            ->whereIn('married.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
77            ->where('married.d_file', '=', $this->tree->id())
78            ->where('married.d_fact', '=', 'MARR')
79            ->where('married.d_julianday1', '>', 'birth.d_julianday1')
80            ->whereIn('birth.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
81            ->where('birth.d_fact', '=', 'BIRT')
82            ->where('birth.d_julianday1', '<>', 0)
83            ->groupBy(['century', 'sex']);
84
85        $female = DB::table('dates as married')
86            ->select([
87                new Expression('ROUND(AVG(' . $prefix . 'married.d_julianday2 - ' . $prefix . 'birth.d_julianday1 - 182.5) / 365.25, 1) AS age'),
88                new Expression('ROUND((' . $prefix . 'married.d_year + 49) / 100, 0) AS century'),
89                new Expression("'F' as sex")
90            ])
91            ->join('families as fam', static function (JoinClause $join): void {
92                $join->on('fam.f_id', '=', 'married.d_gid')
93                    ->on('fam.f_file', '=', 'married.d_file');
94            })
95            ->join('dates as birth', static function (JoinClause $join): void {
96                $join->on('birth.d_gid', '=', 'fam.f_wife')
97                    ->on('birth.d_file', '=', 'fam.f_file');
98            })
99            ->whereIn('married.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
100            ->where('married.d_file', '=', $this->tree->id())
101            ->where('married.d_fact', '=', 'MARR')
102            ->where('married.d_julianday1', '>', 'birth.d_julianday1')
103            ->whereIn('birth.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
104            ->where('birth.d_fact', '=', 'BIRT')
105            ->where('birth.d_julianday1', '<>', 0)
106            ->groupBy(['century', 'sex']);
107
108        return $male->unionAll($female)
109            ->orderBy('century')
110            ->get()
111            ->map(static function (object $row): object {
112                return (object) [
113                    'age'     => (float) $row->age,
114                    'century' => (int) $row->century,
115                    'sex'     => $row->sex,
116                ];
117            });
118    }
119
120    /**
121     * General query on ages at marriage.
122     *
123     * @return string
124     */
125    public function chartMarriageAge(): string
126    {
127        $out = [];
128
129        foreach ($this->queryRecords() as $record) {
130            $out[$record->century][$record->sex] = $record->age;
131        }
132
133        $data = [
134            [
135                I18N::translate('Century'),
136                I18N::translate('Males'),
137                I18N::translate('Females'),
138                I18N::translate('Average age'),
139            ]
140        ];
141
142        foreach ($out as $century => $values) {
143            $female_age  = $values['F'] ?? 0;
144            $male_age    = $values['M'] ?? 0;
145            $average_age = ($female_age + $male_age) / 2.0;
146
147            $data[] = [
148                $this->century_service->centuryName($century),
149                round($male_age, 1),
150                round($female_age, 1),
151                round($average_age, 1),
152            ];
153        }
154
155        $chart_title   = I18N::translate('Average age in century of marriage');
156        $chart_options = [
157            'title' => $chart_title,
158            'subtitle' => I18N::translate('Average age at marriage'),
159            'vAxis' => [
160                'title' => I18N::translate('Age'),
161            ],
162            'hAxis' => [
163                'showTextEvery' => 1,
164                'slantedText'   => false,
165                'title'         => I18N::translate('Century'),
166            ],
167            'colors' => [
168                '#84beff',
169                '#ffd1dc',
170                '#ff0000',
171            ],
172        ];
173
174        return view('statistics/other/charts/combo', [
175            'data'          => $data,
176            'chart_options' => $chart_options,
177            'chart_title'   => $chart_title,
178            'language'      => I18N::languageTag(),
179        ]);
180    }
181}
182