Passed
Branch main (b90ec4)
by Thierry
20:23 queued 14:04
created

CreateDefaultFunds::handle()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 14
nc 1
nop 0
dl 0
loc 25
rs 9.7998
c 1
b 0
f 0
1
<?php
2
3
namespace App\Console\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Facades\DB;
7
use Siak\Tontine\Model\Loan;
8
use Siak\Tontine\Model\Saving;
9
use Siak\Tontine\Model\Tontine;
10
11
class CreateDefaultFunds extends Command
12
{
13
    /**
14
     * The name and signature of the console command.
15
     *
16
     * @var string
17
     */
18
    protected $signature = 'fund:create-defaults';
19
20
    /**
21
     * The console command description.
22
     *
23
     * @var string
24
     */
25
    protected $description = 'Create a default savings fund for each tontine';
26
27
    /**
28
     * Execute the console command.
29
     *
30
      * @return int
31
     */
32
    public function handle()
33
    {
34
        DB::transaction(function() {
35
            foreach(Tontine::cursor() as $tontine)
36
            {
37
                // Create a default savings fund, if it doesn't exist yet.
38
                $fund = $tontine->funds()
39
                    ->withoutGlobalScope('user')
40
                    ->updateOrCreate(['title' => ''], ['active' => true]);
41
42
                // Update the savings and loans with the default fund id.
43
                Loan::whereNull('fund_id')
44
                    ->whereHas('member', function($query) use($tontine) {
45
                        $query->where('tontine_id', $tontine->id);
46
                    })
47
                    ->update(['fund_id' => $fund->id]);
48
                Saving::whereNull('fund_id')
49
                    ->whereHas('member', function($query) use($tontine) {
50
                        $query->where('tontine_id', $tontine->id);
51
                    })
52
                    ->update(['fund_id' => $fund->id]);
53
            }
54
        });
55
56
        return Command::SUCCESS;
57
    }
58
}
59