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