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:
Complex classes like MobileDetect 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 MobileDetect, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 42 | class MobileDetect |
||
| 43 | { |
||
| 44 | const VERSION = '3.0.0-alpha'; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * An associative array of headers in standard format. |
||
| 48 | * So the keys will be "User-Agent", and "Accepts" versus |
||
| 49 | * the all caps PHP format. |
||
| 50 | * |
||
| 51 | * @var array |
||
| 52 | */ |
||
| 53 | protected $headers = array(); |
||
| 54 | |||
| 55 | // Database. |
||
| 56 | protected $userAgentHeaders; |
||
| 57 | protected $recognizedHttpHeaders; |
||
| 58 | protected $phonesProvider; |
||
| 59 | protected $tabletsProvider; |
||
| 60 | protected $browsersProvider; |
||
| 61 | protected $operatingSystemsProvider; |
||
| 62 | |||
| 63 | protected static $knownMatchTypes = array( |
||
| 64 | 'regex', //regular expression |
||
| 65 | 'strpos', //simple case-sensitive string within string check |
||
| 66 | 'stripos', //simple case-insensitive string within string check |
||
| 67 | ); |
||
| 68 | |||
| 69 | /** |
||
| 70 | * For static invocations of this class, this holds a singleton for those methods. |
||
| 71 | * |
||
| 72 | * @var MobileDetect |
||
| 73 | */ |
||
| 74 | protected static $instance; |
||
| 75 | |||
| 76 | /** |
||
| 77 | * An instance of a device when using the static methods. |
||
| 78 | * |
||
| 79 | * @var DeviceInterface |
||
| 80 | */ |
||
| 81 | protected static $device; |
||
| 82 | |||
| 83 | /** |
||
| 84 | * An optionally callable cache setter for attaching a caching implementation for caching the detection of a device. |
||
| 85 | * |
||
| 86 | * The expected signature: |
||
| 87 | * @param $key string The key identifier (i.e. the User-Agent). |
||
| 88 | * @param $obj DeviceInterface the device being saved. |
||
| 89 | * |
||
| 90 | * @var \Closure |
||
| 91 | */ |
||
| 92 | protected $cacheSet; |
||
| 93 | |||
| 94 | /** |
||
| 95 | * An optionally callable cache getter for attaching a caching implementation for caching the detection of a device. |
||
| 96 | * |
||
| 97 | * The expected signature: |
||
| 98 | * @param $key string The key identifier (i.e. the User-Agent). |
||
| 99 | * @return DeviceInterface|null |
||
| 100 | * |
||
| 101 | * @var \Closure |
||
| 102 | */ |
||
| 103 | protected $cacheGet; |
||
| 104 | |||
| 105 | /** |
||
| 106 | * Generates or gets a singleton for use with the simple API. |
||
| 107 | * |
||
| 108 | * @return MobileDetect A single instance for using with the simple static API. |
||
| 109 | */ |
||
| 110 | public static function getInstance() |
||
| 118 | |||
| 119 | public static function destroy() |
||
| 123 | |||
| 124 | /** |
||
| 125 | * @param $headers \Iterator|array|HttpMessageInterface|string When it's a string, it's assumed to be User-Agent. |
||
| 126 | * @param Phones|null $phonesProvider |
||
| 127 | * @param Tablets|null $tabletsProvider |
||
| 128 | * @param Browsers|null $browsersProvider |
||
| 129 | * @param OperatingSystems|null $operatingSystemsProvider |
||
| 130 | * @param UserAgentHeaders $userAgentHeaders |
||
| 131 | * @param HttpHeaders $recognizedHttpHeaders |
||
| 132 | */ |
||
| 133 | public function __construct( |
||
| 207 | |||
| 208 | /** |
||
| 209 | * Makes a best attempt at extracting headers, starting with Apache then trying $_SERVER super global. |
||
| 210 | * |
||
| 211 | * @return array |
||
| 212 | */ |
||
| 213 | public static function getHttpHeadersFromEnv() |
||
| 225 | |||
| 226 | /** |
||
| 227 | * Set the User-Agent to be used. |
||
| 228 | * @param string $userAgent The user agent string to set. |
||
| 229 | * @return MobileDetect Fluent interface. |
||
| 230 | */ |
||
| 231 | public function setUserAgent($userAgent = null) |
||
| 253 | |||
| 254 | /** |
||
| 255 | * Set an HTTP header. |
||
| 256 | * |
||
| 257 | * @param $key |
||
| 258 | * @param $value |
||
| 259 | * @return MobileDetect Fluent interface. |
||
| 260 | * @throws Exception\InvalidArgumentException When the $key isn't a valid HTTP request header name. |
||
| 261 | */ |
||
| 262 | public function setHeader($key, $value) |
||
| 269 | |||
| 270 | /** |
||
| 271 | * Retrieves a header. |
||
| 272 | * |
||
| 273 | * @param $key string The header. |
||
| 274 | * @return string|null If the header is available, it's returned. Null otherwise. |
||
| 275 | */ |
||
| 276 | public function getHeader($key) |
||
| 283 | |||
| 284 | public function getHeaders() |
||
| 288 | |||
| 289 | /** |
||
| 290 | * @param $headerName string |
||
| 291 | * @param $force bool Forces the header set even if it's not standard or doesn't start with "X-" |
||
| 292 | * @return string The header, normalized, so HTTP_USER_AGENT becomes user-agent |
||
| 293 | * @throws Exception\InvalidArgumentException When the $headerName isn't a valid HTTP request header name. |
||
| 294 | */ |
||
| 295 | protected function standardizeHeader($headerName, $force = false) |
||
| 315 | |||
| 316 | /** |
||
| 317 | * Retrieves the user agent header. |
||
| 318 | * @return null|string The value or null if it doesn't exist. |
||
| 319 | */ |
||
| 320 | public function getUserAgent() |
||
| 324 | |||
| 325 | /** |
||
| 326 | * This method allows for static calling of methods that get proxied to the device methods. For example, |
||
| 327 | * when calling Detected::getOperatingSystem() it will be proxied to static::$device->getOperatingSystem(). |
||
| 328 | * Since reflection is used in combination with call_user_func_array(), this method is relatively expensive |
||
| 329 | * and should not be used if the developer cares about performance. This is merely a convenience method |
||
| 330 | * for beginners using this detection library. |
||
| 331 | * |
||
| 332 | * @param string $method The method name being invoked. |
||
| 333 | * @param array $args Arguments for the called method. |
||
| 334 | * |
||
| 335 | * @return mixed |
||
| 336 | * |
||
| 337 | * @throws \BadMethodCallException |
||
| 338 | */ |
||
| 339 | public static function __callStatic($method, array $args = array()) |
||
| 353 | |||
| 354 | public static function getKnownMatches() |
||
| 358 | |||
| 359 | /** |
||
| 360 | * @param $version string The string to convert to a standard version. |
||
| 361 | * @param bool $asArray |
||
| 362 | * @return array|string A string or an array if $asArray is passed as true. |
||
| 363 | */ |
||
| 364 | protected function prepareVersion($version, $asArray = false) |
||
| 375 | |||
| 376 | /** |
||
| 377 | * Converts the quasi-regex into a full regex, replacing various common placeholders such |
||
| 378 | * as [VER] or [MODEL]. |
||
| 379 | * |
||
| 380 | * @param $regex string|array |
||
| 381 | * |
||
| 382 | * @return string |
||
| 383 | */ |
||
| 384 | protected function prepareRegex($regex) |
||
| 399 | |||
| 400 | /** |
||
| 401 | * Given a type of match, this method will check if a valid match is found. |
||
| 402 | * |
||
| 403 | * @param string $type The type {{@see $this->knownMatchTypes}}. |
||
| 404 | * @param string $test The test subject. |
||
| 405 | * @param string $against The pattern (for regex) or substring (for str[i]pos). |
||
| 406 | * @return bool True if matched successfully. |
||
| 407 | * @throws Exception\InvalidArgumentException If $against isn't a string or $type is invalid. |
||
| 408 | */ |
||
| 409 | protected function identityMatch($type, $test, $against) |
||
| 440 | |||
| 441 | /** |
||
| 442 | * Attempts to match the model and extracts |
||
| 443 | * the version and model if available. |
||
| 444 | * |
||
| 445 | * @param $tests array Various tests. |
||
| 446 | * @param $against string The test. |
||
| 447 | * |
||
| 448 | * @return array|bool False if no match, hash of match data otherwise. |
||
| 449 | */ |
||
| 450 | protected function modelAndVersionMatch($tests, $against) |
||
| 483 | |||
| 484 | /** |
||
| 485 | * @param $tests |
||
| 486 | * @param $against |
||
| 487 | * @return null |
||
| 488 | */ |
||
| 489 | View Code Duplication | protected function modelMatch($tests, $against) |
|
| 513 | |||
| 514 | View Code Duplication | protected function versionMatch($tests, $against) |
|
| 538 | |||
| 539 | protected function matchEntity($entity, $tests, $against) |
||
| 549 | |||
| 550 | // @todo: Reduce scope of $deviceInfoFromDb |
||
| 551 | View Code Duplication | protected function detectDeviceModel(array $deviceInfoFromDb) |
|
| 559 | |||
| 560 | // @todo: temporary duplicated code |
||
| 561 | View Code Duplication | protected function detectDeviceModelVersion(array $deviceInfoFromDb) |
|
| 569 | |||
| 570 | protected function detectBrowserModel(array $browserInfoFromDb) |
||
| 574 | |||
| 575 | protected function detectBrowserVersion(array $browserInfoFromDb) |
||
| 586 | |||
| 587 | protected function detectOperatingSystemModel(array $operatingSystemInfoFromDb) |
||
| 591 | |||
| 592 | protected function detectOperatingSystemVersion(array $operatingSystemInfoFromDb) |
||
| 596 | |||
| 597 | /** |
||
| 598 | * Creates a device with all the necessary context to determine all the given |
||
| 599 | * properties of a device, including OS, browser, and any other context-based properties. |
||
| 600 | * |
||
| 601 | * @param DeviceInterface $deviceClass (optional) |
||
| 602 | * The class to use. It can be anything that's derived from DeviceInterface. |
||
| 603 | * |
||
| 604 | * {@see DeviceInterface} |
||
| 605 | * |
||
| 606 | * @return DeviceInterface |
||
| 607 | * |
||
| 608 | * @throws Exception\InvalidArgumentException When an invalid class is used. |
||
| 609 | */ |
||
| 610 | public function detect($deviceClass = null) |
||
| 722 | |||
| 723 | private function searchForItemInDb(array $itemData) |
||
| 754 | |||
| 755 | View Code Duplication | protected function searchPhonesProvider() |
|
| 766 | |||
| 767 | View Code Duplication | protected function searchTabletsProvider() |
|
| 778 | |||
| 779 | View Code Duplication | protected function searchBrowsersProvider() |
|
| 792 | |||
| 793 | View Code Duplication | protected function searchOperatingSystemsProvider() |
|
| 806 | |||
| 807 | /** |
||
| 808 | * @param $regex |
||
| 809 | * @param $against |
||
| 810 | * @param null $matches |
||
| 811 | * @return int |
||
| 812 | */ |
||
| 813 | private function regexMatch($regex, $against, &$matches = null) |
||
| 817 | |||
| 818 | /** |
||
| 819 | * An error handler that gets registered to watch only for regex errors and convert |
||
| 820 | * to an exception. |
||
| 821 | * |
||
| 822 | * @param $code int |
||
| 823 | * @param $msg string |
||
| 824 | * @param $file string |
||
| 825 | * @param $line int |
||
| 826 | * @param $context array |
||
| 827 | * |
||
| 828 | * @return bool False to indicate this is not a regex error to be handled. |
||
| 829 | * |
||
| 830 | * @throws Exception\RegexCompileException When there is a regex error. |
||
| 831 | */ |
||
| 832 | public function regexErrorHandler($code, $msg, $file, $line, $context) |
||
| 842 | |||
| 843 | private function setRegexErrorHandler() |
||
| 848 | |||
| 849 | private function restoreRegexErrorHandler() |
||
| 854 | |||
| 855 | /** |
||
| 856 | * Set the cache setter lambda. |
||
| 857 | * |
||
| 858 | * @param \Closure $cb |
||
| 859 | * |
||
| 860 | * @return MobileDetect |
||
| 861 | */ |
||
| 862 | public function setCacheSetter(\Closure $cb) |
||
| 868 | |||
| 869 | /** |
||
| 870 | * Set the cache getter lambda. |
||
| 871 | * |
||
| 872 | * @param \Closure $cb |
||
| 873 | * |
||
| 874 | * @return $this |
||
| 875 | */ |
||
| 876 | public function setCacheGetter(\Closure $cb) |
||
| 882 | |||
| 883 | /** |
||
| 884 | * Try to get the device from cache if available. |
||
| 885 | * |
||
| 886 | * @param $key string The key. |
||
| 887 | * |
||
| 888 | * @return DeviceInterface|null |
||
| 889 | */ |
||
| 890 | public function getFromCache($key) |
||
| 900 | |||
| 901 | /** |
||
| 902 | * Try to save the detected device in cache. |
||
| 903 | * |
||
| 904 | * @param $key string The key. |
||
| 905 | * @param DeviceInterface $obj The device. |
||
| 906 | * |
||
| 907 | * @return bool false if not succeeded. |
||
| 908 | */ |
||
| 909 | public function setCache($key, DeviceInterface $obj) |
||
| 919 | } |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: