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 |
||
| 12 | class BaseUrlFunction implements StakxTwigFilter |
||
| 13 | { |
||
| 14 | private $site; |
||
| 15 | |||
| 16 | 18 | public function __invoke(Twig_Environment $env, $assetPath, $absolute = false) |
|
| 17 | { |
||
| 18 | 18 | $globals = $env->getGlobals(); |
|
| 19 | 18 | $this->site = $globals['site']; |
|
| 20 | |||
| 21 | 18 | $url = $this->getUrl($absolute); |
|
| 22 | 18 | $baseURL = $this->getBaseUrl(); |
|
| 23 | 18 | $permalink = $this->guessAssetPath($assetPath); |
|
| 24 | |||
| 25 | 18 | return $this->buildPermalink($url, $baseURL, $permalink); |
|
| 26 | } |
||
| 27 | |||
| 28 | public static function get() |
||
| 29 | { |
||
| 30 | return new \Twig_SimpleFunction('url', new self(), array( |
||
|
|
|||
| 31 | 'needs_environment' => true, |
||
| 32 | )); |
||
| 33 | } |
||
| 34 | |||
| 35 | 18 | private function getUrl($absolute) |
|
| 51 | |||
| 52 | 18 | private function getBaseUrl() |
|
| 67 | |||
| 68 | 18 | private function guessAssetPath($assetPath) |
|
| 69 | { |
||
| 70 | 18 | if (is_array($assetPath) || ($assetPath instanceof \ArrayAccess)) |
|
| 71 | { |
||
| 72 | 4 | return (isset($assetPath['permalink'])) ? $assetPath['permalink'] : '/'; |
|
| 73 | } |
||
| 74 | 14 | elseif (is_null($assetPath)) |
|
| 75 | { |
||
| 76 | 1 | return '/'; |
|
| 77 | } |
||
| 78 | |||
| 79 | 13 | return $assetPath; |
|
| 80 | } |
||
| 81 | |||
| 82 | /** |
||
| 83 | * @link https://stackoverflow.com/a/15575293 |
||
| 84 | * @return string |
||
| 85 | */ |
||
| 86 | 18 | View Code Duplication | private function buildPermalink() |
| 100 | } |
||
| 101 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_functionexpects aPostobject, and outputs the author of the post. The base classPostreturns a simple string and outputting a simple string will work just fine. However, the child classBlogPostwhich is a sub-type ofPostinstead decided to return anobject, and is therefore violating the SOLID principles. If aBlogPostwere passed tomy_function, PHP would not complain, but ultimately fail when executing thestrtouppercall in its body.