xref: /webtrees/app/Statistics/Google/ChartMarriageAge.php (revision f25fc0f929f69ab8124cf0cecde45e457db7574a)
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', '>', new Expression($prefix . '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', '>', new Expression($prefix . '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 fn(object $row): object => (object) [
112                'age'     => (float) $row->age,
113                'century' => (int) $row->century,
114                'sex'     => $row->sex,
115            ]);
116    }
117
118    /**
119     * General query on ages at marriage.
120     *
121     * @return string
122     */
123    public function chartMarriageAge(): string
124    {
125        $out = [];
126
127        foreach ($this->queryRecords() as $record) {
128            $out[$record->century][$record->sex] = $record->age;
129        }
130
131        $data = [
132            [
133                I18N::translate('Century'),
134                I18N::translate('Males'),
135                I18N::translate('Females'),
136                I18N::translate('Average age'),
137            ]
138        ];
139
140        foreach ($out as $century => $values) {
141            $female_age  = $values['F'] ?? 0;
142            $male_age    = $values['M'] ?? 0;
143            $average_age = ($female_age + $male_age) / 2.0;
144
145            $data[] = [
146                $this->century_service->centuryName($century),
147                round($male_age, 1),
148                round($female_age, 1),
149                round($average_age, 1),
150            ];
151        }
152
153        $chart_title   = I18N::translate('Average age in century of marriage');
154        $chart_options = [
155            'title' => $chart_title,
156            'subtitle' => I18N::translate('Average age at marriage'),
157            'vAxis' => [
158                'title' => I18N::translate('Age'),
159            ],
160            'hAxis' => [
161                'showTextEvery' => 1,
162                'slantedText'   => false,
163                'title'         => I18N::translate('Century'),
164            ],
165            'colors' => [
166                '#84beff',
167                '#ffd1dc',
168                '#ff0000',
169            ],
170        ];
171
172        return view('statistics/other/charts/combo', [
173            'data'          => $data,
174            'chart_options' => $chart_options,
175            'chart_title'   => $chart_title,
176            'language'      => I18N::languageTag(),
177        ]);
178    }
179}
180