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