3 namespace Drupal\layout_builder\SectionStorage;
5 use Drupal\layout_builder\Section;
8 * Provides a trait for storing sections on an object.
11 * Layout Builder is currently experimental and should only be leveraged by
12 * experimental modules and development releases of contributed modules.
13 * See https://www.drupal.org/core/experimental for more information.
15 trait SectionStorageTrait {
18 * Stores the information for all sections.
20 * Implementations of this method are expected to call array_values() to rekey
21 * the list of sections.
23 * @param \Drupal\layout_builder\Section[] $sections
24 * An array of section objects.
28 abstract protected function setSections(array $sections);
33 public function count() {
34 return count($this->getSections());
40 public function getSection($delta) {
41 if (!$this->hasSection($delta)) {
42 throw new \OutOfBoundsException(sprintf('Invalid delta "%s"', $delta));
45 return $this->getSections()[$delta];
49 * Sets the section for the given delta on the display.
52 * The delta of the section.
53 * @param \Drupal\layout_builder\Section $section
58 protected function setSection($delta, Section $section) {
59 $sections = $this->getSections();
60 $sections[$delta] = $section;
61 $this->setSections($sections);
68 public function appendSection(Section $section) {
69 $delta = $this->count();
71 $this->setSection($delta, $section);
78 public function insertSection($delta, Section $section) {
79 if ($this->hasSection($delta)) {
80 // @todo Use https://www.drupal.org/node/66183 once resolved.
81 $start = array_slice($this->getSections(), 0, $delta);
82 $end = array_slice($this->getSections(), $delta);
83 $this->setSections(array_merge($start, [$section], $end));
86 $this->appendSection($section);
94 public function removeSection($delta) {
95 $sections = $this->getSections();
96 unset($sections[$delta]);
97 $this->setSections($sections);
102 * Indicates if there is a section at the specified delta.
105 * The delta of the section.
108 * TRUE if there is a section for this delta, FALSE otherwise.
110 protected function hasSection($delta) {
111 return isset($this->getSections()[$delta]);
115 * Magic method: Implements a deep clone.
117 public function __clone() {
118 $sections = $this->getSections();
120 foreach ($sections as $delta => $item) {
121 $sections[$delta] = clone $item;
124 $this->setSections($sections);