/
Sections.php
1657 lines (1429 loc) · 55.1 KB
/
Sections.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\Element;
use craft\base\Field;
use craft\db\Query;
use craft\db\Table;
use craft\elements\Entry;
use craft\errors\EntryTypeNotFoundException;
use craft\errors\SectionNotFoundException;
use craft\events\ConfigEvent;
use craft\events\DeleteSiteEvent;
use craft\events\EntryTypeEvent;
use craft\events\FieldEvent;
use craft\events\SectionEvent;
use craft\helpers\ArrayHelper;
use craft\helpers\Db;
use craft\helpers\Json;
use craft\helpers\ProjectConfig as ProjectConfigHelper;
use craft\helpers\StringHelper;
use craft\models\EntryType;
use craft\models\FieldLayout;
use craft\models\Section;
use craft\models\Section_SiteSettings;
use craft\models\Structure;
use craft\queue\jobs\ResaveElements;
use craft\records\EntryType as EntryTypeRecord;
use craft\records\Section as SectionRecord;
use craft\records\Section_SiteSettings as Section_SiteSettingsRecord;
use yii\base\Component;
use yii\base\Exception;
/**
* Sections service.
* An instance of the Sections service is globally accessible in Craft via [[\craft\base\ApplicationTrait::getSections()|`Craft::$app->sections`]].
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0
*/
class Sections extends Component
{
// Constants
// =========================================================================
/**
* @event SectionEvent The event that is triggered before a section is saved.
*/
const EVENT_BEFORE_SAVE_SECTION = 'beforeSaveSection';
/**
* @event SectionEvent The event that is triggered after a section is saved.
*/
const EVENT_AFTER_SAVE_SECTION = 'afterSaveSection';
/**
* @event SectionEvent The event that is triggered before a section is deleted.
*/
const EVENT_BEFORE_DELETE_SECTION = 'beforeDeleteSection';
/**
* @event SectionEvent The event that is triggered before a section delete is applied to the database.
*/
const EVENT_BEFORE_APPLY_SECTION_DELETE = 'beforeApplySectionDelete';
/**
* @event SectionEvent The event that is triggered after a section is deleted.
*/
const EVENT_AFTER_DELETE_SECTION = 'afterDeleteSection';
/**
* @event EntryTypeEvent The event that is triggered before an entry type is saved.
*/
const EVENT_BEFORE_SAVE_ENTRY_TYPE = 'beforeSaveEntryType';
/**
* @event EntryTypeEvent The event that is triggered after an entry type is saved.
*/
const EVENT_AFTER_SAVE_ENTRY_TYPE = 'afterSaveEntryType';
/**
* @event EntryTypeEvent The event that is triggered before an entry type is deleted.
*/
const EVENT_BEFORE_DELETE_ENTRY_TYPE = 'beforeDeleteEntryType';
/**
* @event EntryTypeEvent The event that is triggered before an entry type delete is applied to the database.
*/
const EVENT_BEFORE_APPLY_ENTRY_TYPE_DELETE = 'beforeApplyEntryTypeDelete';
/**
* @event EntryTypeEvent The event that is triggered after an entry type is deleted.
*/
const EVENT_AFTER_DELETE_ENTRY_TYPE = 'afterDeleteEntryType';
const CONFIG_SECTIONS_KEY = 'sections';
const CONFIG_ENTRYTYPES_KEY = 'entryTypes';
// Properties
// =========================================================================
/**
* @var bool Whether entries should be resaved after a section or entry type has been updated.
*
* ::: warning
* Don’t disable this unless you know what you’re doing, as entries won’t reflect section/entry type changes until
* they’ve been resaved. (You can resave entries manually by running the `resave/entries` console command.)
* :::
*/
public $autoResaveEntries = true;
/**
* @var Section[]
*/
private $_sections;
/**
* @var
*/
private $_entryTypesById;
// Public Methods
// =========================================================================
// Sections
// -------------------------------------------------------------------------
/**
* Returns all of the section IDs.
*
* ---
*
* ```php
* $sectionIds = Craft::$app->sections->allSectionIds;
* ```
* ```twig
* {% set sectionIds = craft.app.sections.allSectionIds %}
* ```
*
* @return int[] All the sections’ IDs.
*/
public function getAllSectionIds(): array
{
return ArrayHelper::getColumn($this->getAllSections(), 'id', false);
}
/**
* Returns all of the section IDs that are editable by the current user.
*
* ---
*
* ```php
* $sectionIds = Craft::$app->sections->editableSectionIds;
* ```
* ```twig
* {% set sectionIds = craft.app.sections.editableSectionIds %}
* ```
*
* @return int[] All the editable sections’ IDs.
*/
public function getEditableSectionIds(): array
{
return ArrayHelper::getColumn($this->getEditableSections(), 'id', false);
}
/**
* Returns all sections.
*
* ---
*
* ```php
* $sections = Craft::$app->sections->allSections;
* ```
* ```twig
* {% set sections = craft.app.sections.allSections %}
* ```
*
* @return Section[] All the sections.
*/
public function getAllSections(): array
{
if ($this->_sections !== null) {
return $this->_sections;
}
$results = $this->_createSectionQuery()
->all();
$this->_sections = [];
foreach ($results as $result) {
if (!empty($result['previewTargets'])) {
$result['previewTargets'] = Json::decode($result['previewTargets']);
} else {
$result['previewTargets'] = [];
}
$this->_sections[] = new Section($result);
}
return $this->_sections;
}
/**
* Returns all editable sections.
*
* ---
*
* ```php
* $sections = Craft::$app->sections->editableSections;
* ```
* ```twig
* {% set sections = craft.app.sections.editableSections %}
* ```
*
* @return Section[] All the editable sections.
*/
public function getEditableSections(): array
{
$userSession = Craft::$app->getUser();
return ArrayHelper::where($this->getAllSections(), function(Section $section) use ($userSession) {
return $userSession->checkPermission('editEntries:' . $section->uid);
});
}
/**
* Returns all sections of a given type.
*
* ---
*
* ```php
* use craft\models\Section;
*
* $singles = Craft::$app->sections->getSectionsByType(Section::TYPE_SINGLE);
* ```
* ```twig
* {% set singles = craft.app.sections.getSectionsByType('single') %}
* ```
*
* @param string $type The section type (`single`, `channel`, or `structure`)
* @return Section[] All the sections of the given type.
*/
public function getSectionsByType(string $type): array
{
return ArrayHelper::where($this->getAllSections(), 'type', $type, true);
}
/**
* Gets the total number of sections.
*
* ---
*
* ```php
* $total = Craft::$app->sections->totalSections;
* ```
* ```twig
* {% set total = craft.app.sections.totalSections %}
* ```
*
* @return int
*/
public function getTotalSections(): int
{
return count($this->getAllSections());
}
/**
* Gets the total number of sections that are editable by the current user.
*
* ---
*
* ```php
* $total = Craft::$app->sections->totalEditableSections;
* ```
* ```twig
* {% set total = craft.app.sections.totalEditableSections %}
* ```
*
* @return int
*/
public function getTotalEditableSections(): int
{
return count($this->getEditableSections());
}
/**
* Returns a section by its ID.
*
* ---
*
* ```php
* $section = Craft::$app->sections->getSectionById(1);
* ```
* ```twig
* {% set section = craft.app.sections.getSectionById(1) %}
* ```
*
* @param int $sectionId
* @return Section|null
*/
public function getSectionById(int $sectionId)
{
return ArrayHelper::firstWhere($this->getAllSections(), 'id', $sectionId);
}
/**
* Gets a section by its UID.
*
* ---
*
* ```php
* $section = Craft::$app->sections->getSectionByUid('b3a9eef3-9444-4995-84e2-6dc6b60aebd2');
* ```
* ```twig
* {% set section = craft.app.sections.getSectionByUid('b3a9eef3-9444-4995-84e2-6dc6b60aebd2') %}
* ```
*
* @param string $uid
* @return Section|null
*/
public function getSectionByUid(string $uid)
{
return ArrayHelper::firstWhere($this->getAllSections(), 'uid', $uid);
}
/**
* Gets a section by its handle.
*
* ---
*
* ```php
* $section = Craft::$app->sections->getSectionByHandle('news');
* ```
* ```twig
* {% set section = craft.app.sections.getSectionByHandle('news') %}
* ```
*
* @param string $sectionHandle
* @return Section|null
*/
public function getSectionByHandle(string $sectionHandle)
{
return ArrayHelper::firstWhere($this->getAllSections(), 'handle', $sectionHandle);
}
/**
* Returns a section’s site-specific settings.
*
* @param int $sectionId
* @return Section_SiteSettings[] The section’s site-specific settings.
*/
public function getSectionSiteSettings(int $sectionId): array
{
$siteSettings = (new Query())
->select([
'sections_sites.id',
'sections_sites.sectionId',
'sections_sites.siteId',
'sections_sites.enabledByDefault',
'sections_sites.hasUrls',
'sections_sites.uriFormat',
'sections_sites.template',
])
->from(['{{%sections_sites}} sections_sites'])
->innerJoin('{{%sites}} sites', '[[sites.id]] = [[sections_sites.siteId]]')
->where(['sections_sites.sectionId' => $sectionId])
->orderBy(['sites.sortOrder' => SORT_ASC])
->all();
foreach ($siteSettings as $key => $value) {
$siteSettings[$key] = new Section_SiteSettings($value);
}
return $siteSettings;
}
/**
* Saves a section.
*
* ---
*
* ```php
* use craft\models\Section;
* use craft\models\Section_SiteSettings;
*
* $section = new Section([
* 'name' => 'News',
* 'handle' => 'news',
* 'type' => Section::TYPE_CHANNEL,
* 'siteSettings' => [
* new Section_SiteSettings([
* 'siteId' => Craft::$app->sites->getPrimarySite()->id,
* 'enabledByDefault' => true,
* 'hasUrls' => true,
* 'uriFormat' => 'foo/{slug}',
* 'template' => 'foo/_entry',
* ]),
* ]
* ]);
*
* $success = Craft::$app->sections->saveSection($section);
* ```
*
* @param Section $section The section to be saved
* @param bool $runValidation Whether the section should be validated
* @return bool
* @throws SectionNotFoundException if $section->id is invalid
* @throws \Throwable if reasons
*/
public function saveSection(Section $section, bool $runValidation = true): bool
{
$isNewSection = !$section->id;
// Fire a 'beforeSaveSection' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_SECTION)) {
$this->trigger(self::EVENT_BEFORE_SAVE_SECTION, new SectionEvent([
'section' => $section,
'isNew' => $isNewSection
]));
}
if ($runValidation && !$section->validate()) {
Craft::info('Section not saved due to validation error.', __METHOD__);
return false;
}
if ($isNewSection) {
$section->uid = StringHelper::UUID();
} else if (!$section->uid) {
$section->uid = Db::uidById(Table::SECTIONS, $section->id);
}
// Main section settings
if ($section->type === Section::TYPE_SINGLE) {
$section->propagationMethod = Section::PROPAGATION_METHOD_ALL;
}
// Assemble the section config
// -----------------------------------------------------------------
$projectConfig = Craft::$app->getProjectConfig();
$configData = [
'name' => $section->name,
'handle' => $section->handle,
'type' => $section->type,
'enableVersioning' => (bool)$section->enableVersioning,
'propagationMethod' => $section->propagationMethod,
'siteSettings' => [],
];
if (!empty($section->previewTargets)) {
$configData['previewTargets'] = $section->previewTargets;
}
if ($section->type === Section::TYPE_STRUCTURE) {
$sectionRecord = $this->_getSectionRecord($section->uid);
if ($sectionRecord->structureId) {
$structureUid = Db::uidById(Table::STRUCTURES, $sectionRecord->structureId);
} else {
$structureUid = StringHelper::UUID();
}
$configData['structure'] = [
'uid' => $structureUid,
'maxLevels' => (int)$section->maxLevels ?: null,
];
}
// Load the existing entry type info
if (!$isNewSection) {
$configData[self::CONFIG_ENTRYTYPES_KEY] = $projectConfig->get(self::CONFIG_SECTIONS_KEY . '.' . $section->uid . '.' . self::CONFIG_ENTRYTYPES_KEY);
}
// Get the site settings
$allSiteSettings = $section->getSiteSettings();
if (empty($allSiteSettings)) {
throw new Exception('Tried to save a section without any site settings');
}
foreach ($allSiteSettings as $siteId => $settings) {
$siteUid = Db::uidById(Table::SITES, $siteId);
$configData['siteSettings'][$siteUid] = [
'enabledByDefault' => (bool)$settings['enabledByDefault'],
'hasUrls' => (bool)$settings['hasUrls'],
'uriFormat' => $settings['uriFormat'],
'template' => $settings['template'],
];
}
// Do everything that follows in a transaction so no DB changes will be
// saved if an exception occurs that ends up preventing the project config
// changes from getting saved
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// Save the section config
// -----------------------------------------------------------------
$configPath = self::CONFIG_SECTIONS_KEY . '.' . $section->uid;
$projectConfig->set($configPath, $configData);
if ($isNewSection) {
$section->id = Db::idByUid(Table::SECTIONS, $section->uid);
}
// Make sure there's at least one entry type for this section
// -----------------------------------------------------------------
if (!$isNewSection) {
$entryTypeExists = (new Query())
->select(['id'])
->from([Table::ENTRYTYPES])
->where(['sectionId' => $section->id])
->exists();
} else {
$entryTypeExists = false;
}
if (!$entryTypeExists) {
$entryType = new EntryType();
$entryType->sectionId = $section->id;
$entryType->name = $section->name;
$entryType->handle = $section->handle;
if ($section->type === Section::TYPE_SINGLE) {
$entryType->hasTitleField = false;
$entryType->titleLabel = null;
$entryType->titleFormat = '{section.name|raw}';
} else {
$entryType->hasTitleField = true;
$entryType->titleLabel = Craft::t('app', 'Title');
$entryType->titleFormat = null;
}
$this->saveEntryType($entryType);
$section->setEntryTypes([$entryType]);
}
// Special handling for Single sections
// -----------------------------------------------------------------
if ($section->type === Section::TYPE_SINGLE) {
// Ensure & get the single entry
$entry = $this->_ensureSingleEntry($section, $configData['siteSettings']);
// Deal with the section's entry types
if (!$isNewSection) {
foreach ($this->getEntryTypesBySectionId($section->id) as $entryType) {
if ($entryType->id == $entry->typeId) {
// This is *the* entry's type. Make sure its name & handle match the section's
if (
($entryType->name !== ($entryType->name = $section->name)) ||
($entryType->handle !== ($entryType->handle = $section->handle))
) {
$this->saveEntryType($entryType);
}
$section->setEntryTypes([$entryType]);
} else {
// We don't need this one anymore
$this->deleteEntryType($entryType);
}
}
}
}
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
return true;
}
/**
* Handle section change
*
* @param ConfigEvent $event
*/
public function handleChangedSection(ConfigEvent $event)
{
ProjectConfigHelper::ensureAllSitesProcessed();
ProjectConfigHelper::ensureAllFieldsProcessed();
$sectionUid = $event->tokenMatches[0];
$data = $event->newValue;
$db = Craft::$app->getDb();
$transaction = $db->beginTransaction();
try {
$siteSettingData = $data['siteSettings'];
// Basic data
$sectionRecord = $this->_getSectionRecord($sectionUid, true);
$sectionRecord->uid = $sectionUid;
$sectionRecord->name = $data['name'];
$sectionRecord->handle = $data['handle'];
$sectionRecord->type = $data['type'];
$sectionRecord->enableVersioning = (bool)$data['enableVersioning'];
$sectionRecord->propagationMethod = $data['propagationMethod'] ?? Section::PROPAGATION_METHOD_ALL;
$sectionRecord->previewTargets = $data['previewTargets'] ?? null;
$isNewSection = $sectionRecord->getIsNewRecord();
if ($data['type'] === Section::TYPE_STRUCTURE) {
// Save the structure
$structureUid = $data['structure']['uid'];
$structure = Craft::$app->getStructures()->getStructureByUid($structureUid, true) ?? new Structure(['uid' => $structureUid]);
$isNewStructure = empty($structure->id);
$structure->maxLevels = $data['structure']['maxLevels'];
Craft::$app->getStructures()->saveStructure($structure);
$sectionRecord->structureId = $structure->id;
} else if (!$isNewSection && $sectionRecord->structureId) {
// Delete the old one
Craft::$app->getStructures()->deleteStructureById($sectionRecord->structureId);
$sectionRecord->structureId = null;
$isNewStructure = false;
}
$resaveEntries = (
$sectionRecord->handle !== $sectionRecord->getOldAttribute('handle') ||
$sectionRecord->type !== $sectionRecord->getOldAttribute('type') ||
$sectionRecord->propagationMethod != $sectionRecord->getOldAttribute('propagationMethod') ||
$sectionRecord->structureId != $sectionRecord->getOldAttribute('structureId')
);
if ($sectionRecord->dateDeleted) {
$sectionRecord->restore();
$resaveEntries = true;
} else {
$sectionRecord->save(false);
}
// Update the site settings
// -----------------------------------------------------------------
if (!$isNewSection) {
// Get the old section site settings
$allOldSiteSettingsRecords = Section_SiteSettingsRecord::find()
->where(['sectionId' => $sectionRecord->id])
->indexBy('siteId')
->all();
} else {
$allOldSiteSettingsRecords = [];
}
$siteIdMap = Db::idsByUids(Table::SITES, array_keys($siteSettingData));
foreach ($siteSettingData as $siteUid => $siteSettings) {
$siteId = $siteIdMap[$siteUid];
// Was this already selected?
if (!$isNewSection && isset($allOldSiteSettingsRecords[$siteId])) {
$siteSettingsRecord = $allOldSiteSettingsRecords[$siteId];
} else {
$siteSettingsRecord = new Section_SiteSettingsRecord();
$siteSettingsRecord->sectionId = $sectionRecord->id;
$siteSettingsRecord->siteId = $siteId;
$resaveEntries = true;
}
$siteSettingsRecord->enabledByDefault = $siteSettings['enabledByDefault'];
if ($siteSettingsRecord->hasUrls = $siteSettings['hasUrls']) {
$siteSettingsRecord->uriFormat = $siteSettings['uriFormat'];
$siteSettingsRecord->template = $siteSettings['template'];
} else {
$siteSettingsRecord->uriFormat = $siteSettings['uriFormat'] = null;
$siteSettingsRecord->template = $siteSettings['template'] = null;
}
$resaveEntries = (
$resaveEntries ||
$siteSettingsRecord->hasUrls != $siteSettingsRecord->getOldAttribute('hasUrls') ||
$siteSettingsRecord->uriFormat !== $siteSettingsRecord->getOldAttribute('uriFormat')
);
$siteSettingsRecord->save(false);
}
if (!$isNewSection) {
// Drop any sites that are no longer being used, as well as the associated entry/element site
// rows
$affectedSiteUids = array_keys($siteSettingData);
/** @noinspection PhpUndefinedVariableInspection */
foreach ($allOldSiteSettingsRecords as $siteId => $siteSettingsRecord) {
$siteUid = array_search($siteId, $siteIdMap, false);
if (!in_array($siteUid, $affectedSiteUids, false)) {
$siteSettingsRecord->delete();
$resaveEntries = true;
}
}
}
// If the section was just converted to a Structure,
// add the existing entries to the structure
// -----------------------------------------------------------------
if (
$sectionRecord->type === Section::TYPE_STRUCTURE &&
!$isNewSection &&
$isNewStructure
) {
$this->_populateNewStructure($sectionRecord);
}
// Finally, deal with the existing entries...
// -----------------------------------------------------------------
if (!$isNewSection && $resaveEntries && $this->autoResaveEntries) {
Craft::$app->getQueue()->push(new ResaveElements([
'description' => Craft::t('app', 'Resaving {section} entries', [
'section' => $sectionRecord->name,
]),
'elementType' => Entry::class,
'criteria' => [
'sectionId' => $sectionRecord->id,
'siteId' => '*',
'unique' => true,
'status' => null,
'enabledForSite' => false,
]
]));
}
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Clear caches
$this->_sections = null;
/** @var Section $section */
$section = $this->getSectionById($sectionRecord->id);
// If this is a Single and no entry type changes need to be processed,
// ensure that the section has its one and only entry
if (
!$isNewSection &&
$section->type === Section::TYPE_SINGLE &&
!Craft::$app->getProjectConfig()->areChangesPending($event->path . '.' . self::CONFIG_ENTRYTYPES_KEY)
) {
$this->_ensureSingleEntry($section, $siteSettingData);
}
// Fire an 'afterSaveSection' event
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_SECTION)) {
$this->trigger(self::EVENT_AFTER_SAVE_SECTION, new SectionEvent([
'section' => $section,
'isNew' => $isNewSection
]));
}
}
/**
* Deletes a section by its ID.
*
* ---
*
* ```php
* $success = Craft::$app->sections->deleteSectionById(1);
* ```
*
* @param int $sectionId
* @return bool Whether the section was deleted successfully
* @throws \Throwable if reasons
*/
public function deleteSectionById(int $sectionId): bool
{
$section = $this->getSectionById($sectionId);
if (!$section) {
return false;
}
return $this->deleteSection($section);
}
/**
* Deletes a section.
*
* ---
*
* ```php
* $success = Craft::$app->sections->deleteSection($section);
* ```
*
* @param Section $section
* @return bool Whether the section was deleted successfully
* @throws \Throwable if reasons
*/
public function deleteSection(Section $section): bool
{
// Fire a 'beforeDeleteSection' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_DELETE_SECTION)) {
$this->trigger(self::EVENT_BEFORE_DELETE_SECTION, new SectionEvent([
'section' => $section,
]));
}
// Delete the entry types first
$entryTypes = $this->getEntryTypesBySectionId($section->id);
foreach ($entryTypes as $entryType) {
$this->deleteEntryType($entryType);
}
// Remove the section from the project config
Craft::$app->getProjectConfig()->remove(self::CONFIG_SECTIONS_KEY . '.' . $section->uid);
return true;
}
/**
* Handle a section getting deleted
*
* @param ConfigEvent $event
*/
public function handleDeletedSection(ConfigEvent $event)
{
$uid = $event->tokenMatches[0];
$sectionRecord = $this->_getSectionRecord($uid);
if (!$sectionRecord->id) {
return;
}
/** @var Section $section */
$section = $this->getSectionById($sectionRecord->id);
// Fire a 'beforeApplySectionDelete' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_APPLY_SECTION_DELETE)) {
$this->trigger(self::EVENT_BEFORE_APPLY_SECTION_DELETE, new SectionEvent([
'section' => $section,
]));
}
$transaction = Craft::$app->getDb()->beginTransaction();
try {
// All entries *should* be deleted by now via their entry types, but loop through all the sites in case
// there are any lingering entries from unsupported sites
$entryQuery = Entry::find()
->anyStatus()
->sectionId($sectionRecord->id);
$elementsService = Craft::$app->getElements();
foreach (Craft::$app->getSites()->getAllSiteIds() as $siteId) {
foreach ($entryQuery->siteId($siteId)->each() as $entry) {
$elementsService->deleteElement($entry);
}
}
// Delete the structure
if ($sectionRecord->structureId) {
Craft::$app->getStructures()->deleteStructureById($sectionRecord->structureId);
}
// Delete the section
Craft::$app->getDb()->createCommand()
->softDelete(Table::SECTIONS, ['id' => $sectionRecord->id])
->execute();
$transaction->commit();
} catch (\Throwable $e) {
$transaction->rollBack();
throw $e;
}
// Clear caches
$this->_sections = null;
// Fire an 'afterDeleteSection' event
if ($this->hasEventHandlers(self::EVENT_AFTER_DELETE_SECTION)) {
$this->trigger(self::EVENT_AFTER_DELETE_SECTION, new SectionEvent([
'section' => $section,
]));
}
}
/**
* Prune a deleted site from section site settings.
*
* @param DeleteSiteEvent $event
*/
public function pruneDeletedSite(DeleteSiteEvent $event)
{
$siteUid = $event->site->uid;
$projectConfig = Craft::$app->getProjectConfig();
$sections = $projectConfig->get(self::CONFIG_SECTIONS_KEY);
// Loop through the sections and prune the UID from field layouts.
if (is_array($sections)) {
foreach ($sections as $sectionUid => $sectionGroup) {
$projectConfig->remove(self::CONFIG_SECTIONS_KEY . '.' . $sectionUid . '.siteSettings.' . $siteUid);
}
}
}
/**
* Prune a deleted field from entry type layouts.
*
* @param FieldEvent $event
*/
public function pruneDeletedField(FieldEvent $event)
{
/** @var Field $field */
$field = $event->field;
$fieldUid = $field->uid;
$projectConfig = Craft::$app->getProjectConfig();
$sections = $projectConfig->get(self::CONFIG_SECTIONS_KEY);
// Engage stealth mode
$projectConfig->muteEvents = true;
// Loop through the tag groups and prune the UID from field layouts.
if (is_array($sections)) {
foreach ($sections as $sectionUid => $section) {
if (!empty($section['entryTypes'])) {
foreach ($section['entryTypes'] as $entryTypeUid => $entryType) {
if (!empty($entryType['fieldLayouts'])) {
foreach ($entryType['fieldLayouts'] as $layoutUid => $layout) {
if (!empty($layout['tabs'])) {
foreach ($layout['tabs'] as $tabUid => $tab) {
$projectConfig->remove(self::CONFIG_SECTIONS_KEY . '.' . $sectionUid . '.' . self::CONFIG_ENTRYTYPES_KEY . '.' . $entryTypeUid . '.fieldLayouts.' . $layoutUid . '.tabs.' . $tabUid . '.fields.' . $fieldUid);
}
}
}
}
}
}
}
}
// Nuke all the layout fields from the DB
Craft::$app->getDb()->createCommand()->delete('{{%fieldlayoutfields}}', ['fieldId' => $field->id])->execute();
// Allow events again
$projectConfig->muteEvents = false;
}
/**
* Returns whether a section’s entries have URLs for the given site ID, and if the section’s template path is valid.
*
* @param Section $section
* @param int $siteId
* @return bool
*/
public function isSectionTemplateValid(Section $section, int $siteId): bool
{
$sectionSiteSettings = $section->getSiteSettings();
if (isset($sectionSiteSettings[$siteId]) && $sectionSiteSettings[$siteId]->hasUrls) {
// Set Craft to the site template mode
$view = Craft::$app->getView();
$oldTemplateMode = $view->getTemplateMode();
$view->setTemplateMode($view::TEMPLATE_MODE_SITE);
// Does the template exist?
$templateExists = Craft::$app->getView()->doesTemplateExist((string)$sectionSiteSettings[$siteId]->template);
// Restore the original template mode
$view->setTemplateMode($oldTemplateMode);
if ($templateExists) {
return true;
}
}
return false;
}
// Entry Types
// -------------------------------------------------------------------------
/**
* Returns a section’s entry types.
*
* ---
*
* ```php
* $entryTypes = Craft::$app->sections->getEntryTypesBySectionId(1);
* ```
*
* @param int $sectionId
* @return EntryType[]
*/
public function getEntryTypesBySectionId(int $sectionId): array