Skip to content

Commit f7741c9

Browse files
committed
Remove reindexing feature from ReferenceList::addReference
1 parent e306e75 commit f7741c9

2 files changed

Lines changed: 29 additions & 7 deletions

File tree

src/ReferenceList.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,15 @@ public function addReference( Reference $reference, $index = null ) {
7171
return;
7272
}
7373

74+
$splHash = spl_object_hash( $reference );
75+
76+
if ( array_key_exists( $splHash, $this->references ) ) {
77+
return;
78+
}
79+
7480
if ( $index === null || $index >= count( $this->references ) ) {
7581
// Append object to the end of the reference list.
76-
$this->references[spl_object_hash( $reference )] = $reference;
82+
$this->references[$splHash] = $reference;
7783
} else {
7884
$this->insertReferenceAtIndex( $reference, $index );
7985
}
@@ -104,9 +110,11 @@ private function insertReferenceAtIndex( Reference $reference, $index ) {
104110
throw new InvalidArgumentException( '$index must be an integer' );
105111
}
106112

113+
$splHash = spl_object_hash( $reference );
114+
107115
$this->references = array_merge(
108116
array_slice( $this->references, 0, $index ),
109-
[ spl_object_hash( $reference ) => $reference ],
117+
[ $splHash => $reference ],
110118
array_slice( $this->references, $index )
111119
);
112120
}

tests/unit/ReferenceListTest.php

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -241,17 +241,31 @@ public function testAddReferenceAtIndexMovesIdenticalObjects() {
241241
$list->addNewReference( new PropertyNoValueSnak( 1 ) );
242242
$reference = new Reference( [ new PropertyNoValueSnak( 2 ) ] );
243243
$list->addReference( $reference );
244-
$this->assertSame( 1, $list->indexOf( $reference ), 'pre condition' );
244+
$list->addNewReference( new PropertyNoValueSnak( 3 ) );
245+
246+
$this->assertSame(
247+
1,
248+
$list->indexOf( $reference ),
249+
'pre-condition is that the element is at index 1'
250+
);
245251

246252
$list->addReference( $reference, 0 );
247253

248-
$this->assertCount( 2, $list, 'not added' );
249-
$this->assertSame( 0, $list->indexOf( $reference ), 'can decrease index' );
254+
$this->assertCount( 3, $list, 'not added' );
255+
$this->assertSame(
256+
1,
257+
$list->indexOf( $reference ),
258+
'make sure calling addReference with a lower index did not changed it'
259+
);
250260

251261
$list->addReference( $reference, 2 );
252262

253-
$this->assertCount( 2, $list, 'not added' );
254-
$this->assertSame( 0, $list->indexOf( $reference ), 'can not increase index' );
263+
$this->assertCount( 3, $list, 'not added' );
264+
$this->assertSame(
265+
1,
266+
$list->indexOf( $reference ),
267+
'make sure calling addReference with a higher index did not changed it'
268+
);
255269
}
256270

257271
public function testAddReferenceAtIndexZero() {

0 commit comments

Comments
 (0)