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 |
||
| 31 | class BearerAuth extends AbstractBearer { |
||
| 32 | /** @var IUserSession */ |
||
| 33 | private $userSession; |
||
| 34 | /** @var ISession */ |
||
| 35 | private $session; |
||
| 36 | /** @var IRequest */ |
||
| 37 | private $request; |
||
| 38 | /** @var string */ |
||
| 39 | private $principalPrefix; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @param IUserSession $userSession |
||
| 43 | * @param ISession $session |
||
| 44 | * @param string $principalPrefix |
||
| 45 | * @param IRequest $request |
||
| 46 | */ |
||
| 47 | View Code Duplication | public function __construct(IUserSession $userSession, |
|
|
|
|||
| 48 | ISession $session, |
||
| 49 | IRequest $request, |
||
| 50 | $principalPrefix = 'principals/users/') { |
||
| 51 | $this->userSession = $userSession; |
||
| 52 | $this->session = $session; |
||
| 53 | $this->request = $request; |
||
| 54 | $this->principalPrefix = $principalPrefix; |
||
| 55 | |||
| 56 | // setup realm |
||
| 57 | $defaults = new \OCP\Defaults(); |
||
| 58 | $this->realm = $defaults->getName(); |
||
| 59 | } |
||
| 60 | |||
| 61 | private function setupUserFs($userId) { |
||
| 62 | \OC_Util::setupFS($userId); |
||
| 63 | $this->session->close(); |
||
| 64 | return $this->principalPrefix . $userId; |
||
| 65 | } |
||
| 66 | |||
| 67 | /** |
||
| 68 | * {@inheritdoc} |
||
| 69 | */ |
||
| 70 | public function validateBearerToken($bearerToken) { |
||
| 71 | \OC_Util::setupFS(); |
||
| 72 | |||
| 73 | if(!$this->userSession->isLoggedIn()) { |
||
| 74 | $this->userSession->tryTokenLogin($this->request); |
||
| 75 | } |
||
| 76 | if($this->userSession->isLoggedIn()) { |
||
| 77 | return $this->setupUserFs($this->userSession->getUser()->getUID()); |
||
| 78 | } |
||
| 79 | |||
| 80 | return false; |
||
| 81 | } |
||
| 82 | |||
| 83 | /** |
||
| 84 | * \Sabre\DAV\Auth\Backend\AbstractBearer::challenge sets an WWW-Authenticate |
||
| 85 | * header which some DAV clients can't handle. Thus we override this function |
||
| 86 | * and make it simply return a 401. |
||
| 87 | * |
||
| 88 | * @param RequestInterface $request |
||
| 89 | * @param ResponseInterface $response |
||
| 90 | */ |
||
| 91 | public function challenge(RequestInterface $request, ResponseInterface $response) { |
||
| 94 | } |
||
| 95 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.