Completed
Push — master ( 09cc32...487230 )
by Maxime
05:30 queued 22s
created

SyncFlatten::flattenSyncedData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 0
dl 0
loc 21
ccs 0
cts 18
cp 0
crap 12
rs 9.584
c 0
b 0
f 0
1
<?php
2
3
namespace Distilleries\Contentful\Commands\Sync;
4
5
use stdClass;
6
use Exception;
7
use Illuminate\Console\Command;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Facades\DB;
10
use Distilleries\Contentful\Models\Locale;
11
use Symfony\Component\Console\Helper\ProgressBar;
12
use Distilleries\Contentful\Repositories\AssetsRepository;
13
use Distilleries\Contentful\Repositories\EntriesRepository;
14
15
class SyncFlatten extends Command
16
{
17
    use Traits\SyncTrait;
18
19
    /**
20
     * Number of entries to fetch per pagination.
21
     *
22
     * @var integer
23
     */
24
    const PER_BATCH = 50;
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    protected $signature = 'contentful:sync-flatten {--preview}';
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    protected $description = 'Map and persist previously synced Contentful data';
35
36
    /**
37
     * Assets repository instance.
38
     *
39
     * @var \Distilleries\Contentful\Repositories\AssetsRepository
40
     */
41
    protected $assets;
42
43
    /**
44
     * Entries repository instance.
45
     *
46
     * @var \Distilleries\Contentful\Repositories\EntriesRepository
47
     */
48
    protected $entries;
49
50
    /**
51
     * MapEntries command constructor.
52
     *
53
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
54
     */
55
    public function __construct()
56
    {
57
        parent::__construct();
58
59
        $this->assets = new AssetsRepository;
60
61
        $this->entries = new EntriesRepository;
62
    }
63
64
    /**
65
     * Execute the console command.
66
     *
67
     * @return void
68
     */
69
    public function handle()
70
    {
71
        $isPreview = $this->option('preview');
72
        if ($isPreview) {
73
            use_contentful_preview();
74
        }
75
76
        $dumpPath = $this->dumpSync($isPreview);
0 ignored issues
show
Documentation introduced by
$isPreview is of type string|array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
77
        $this->putSync($dumpPath, $isPreview,'mysql_sync');
0 ignored issues
show
Documentation introduced by
$isPreview is of type string|array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
78
79
        $this->switchToSyncDb();
80
        $this->line('Truncate Contentful related tables');
81
        $this->assets->truncateRelatedTables();
82
        $this->entries->truncateRelatedTables();
83
        $this->line('Map and persist synced data');
84
85
        try {
86
            $this->flattenSyncedData();
87
        } catch (Exception $e) {
88
            echo PHP_EOL;
89
            $this->error($e->getMessage());
90
            return;
91
        }
92
93
        $dumpPath = $this->dumpSync($isPreview,'mysql_sync');
0 ignored issues
show
Documentation introduced by
$isPreview is of type string|array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
94
        $this->putSync($dumpPath, $isPreview);
0 ignored issues
show
Documentation introduced by
$isPreview is of type string|array, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
95
    }
96
97
    /**
98
     * Map and persist synced data.
99
     *
100
     * @return void
101
     * @throws \Exception
102
     */
103
    private function flattenSyncedData()
104
    {
105
        $page = 1;
106
        $paginator = DB::table('sync_entries')->paginate(static::PER_BATCH, ['*'], 'page', $page);
107
        $locales = Locale::all();
108
109
        $bar = $this->createProgressBar($paginator->total());
110
        while ($paginator->isNotEmpty()) {
111
            foreach ($paginator->items() as $item) {
112
                $bar->setMessage('Map entry ID: ' . $item->contentful_id);
113
                $this->mapItemToContentfulModel($item,$locales);
0 ignored issues
show
Bug introduced by
It seems like $locales defined by \Distilleries\Contentful\Models\Locale::all() on line 107 can also be of type array<integer,object<Ill...base\Eloquent\Builder>>; however, Distilleries\Contentful\...ItemToContentfulModel() does only seem to accept object<Illuminate\Support\Collection>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
114
                $bar->advance();
115
            }
116
117
            $page++;
118
            $paginator = DB::table('sync_entries')->paginate(static::PER_BATCH, ['*'], 'page', $page);
119
        }
120
        $bar->finish();
121
122
        echo PHP_EOL;
123
    }
124
125
    /**
126
     * Create custom progress bar.
127
     *
128
     * @param  integer  $total
129
     * @return \Symfony\Component\Console\Helper\ProgressBar
130
     */
131
    private function createProgressBar(int $total): ProgressBar
132
    {
133
        $bar = $this->output->createProgressBar($total);
134
135
        $bar->setFormat("%message%" . PHP_EOL . " %current%/%max% [%bar%] %percent:3s%%");
136
137
        return $bar;
138
    }
139
140
    /**
141
     * Map and persist given sync_entries item.
142
     *
143
     * @param  \stdClass  $item
144
     * @param \Illuminate\Support\Collection $locales
145
     * @return void
146
     * @throws \Exception
147
     */
148
    private function mapItemToContentfulModel(stdClass $item, Collection $locales)
149
    {
150
        $entry = json_decode($item->payload, true);
151
152
        if ($item->contentful_type === 'asset') {
153
            $this->assets->toContentfulModel($entry,$locales);
154
        } else {
155
            $this->entries->toContentfulModel($entry,$locales);
156
        }
157
    }
158
}
159