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