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 |
||
| 25 | class SDK5 implements SocialNetworkPublisher |
||
| 26 | { |
||
| 27 | /** |
||
| 28 | * @var Facebook |
||
| 29 | */ |
||
| 30 | private $facebook; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @var string |
||
| 34 | */ |
||
| 35 | private $pageId; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * @param Facebook $facebook Ready to use instance of the Facebook PHP SDK |
||
| 39 | * @param string $pageId Identifier of the page, on which the status update will be published |
||
| 40 | */ |
||
| 41 | public function __construct(Facebook $facebook, string $pageId) |
||
| 46 | |||
| 47 | /** |
||
| 48 | * {@inheritdoc} |
||
| 49 | */ |
||
| 50 | public function canPublish(Message $message): bool |
||
| 55 | |||
| 56 | /** |
||
| 57 | * {@inheritdoc} |
||
| 58 | */ |
||
| 59 | View Code Duplication | public function publish(Message $message): bool |
|
| 60 | { |
||
| 61 | if (!$this->canPublish($message)) { |
||
| 62 | throw new MessageNotIntendedForPublisher(SocialNetwork::FACEBOOK); |
||
| 63 | } |
||
| 64 | |||
| 65 | try { |
||
| 66 | $publishPostEndpoint = '/' . $this->pageId. '/feed'; |
||
| 67 | $response = $this->facebook->post( |
||
| 68 | $publishPostEndpoint, |
||
| 69 | $this->prepareParams($message) |
||
| 70 | ); |
||
| 71 | $post = $response->getGraphNode(); |
||
| 72 | |||
| 73 | return isset($post['id']) ? !empty($post['id']) : false; |
||
| 74 | } catch (Throwable $t) { |
||
| 75 | throw new FailureWhenPublishingMessage($t); |
||
| 76 | } |
||
| 77 | } |
||
| 78 | |||
| 79 | /** |
||
| 80 | * @param Message $message |
||
| 81 | * @return array |
||
| 82 | */ |
||
| 83 | protected function prepareParams(Message $message): array |
||
| 104 | } |
||
| 105 |