Complex classes like Connector often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Connector, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 20 | class Connector implements ConnectorInterface |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * The official service URI; can be overridden via the constructor |
||
| 24 | * |
||
| 25 | * @var string |
||
| 26 | */ |
||
| 27 | const SERVICE_PRODUCTION_URL = 'https://api.communibase.nl/0.1/'; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * The API key which is to be used for the api. |
||
| 31 | * Is required to be set via the constructor. |
||
| 32 | * |
||
| 33 | * @var string |
||
| 34 | */ |
||
| 35 | private $apiKey; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * The url which is to be used for this connector. Defaults to the production url. |
||
| 39 | * Can be set via the constructor. |
||
| 40 | * |
||
| 41 | * @var string |
||
| 42 | */ |
||
| 43 | private $serviceUrl; |
||
| 44 | |||
| 45 | /** |
||
| 46 | * @var array of extra headers to send with each request |
||
| 47 | */ |
||
| 48 | private $extraHeaders = []; |
||
| 49 | |||
| 50 | /** |
||
| 51 | * @var QueryLogger |
||
| 52 | */ |
||
| 53 | private $logger; |
||
| 54 | |||
| 55 | /** |
||
| 56 | * @var ClientInterface |
||
| 57 | */ |
||
| 58 | private $client; |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Create a new Communibase Connector instance based on the given api-key and possible serviceUrl |
||
| 62 | * |
||
| 63 | * @param string $apiKey The API key for Communibase |
||
| 64 | * @param string $serviceUrl The Communibase API endpoint; defaults to self::SERVICE_PRODUCTION_URL |
||
| 65 | * @param ClientInterface $client An optional GuzzleHttp Client (or Interface for mocking) |
||
| 66 | */ |
||
| 67 | public function __construct( |
||
| 68 | $apiKey, |
||
| 69 | $serviceUrl = self::SERVICE_PRODUCTION_URL, |
||
| 70 | ClientInterface $client = null |
||
| 71 | ) { |
||
| 72 | $this->apiKey = $apiKey; |
||
| 73 | $this->serviceUrl = $serviceUrl; |
||
| 74 | $this->client = $client; |
||
| 75 | } |
||
| 76 | |||
| 77 | /** |
||
| 78 | * Returns an array that has all the fields according to the definition in Communibase. |
||
| 79 | * |
||
| 80 | * @param string $entityType |
||
| 81 | * |
||
| 82 | * @return array |
||
| 83 | * |
||
| 84 | * @throws Exception |
||
| 85 | */ |
||
| 86 | public function getTemplate($entityType) |
||
| 87 | { |
||
| 88 | $params = [ |
||
| 89 | 'fields' => 'attributes.title', |
||
| 90 | 'limit' => 1, |
||
| 91 | ]; |
||
| 92 | $definition = $this->search('EntityType', ['title' => $entityType], $params); |
||
| 93 | |||
| 94 | return array_fill_keys(array_merge(['_id'], array_column($definition[0]['attributes'], 'title')), null); |
||
| 95 | } |
||
| 96 | |||
| 97 | /** |
||
| 98 | * Get a single Entity by its id |
||
| 99 | * |
||
| 100 | * @param string $entityType |
||
| 101 | * @param string $id |
||
| 102 | * @param array $params (optional) |
||
| 103 | * |
||
| 104 | * @param string|null $version |
||
| 105 | * @return array entity |
||
| 106 | * |
||
| 107 | * @throws Exception |
||
| 108 | */ |
||
| 109 | public function getById($entityType, $id, array $params = [], $version = null) |
||
| 110 | { |
||
| 111 | if (empty($id)) { |
||
| 112 | throw new Exception('Id is empty'); |
||
| 113 | } |
||
| 114 | |||
| 115 | if (!static::isIdValid($id)) { |
||
| 116 | throw new Exception('Id is invalid, please use a correctly formatted id'); |
||
| 117 | } |
||
| 118 | |||
| 119 | return ($version === null) |
||
| 120 | ? $this->doGet($entityType . '.json/crud/' . $id, $params) |
||
| 121 | : $this->doGet($entityType . '.json/history/' . $id . '/' . $version, $params); |
||
| 122 | } |
||
| 123 | |||
| 124 | /** |
||
| 125 | * Get a single Entity by a ref-string |
||
| 126 | * |
||
| 127 | * @param array $ref |
||
| 128 | * @param array $parentEntity (optional) |
||
| 129 | * |
||
| 130 | * @return array the referred Entity data |
||
| 131 | * |
||
| 132 | * @throws Exception |
||
| 133 | */ |
||
| 134 | public function getByRef(array $ref, array $parentEntity = []) |
||
| 135 | { |
||
| 136 | if (strpos($ref['rootDocumentEntityType'], 'parent') !== false) { |
||
| 137 | // something with parent |
||
| 138 | throw new Exception('Not implemented (yet)'); |
||
| 139 | } |
||
| 140 | |||
| 141 | $document = $this->getById($ref['rootDocumentEntityType'], $ref['rootDocumentId']); |
||
| 142 | if (count($document) === 0) { |
||
| 143 | throw new Exception('Invalid document reference (document cannot be found by Id)'); |
||
| 144 | } |
||
| 145 | |||
| 146 | $container = $document; |
||
| 147 | foreach ($ref['path'] as $pathInDocument) { |
||
| 148 | if (!array_key_exists($pathInDocument['field'], $container)) { |
||
| 149 | throw new Exception('Could not find the path in document'); |
||
| 150 | } |
||
| 151 | $container = $container[$pathInDocument['field']]; |
||
| 152 | if (empty($pathInDocument['objectId'])) { |
||
| 153 | continue; |
||
| 154 | } |
||
| 155 | |||
| 156 | if (!is_array($container)) { |
||
| 157 | throw new Exception('Invalid value for path in document'); |
||
| 158 | } |
||
| 159 | $result = array_filter($container, function($item) use ($pathInDocument) { |
||
| 160 | return $item['_id'] === $pathInDocument['objectId']; |
||
| 161 | }); |
||
| 162 | if (count($result) === 0) { |
||
| 163 | throw new Exception('Empty result of reference'); |
||
| 164 | } |
||
| 165 | $container = reset($result); |
||
| 166 | } |
||
| 167 | return $container; |
||
| 168 | } |
||
| 169 | |||
| 170 | /** |
||
| 171 | * Get an array of entities by their ids |
||
| 172 | * |
||
| 173 | * @param string $entityType |
||
| 174 | * @param array $ids |
||
| 175 | * @param array $params (optional) |
||
| 176 | * |
||
| 177 | * @return array entities |
||
| 178 | */ |
||
| 179 | public function getByIds($entityType, array $ids, array $params = []) |
||
| 180 | { |
||
| 181 | $validIds = array_values(array_unique(array_filter($ids, ['Connector', 'isIdValid']))); |
||
| 182 | |||
| 183 | if (count($validIds) === 0) { |
||
| 184 | return []; |
||
| 185 | } |
||
| 186 | |||
| 187 | $doSortByIds = empty($params['sort']); |
||
| 188 | $results = $this->search($entityType, ['_id' => ['$in' => $validIds]], $params); |
||
| 189 | if (!$doSortByIds) { |
||
| 190 | return $results; |
||
| 191 | } |
||
| 192 | |||
| 193 | $flipped = array_flip($validIds); |
||
| 194 | foreach ($results as $result) { |
||
| 195 | $flipped[$result['_id']] = $result; |
||
| 196 | } |
||
| 197 | return array_filter(array_values($flipped), function ($result) { |
||
| 198 | return is_array($result) && !empty($result); |
||
| 199 | }); |
||
| 200 | |||
| 201 | } |
||
| 202 | |||
| 203 | /** |
||
| 204 | * Get all entities of a certain type |
||
| 205 | * |
||
| 206 | * @param string $entityType |
||
| 207 | * @param array $params (optional) |
||
| 208 | * |
||
| 209 | * @return array|null |
||
| 210 | */ |
||
| 211 | public function getAll($entityType, array $params = []) |
||
| 215 | |||
| 216 | /** |
||
| 217 | * Get result entityIds of a certain search |
||
| 218 | * |
||
| 219 | * @param string $entityType |
||
| 220 | * @param array $selector (optional) |
||
| 221 | * @param array $params (optional) |
||
| 222 | * |
||
| 223 | * @return array |
||
| 224 | */ |
||
| 225 | public function getIds($entityType, array $selector = [], array $params = []) |
||
| 231 | |||
| 232 | /** |
||
| 233 | * Get the id of an entity based on a search |
||
| 234 | * |
||
| 235 | * @param string $entityType i.e. Person |
||
| 236 | * @param array $selector (optional) i.e. ['firstName' => 'Henk'] |
||
| 237 | * |
||
| 238 | * @return array resultData |
||
| 239 | */ |
||
| 240 | public function getId($entityType, array $selector = []) |
||
| 247 | |||
| 248 | /** |
||
| 249 | * Call the aggregate endpoint with a given set of pipeline definitions: |
||
| 250 | * E.g. [ |
||
| 251 | * { "$match": { "_id": {"$ObjectId": "52f8fb85fae15e6d0806e7c7"} } }, |
||
| 252 | * { "$unwind": "$participants" }, |
||
| 253 | * { "$group": { "_id": "$_id", "participantCount": { "$sum": 1 } } } |
||
| 254 | * ] |
||
| 255 | * |
||
| 256 | * @see http://docs.mongodb.org/manual/core/aggregation-pipeline/ |
||
| 257 | * |
||
| 258 | * @param $entityType |
||
| 259 | * @param array $pipeline |
||
| 260 | * @return array |
||
| 261 | */ |
||
| 262 | public function aggregate($entityType, array $pipeline) |
||
| 266 | |||
| 267 | /** |
||
| 268 | * Returns an array of the history for the entity with the following format: |
||
| 269 | * |
||
| 270 | * <code> |
||
| 271 | * [ |
||
| 272 | * [ |
||
| 273 | * 'updatedBy' => '', // name of the user |
||
| 274 | * 'updatedAt' => '', // a string according to the DateTime::ISO8601 format |
||
| 275 | * '_id' => '', // the ID of the entity which can ge fetched seperately |
||
| 276 | * ], |
||
| 277 | * ... |
||
| 278 | * ] |
||
| 279 | * </code> |
||
| 280 | * |
||
| 281 | * @param string $entityType |
||
| 282 | * @param string $id |
||
| 283 | * |
||
| 284 | * @return array |
||
| 285 | * |
||
| 286 | * @throws Exception |
||
| 287 | */ |
||
| 288 | public function getHistory($entityType, $id) |
||
| 292 | |||
| 293 | /** |
||
| 294 | * Search for the given entity by optional passed selector/params |
||
| 295 | * |
||
| 296 | * @param string $entityType |
||
| 297 | * @param array $querySelector |
||
| 298 | * @param array $params (optional) |
||
| 299 | * |
||
| 300 | * @return array |
||
| 301 | * |
||
| 302 | * @throws Exception |
||
| 303 | */ |
||
| 304 | public function search($entityType, array $querySelector, array $params = []) |
||
| 308 | |||
| 309 | /** |
||
| 310 | * This will save an entity in Communibase. When a _id-field is found, this entity will be updated |
||
| 311 | * |
||
| 312 | * NOTE: When updating, depending on the Entity, you may need to include all fields. |
||
| 313 | * |
||
| 314 | * @param string $entityType |
||
| 315 | * @param array $properties - the to-be-saved entity data |
||
| 316 | * |
||
| 317 | * @returns array resultData |
||
| 318 | * |
||
| 319 | * @throws Exception |
||
| 320 | */ |
||
| 321 | public function update($entityType, array $properties) |
||
| 331 | |||
| 332 | /** |
||
| 333 | * Finalize an invoice by adding an invoiceNumber to it. |
||
| 334 | * Besides, invoice items will receive a 'generalLedgerAccountNumber'. |
||
| 335 | * This number will be unique and sequential within the 'daybook' of the invoice. |
||
| 336 | * |
||
| 337 | * NOTE: this is Invoice specific |
||
| 338 | * |
||
| 339 | * @param string $entityType |
||
| 340 | * @param string $id |
||
| 341 | * |
||
| 342 | * @return array |
||
| 343 | * |
||
| 344 | * @throws Exception |
||
| 345 | */ |
||
| 346 | public function finalize($entityType, $id) |
||
| 354 | |||
| 355 | /** |
||
| 356 | * Delete something from Communibase |
||
| 357 | * |
||
| 358 | * @param string $entityType |
||
| 359 | * @param string $id |
||
| 360 | * |
||
| 361 | * @return array resultData |
||
| 362 | */ |
||
| 363 | public function destroy($entityType, $id) |
||
| 367 | |||
| 368 | /** |
||
| 369 | * Get the binary contents of a file by its ID |
||
| 370 | * |
||
| 371 | * NOTE: for meta-data like filesize and mimetype, one can use the getById()-method. |
||
| 372 | * |
||
| 373 | * @param string $id id string for the file-entity |
||
| 374 | * |
||
| 375 | * @return StreamInterface Binary contents of the file. Since the stream can be made a string this works like a charm! |
||
| 376 | * |
||
| 377 | * @throws Exception |
||
| 378 | */ |
||
| 379 | public function getBinary($id) |
||
| 387 | |||
| 388 | /** |
||
| 389 | * Uploads the contents of the resource (this could be a file handle) to Communibase |
||
| 390 | * |
||
| 391 | * @param StreamInterface $resource |
||
| 392 | * @param string $name |
||
| 393 | * @param string $destinationPath |
||
| 394 | * @param string $id |
||
| 395 | * |
||
| 396 | * @return array|mixed |
||
| 397 | * @throws Exception |
||
| 398 | */ |
||
| 399 | public function updateBinary(StreamInterface $resource, $name, $destinationPath, $id = '') |
||
| 434 | |||
| 435 | /** |
||
| 436 | * @param string $path |
||
| 437 | * @param array $params |
||
| 438 | * @param array $data |
||
| 439 | * |
||
| 440 | * @return array |
||
| 441 | * |
||
| 442 | * @throws Exception |
||
| 443 | */ |
||
| 444 | protected function doGet($path, array $params = null, array $data = null) |
||
| 448 | |||
| 449 | /** |
||
| 450 | * @param string $path |
||
| 451 | * @param array $params |
||
| 452 | * @param array $data |
||
| 453 | * |
||
| 454 | * @return array |
||
| 455 | * |
||
| 456 | * @throws Exception |
||
| 457 | */ |
||
| 458 | protected function doPost($path, array $params = null, array $data = null) |
||
| 462 | |||
| 463 | /** |
||
| 464 | * @param string $path |
||
| 465 | * @param array $params |
||
| 466 | * @param array $data |
||
| 467 | * |
||
| 468 | * @return array |
||
| 469 | * |
||
| 470 | * @throws Exception |
||
| 471 | */ |
||
| 472 | protected function doPut($path, array $params = null, array $data = null) |
||
| 476 | |||
| 477 | /** |
||
| 478 | * @param string $path |
||
| 479 | * @param array $params |
||
| 480 | * @param array $data |
||
| 481 | * |
||
| 482 | * @return array |
||
| 483 | * |
||
| 484 | * @throws Exception |
||
| 485 | */ |
||
| 486 | protected function doDelete($path, array $params = null, array $data = null) |
||
| 490 | |||
| 491 | /** |
||
| 492 | * Process the request |
||
| 493 | * |
||
| 494 | * @param string $method |
||
| 495 | * @param string $path |
||
| 496 | * @param array $params |
||
| 497 | * @param array $data |
||
| 498 | * |
||
| 499 | * @return array i.e. [success => true|false, [errors => ['message' => 'this is broken', ..]]] |
||
| 500 | * |
||
| 501 | * @throws Exception |
||
| 502 | */ |
||
| 503 | protected function getResult($method, $path, array $params = null, array $data = null) |
||
| 530 | |||
| 531 | /** |
||
| 532 | * @param array $params |
||
| 533 | * |
||
| 534 | * @return mixed |
||
| 535 | */ |
||
| 536 | private function preParseParams(array $params) |
||
| 561 | |||
| 562 | /** |
||
| 563 | * Parse the Communibase result and if necessary throw an exception |
||
| 564 | * |
||
| 565 | * @param string $response |
||
| 566 | * @param int $httpCode |
||
| 567 | * |
||
| 568 | * @return array |
||
| 569 | * |
||
| 570 | * @throws Exception |
||
| 571 | */ |
||
| 572 | private function parseResult($response, $httpCode) |
||
| 582 | |||
| 583 | /** |
||
| 584 | * Error message based on the most recent JSON error. |
||
| 585 | * |
||
| 586 | * @see http://nl1.php.net/manual/en/function.json-last-error.php |
||
| 587 | * |
||
| 588 | * @return string |
||
| 589 | */ |
||
| 590 | private function getLastJsonError() |
||
| 603 | |||
| 604 | /** |
||
| 605 | * @param string $id |
||
| 606 | * |
||
| 607 | * @return bool |
||
| 608 | */ |
||
| 609 | public static function isIdValid($id) |
||
| 621 | |||
| 622 | /** |
||
| 623 | * Generate a Communibase compatible ID, that consists of: |
||
| 624 | * |
||
| 625 | * a 4-byte timestamp, |
||
| 626 | * a 3-byte machine identifier, |
||
| 627 | * a 2-byte process id, and |
||
| 628 | * a 3-byte counter, starting with a random value. |
||
| 629 | * |
||
| 630 | * @return string |
||
| 631 | */ |
||
| 632 | public static function generateId() |
||
| 649 | |||
| 650 | /** |
||
| 651 | * Add extra headers to be added to each request |
||
| 652 | * |
||
| 653 | * @see http://php.net/manual/en/function.header.php |
||
| 654 | * |
||
| 655 | * @param array $extraHeaders |
||
| 656 | */ |
||
| 657 | public function addExtraHeaders(array $extraHeaders) |
||
| 661 | |||
| 662 | /** |
||
| 663 | * @param QueryLogger $logger |
||
| 664 | */ |
||
| 665 | public function setQueryLogger(QueryLogger $logger) |
||
| 669 | |||
| 670 | /** |
||
| 671 | * @return QueryLogger |
||
| 672 | */ |
||
| 673 | public function getQueryLogger() |
||
| 677 | |||
| 678 | /** |
||
| 679 | * @return Client |
||
| 680 | * @throws Exception |
||
| 681 | */ |
||
| 682 | protected function getClient() |
||
| 702 | |||
| 703 | /** |
||
| 704 | * @param string $method |
||
| 705 | * @param array $arguments |
||
| 706 | * |
||
| 707 | * @return \Psr\Http\Message\ResponseInterface |
||
| 708 | * @throws Exception |
||
| 709 | */ |
||
| 710 | private function call($method, array $arguments) |
||
| 751 | } |
||
| 752 |