Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
17 | class ReferenceRemover { |
||
18 | |||
19 | private WikibaseApi $api; |
||
|
|||
20 | |||
21 | /** |
||
22 | * @param WikibaseApi $api |
||
23 | */ |
||
24 | public function __construct( WikibaseApi $api ) { |
||
25 | $this->api = $api; |
||
26 | } |
||
27 | |||
28 | /** |
||
29 | * @since 0.2 |
||
30 | * |
||
31 | * @param Reference|string $reference Reference object or hash |
||
32 | * @param Statement|StatementGuid|string $target Statement object or GUID |
||
33 | * @param EditInfo|null $editInfo |
||
34 | * |
||
35 | * @throws UnexpectedValueException |
||
36 | */ |
||
37 | public function set( $reference, $target, EditInfo $editInfo = null ): bool { |
||
38 | if ( $reference instanceof Reference ) { |
||
39 | $reference = $reference->getHash(); |
||
40 | } |
||
41 | if ( !is_string( $reference ) ) { |
||
42 | throw new UnexpectedValueException( 'Could not get reference hash from $reference' ); |
||
43 | } |
||
44 | |||
45 | if ( is_string( $target ) ) { |
||
46 | $guid = $target; |
||
47 | } elseif ( $target instanceof StatementGuid ) { |
||
48 | $guid = $target->getSerialization(); |
||
49 | } elseif ( $target instanceof Statement ) { |
||
50 | $guid = $target->getGuid(); |
||
51 | } else { |
||
52 | throw new UnexpectedValueException( 'Could not get statement guid from $target' ); |
||
53 | } |
||
54 | if ( !is_string( $guid ) ) { |
||
55 | throw new UnexpectedValueException( 'Unexpected statement guid got from $target' ); |
||
56 | } |
||
57 | |||
58 | $params = [ |
||
59 | 'statement' => $guid, |
||
60 | 'references' => $reference, |
||
61 | ]; |
||
62 | |||
63 | $this->api->postRequest( 'wbremovereferences', $params, $editInfo ); |
||
64 | return true; |
||
65 | } |
||
66 | |||
67 | } |
||
68 |