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 Module 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 Module, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 18 | class Module implements |
||
| 19 | BootstrapListenerInterface, |
||
| 20 | ConfigProviderInterface, |
||
| 21 | ServiceProviderInterface, |
||
| 22 | ViewHelperProviderInterface |
||
| 23 | { |
||
| 24 | public function init(ModuleManager $manager) |
||
| 25 | { |
||
| 26 | $eventManager = $manager->getEventManager(); |
||
| 27 | |||
| 28 | /* |
||
| 29 | * This event change the config before it's cached |
||
| 30 | * The change will apply to 'template_path_stack' and 'assetic_configuration' |
||
| 31 | * These 2 config take part in the Playground Theme Management |
||
| 32 | */ |
||
| 33 | $eventManager->attach(\Zend\ModuleManager\ModuleEvent::EVENT_MERGE_CONFIG, array($this, 'onMergeConfig'), 100); |
||
| 34 | } |
||
| 35 | |||
| 36 | /** |
||
| 37 | * This method is called only when the config is not cached. |
||
| 38 | * @param \Zend\ModuleManager\ModuleEvent $e |
||
| 39 | */ |
||
| 40 | public function onMergeConfig(\Zend\ModuleManager\ModuleEvent $e) |
||
| 41 | { |
||
| 42 | $config = $e->getConfigListener()->getMergedConfig(false); |
||
| 43 | |||
| 44 | if (isset($config['playgroundLocale']) && isset($config['playgroundLocale']['enable']) && $config['playgroundLocale']['enable']) { |
||
| 45 | $config['router']['routes']['frontend']['options']['route'] = '/[:locale[/]]'; |
||
| 46 | $config['router']['routes']['frontend']['options']['constraints']['locale'] = '[a-z]{2}([-_][A-Z]{2})?(?=/|$)'; |
||
| 47 | $config['router']['routes']['frontend']['options']['defaults']['locale'] = $config['playgroundLocale']['default']; |
||
| 48 | } |
||
| 49 | |||
| 50 | $e->getConfigListener()->setMergedConfig($config); |
||
| 51 | } |
||
| 52 | |||
| 53 | public function onBootstrap(EventInterface $e) |
||
| 54 | { |
||
| 55 | // this is useful for zfr-cors to accept chrome extension like Postman |
||
| 56 | UriFactory::registerScheme('chrome-extension', 'Zend\Uri\Uri'); |
||
| 57 | |||
| 58 | $serviceManager = $e->getApplication()->getServiceManager(); |
||
| 59 | $config = $e->getApplication()->getServiceManager()->get('config'); |
||
| 60 | |||
| 61 | // Locale management |
||
| 62 | $translator = $serviceManager->get('translator'); |
||
| 63 | $defaultLocale = 'fr'; |
||
| 64 | |||
| 65 | // Gestion de la locale |
||
| 66 | if (PHP_SAPI !== 'cli') { |
||
| 67 | $config = $e->getApplication()->getServiceManager()->get('config'); |
||
| 68 | if (isset($config['playgroundLocale'])) { |
||
| 69 | $pgLocale = $config['playgroundLocale']; |
||
| 70 | $defaultLocale = $pgLocale['default']; |
||
| 71 | |||
| 72 | if (isset($pgLocale['strategies'])) { |
||
| 73 | $pgstrat = $pgLocale['strategies']; |
||
| 74 | |||
| 75 | // Is there a locale in the URL ? |
||
| 76 | if (in_array('uri', $pgstrat)) { |
||
| 77 | $path = $e->getRequest()->getUri()->getPath(); |
||
| 78 | $parts = explode('/', trim($path, '/')); |
||
| 79 | $localeCandidate = array_shift($parts); |
||
| 80 | // I switch from locale to... language |
||
| 81 | $localeCandidate = substr($localeCandidate, 0, 2); |
||
| 82 | |||
| 83 | if (in_array($localeCandidate, $pgLocale['supported'])) { |
||
| 84 | $locale = $localeCandidate; |
||
| 85 | } |
||
| 86 | } |
||
| 87 | |||
| 88 | // Is there a cookie for the locale ? |
||
| 89 | if (empty($locale) && in_array('cookie', $pgstrat)) { |
||
| 90 | $serviceManager->get('router')->setTranslator($translator); |
||
| 91 | if ($serviceManager->get('router')->match($serviceManager->get('request')) && |
||
| 92 | strpos($serviceManager->get('router')->match($serviceManager->get('request'))->getMatchedRouteName(), 'admin') !==false |
||
| 93 | ) { |
||
| 94 | View Code Duplication | if ($e->getRequest()->getCookie() && |
|
| 95 | $e->getRequest()->getCookie()->offsetExists('pg_locale_back') |
||
| 96 | ) { |
||
| 97 | $locale = $e->getRequest()->getCookie()->offsetGet('pg_locale_back'); |
||
| 98 | } |
||
| 99 | View Code Duplication | } else { |
|
| 100 | if ($e->getRequest()->getCookie() && |
||
| 101 | $e->getRequest()->getCookie()->offsetExists('pg_locale_frontend') |
||
| 102 | ) { |
||
| 103 | $locale = $e->getRequest()->getCookie()->offsetGet('pg_locale_frontend'); |
||
| 104 | } |
||
| 105 | } |
||
| 106 | } |
||
| 107 | |||
| 108 | // Is there a locale in the request Header ? |
||
| 109 | if (empty($locale) && in_array('header', $pgstrat)) { |
||
| 110 | if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { |
||
| 111 | $localeCandidate = \Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); |
||
| 112 | // I switch from locale to... language |
||
| 113 | $localeCandidate = substr($localeCandidate, 0, 2); |
||
| 114 | if (in_array($localeCandidate, $pgLocale['supported'])) { |
||
| 115 | $locale = $localeCandidate; |
||
| 116 | } |
||
| 117 | } |
||
| 118 | } |
||
| 119 | } |
||
| 120 | // I take the default locale |
||
| 121 | if (empty($locale)) { |
||
| 122 | $locale = $defaultLocale; |
||
| 123 | } |
||
| 124 | } |
||
| 125 | |||
| 126 | // I take the default locale |
||
| 127 | if (empty($locale)) { |
||
| 128 | $locale = $defaultLocale; |
||
| 129 | } |
||
| 130 | |||
| 131 | $translator->setLocale($locale); |
||
| 132 | |||
| 133 | // Attach the translator to the router |
||
| 134 | $e->getRouter()->setTranslator($translator); |
||
| 135 | $e->getRouter()->setTranslatorTextDomain('routes'); |
||
| 136 | |||
| 137 | // Attach the translator to the plugins |
||
| 138 | $translate = $serviceManager->get('viewhelpermanager')->get('translate'); |
||
| 139 | $translate->getTranslator()->setLocale($locale); |
||
| 140 | |||
| 141 | $options = $serviceManager->get('playgroundcore_module_options'); |
||
| 142 | $options->setLocale($locale); |
||
| 143 | } |
||
| 144 | |||
| 145 | // positionnement de la langue pour les traductions de date avec strftime |
||
| 146 | setlocale(LC_TIME, "fr_FR", 'fr_FR.utf8', 'fra'); |
||
| 147 | |||
| 148 | AbstractValidator::setDefaultTranslator($translator, 'playgroundcore'); |
||
| 149 | |||
| 150 | /* |
||
| 151 | * Entity translation based on Doctrine Gedmo library |
||
| 152 | */ |
||
| 153 | $doctrine = $serviceManager->get('doctrine.entitymanager.orm_default'); |
||
| 154 | $evm = $doctrine->getEventManager(); |
||
| 155 | |||
| 156 | $translatableListener = new \Gedmo\Translatable\TranslatableListener(); |
||
| 157 | $translatableListener->setDefaultLocale($defaultLocale); |
||
| 158 | |||
| 159 | // If no translation is found, fallback to entity data |
||
| 160 | $translatableListener->setTranslationFallback(true); |
||
| 161 | |||
| 162 | // set Locale |
||
| 163 | if (!empty($locale)) { |
||
| 164 | $translatableListener->setTranslatableLocale($locale); |
||
| 165 | } |
||
| 166 | |||
| 167 | $evm->addEventSubscriber($translatableListener); |
||
| 168 | |||
| 169 | /** |
||
| 170 | * Adding a Filter to slugify a string (make it URL compliiant) |
||
| 171 | */ |
||
| 172 | $filterChain = new \Zend\Filter\FilterChain(); |
||
| 173 | $filterChain->getPluginManager()->setInvokableClass( |
||
| 174 | 'slugify', |
||
| 175 | 'PlaygroundCore\Filter\Slugify' |
||
| 176 | ); |
||
| 177 | $filterChain->attach(new Filter\Slugify()); |
||
| 178 | |||
| 179 | // Start the session container |
||
| 180 | $sessionConfig = new SessionConfig(); |
||
| 181 | $sessionConfig->setOptions($config['session']); |
||
| 182 | $sessionManager = new SessionManager($sessionConfig); |
||
| 183 | $sessionManager->start(); |
||
| 184 | |||
| 185 | /** |
||
| 186 | * Optional: If you later want to use namespaces, you can already store the |
||
| 187 | * Manager in the shared (static) Container (=namespace) field |
||
| 188 | */ |
||
| 189 | \Zend\Session\Container::setDefaultManager($sessionManager); |
||
| 190 | |||
| 191 | // Google Analytics : When the render event is triggered, we invoke the view helper to |
||
| 192 | // render the javascript code. |
||
| 193 | $e->getApplication()->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function (\Zend\Mvc\MvcEvent $e) use ($serviceManager) { |
||
| 194 | $view = $serviceManager->get('ViewHelperManager'); |
||
| 195 | $plugin = $view->get('googleAnalytics'); |
||
| 196 | $plugin(); |
||
| 197 | |||
| 198 | $pluginOG = $view->get('facebookOpengraph'); |
||
| 199 | $pluginOG(); |
||
| 200 | |||
| 201 | $pluginTC = $view->get('twitterCard'); |
||
| 202 | $pluginTC(); |
||
| 203 | }); |
||
| 204 | |||
| 205 | |||
| 206 | if (PHP_SAPI !== 'cli') { |
||
| 207 | $session = new Container('facebook'); |
||
| 208 | $fb = $e->getRequest()->getPost()->get('signed_request'); |
||
| 209 | if ($fb) { |
||
| 210 | $signedReq = explode('.', $fb, 2); |
||
| 211 | $payload = $signedReq[1]; |
||
| 212 | $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); |
||
| 213 | $session->offsetSet('signed_request', $data); |
||
| 214 | |||
| 215 | // This fix exists only for safari on Windows : we need to redirect the user to the page outside of iframe |
||
| 216 | // for the cookie to be accepted. Core just adds a 'redir_fb_page_id' var to alert controllers |
||
| 217 | // that they need to send the user back to FB... |
||
| 218 | |||
| 219 | if (!count($_COOKIE) > 0 && strpos($_SERVER['HTTP_USER_AGENT'], 'Safari')) { |
||
| 220 | echo '<script type="text/javascript">' . |
||
| 221 | 'window.top.location.href = window.location.href+"?redir_fb_page_id='. $data["page"]["id"]. '";' . |
||
| 222 | '</script>'; |
||
| 223 | } |
||
| 224 | |||
| 225 | // This fix exists only for IE6+, when this app is embedded into an iFrame : The P3P policy has to be set. |
||
| 226 | $response = $e->getResponse(); |
||
| 227 | if ($response instanceof \Zend\Http\Response && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') || strpos($_SERVER['HTTP_USER_AGENT'], 'rv:11.'))) { |
||
| 228 | $response->getHeaders()->addHeaderLine('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); |
||
| 229 | } |
||
| 230 | } |
||
| 231 | } |
||
| 232 | } |
||
| 233 | |||
| 234 | public function getConfig() |
||
| 238 | |||
| 239 | public function getViewHelperConfig() |
||
| 292 | |||
| 293 | public function getServiceConfig() |
||
| 294 | { |
||
| 295 | return array( |
||
| 396 | |||
| 397 | public function getConsoleUsage(\Zend\Console\Adapter\Posix $console) |
||
| 403 | } |
||
| 404 |
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: