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