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 |
||
| 20 | class Sftp extends Xtp implements Simulator |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * Check for required loaded libraries or extensions. |
||
| 24 | * |
||
| 25 | * @throws \phpbu\App\Backup\Sync\Exception |
||
| 26 | */ |
||
| 27 | 7 | protected function checkRequirements() |
|
| 33 | |||
| 34 | /** |
||
| 35 | * Return implemented (*)TP protocol name. |
||
| 36 | * |
||
| 37 | * @return string |
||
| 38 | */ |
||
| 39 | 1 | protected function getProtocolName() |
|
| 43 | |||
| 44 | /** |
||
| 45 | * (non-PHPDoc) |
||
| 46 | * |
||
| 47 | * @see \phpbu\App\Backup\Sync::sync() |
||
| 48 | * @param \phpbu\App\Backup\Target $target |
||
| 49 | * @param \phpbu\App\Result $result |
||
| 50 | * @throws \phpbu\App\Backup\Sync\Exception |
||
| 51 | */ |
||
| 52 | 1 | public function sync(Target $target, Result $result) |
|
| 53 | { |
||
| 54 | 1 | $sftp = $this->login(); |
|
| 55 | 1 | $remoteFilename = $target->getFilename(); |
|
| 56 | 1 | $localFile = $target->getPathname(); |
|
| 57 | |||
| 58 | 1 | foreach ($this->getRemoteDirectoryList() as $dir) { |
|
| 59 | 1 | if (!$sftp->is_dir($dir)) { |
|
| 60 | 1 | $result->debug(sprintf('creating remote dir \'%s\'', $dir)); |
|
| 61 | 1 | $sftp->mkdir($dir); |
|
| 62 | } |
||
| 63 | 1 | $result->debug(sprintf('change to remote dir \'%s\'', $dir)); |
|
| 64 | 1 | $sftp->chdir($dir); |
|
| 65 | } |
||
| 66 | |||
| 67 | 1 | $result->debug(sprintf('store file \'%s\' as \'%s\'', $localFile, $remoteFilename)); |
|
| 68 | 1 | $result->debug(sprintf('last error \'%s\'', $sftp->getLastSFTPError())); |
|
| 69 | |||
| 70 | 1 | if (!$sftp->put($remoteFilename, $localFile, phpseclib\Net\SFTP::SOURCE_LOCAL_FILE)) { |
|
| 71 | throw new Exception(sprintf('error uploading file: %s - %s', $localFile, $sftp->getLastSFTPError())); |
||
| 72 | } |
||
| 73 | 1 | } |
|
| 74 | |||
| 75 | /** |
||
| 76 | * Create a sftp handle. |
||
| 77 | * |
||
| 78 | * @return \phpseclib\Net\SFTP |
||
| 79 | * @throws \phpbu\App\Backup\Sync\Exception |
||
| 80 | */ |
||
| 81 | protected function login() : phpseclib\Net\SFTP |
||
| 102 | |||
| 103 | /** |
||
| 104 | * Return list of remote directories to travers. |
||
| 105 | * |
||
| 106 | * @return array |
||
| 107 | */ |
||
| 108 | 1 | private function getRemoteDirectoryList() : array |
|
| 121 | } |
||
| 122 |