Skip to content

Commit

Permalink
abstract lazy array for cart presenter + improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
matthieu-rolland committed Jul 19, 2024
1 parent fd52627 commit eae4e98
Show file tree
Hide file tree
Showing 2 changed files with 696 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/Adapter/Presenter/AbstractLazyArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
*/
abstract class AbstractLazyArray implements Iterator, ArrayAccess, Countable, JsonSerializable
{
private const INDEX_NAME_PATTERN = '/@indexName\s+"([^"]+)"/';

/**
* @var ArrayObject
*/
Expand Down Expand Up @@ -94,11 +96,17 @@ public function __construct()
foreach ($methods as $method) {
$methodDoc = $method->getDocComment();
if (strpos($methodDoc, '@arrayAccess') !== false) {
if (preg_match(self::INDEX_NAME_PATTERN, $methodDoc, $matches)) {
$indexName = $matches[1];
} else {
$indexName = $this->convertMethodNameToIndex($method->getName());
}
$this->arrayAccessList->offsetSet(
$this->convertMethodNameToIndex($method->getName()),
$indexName,
[
'type' => 'method',
'value' => $method->getName(),
'isRewritable' => strpos($methodDoc, '@isRewritable') !== false,
]
);
}
Expand Down Expand Up @@ -391,15 +399,17 @@ public function intersectKey($array)
*/
public function offsetSet($offset, $value, $force = false): void
{
if (!$force && $this->arrayAccessList->offsetExists($offset)) {
if ($this->arrayAccessList->offsetExists($offset)) {
$result = $this->arrayAccessList->offsetGet($offset);
if ($result['type'] !== 'variable') {

if (!$force && $result['type'] !== 'variable' && !$result['isRewritable']) {
throw new RuntimeException('Trying to set the index ' . print_r($offset, true) . ' of the LazyArray ' . get_class($this) . ' already defined by a method is not allowed');
}
}
$this->arrayAccessList->offsetSet($offset, [
'type' => 'variable',
'value' => $value,
'isRewritable' => $result['isRewritable'] ?? false,
]);
}

Expand Down
Loading

0 comments on commit eae4e98

Please sign in to comment.