code style and lint errors

This commit is contained in:
korelstar 2019-05-25 08:15:05 +02:00 committed by GitHub
parent 682dc48055
commit 16de16937e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 892 additions and 901 deletions

2
.gitignore vendored
View File

@ -1,10 +1,12 @@
node_modules/
vendor/
*.log
build/
js/
.rvm
report
clover.xml
composer.lock
# just sane ignores
.*.sw[po]

View File

@ -11,6 +11,7 @@ build:
tests:
override:
- php-scrutinizer-run
- phpcs-run --standard=phpcs.xml appinfo/ lib/
- eslint-run --ext .js,.vue src
tools:

View File

@ -49,8 +49,7 @@ script:
# - phpunit -c phpunit.integration.xml
# build js
- make npm-init
- make init
- make lint
- make stylelint
- make build-js-production

View File

@ -9,32 +9,32 @@ appstore_dir=$(build_dir)/appstore
package_name=$(app_name)
cert_dir=$(HOME)/.nextcloud/certificates
appstore: clean
appstore: clean lint build-js-production
mkdir -p $(sign_dir)
rsync -a \
--exclude=.git \
--exclude=.babelrc.js \
--exclude=build \
--exclude=.gitignore \
--exclude=.travis.yml \
--exclude=.scrutinizer.yml \
--exclude=CONTRIBUTING.md \
--exclude=composer.json \
--exclude=composer.lock \
--exclude=composer.phar \
--exclude=.tx \
--exclude=CONTRIBUTING.md \
--exclude=.editorconfig \
--exclude=.eslintrc.js \
--exclude=.git \
--exclude=.github \
--exclude=.gitignore \
--exclude=l10n/no-php \
--exclude=Makefile \
--exclude=nbproject \
--exclude=screenshots \
--exclude=package*.json \
--exclude=phpcs.xml \
--exclude=phpunit*xml \
--exclude=.scrutinizer.yml \
--exclude=src \
--exclude=.stylelintrc.js \
--exclude=tests \
--exclude=vendor/bin \
--exclude=js/node_modules \
--exclude=js/tests \
--exclude=js/karma.conf.js \
--exclude=js/gulpfile.js \
--exclude=js/bower.json \
--exclude=js/package.json \
--exclude=.travis.yml \
--exclude=.tx \
--exclude=vendor \
$(project_dir) $(sign_dir)
@echo "Signing…"
php ../server/occ integrity:sign-app \
@ -51,7 +51,12 @@ appstore: clean
all: dev-setup lint build-js-production test
# Dev env management
dev-setup: clean clean-dev npm-init
dev-setup: clean clean-dev init
init: composer-init npm-init
composer-init:
composer install
npm-init:
npm install
@ -84,17 +89,27 @@ test-coverage:
npm run test:coverage
# Linting
lint:
lint: lint-php lint-js lint-css
lint-php:
vendor/bin/phpcs --standard=phpcs.xml --runtime-set ignore_warnings_on_exit 1 appinfo/ lib/
lint-js:
npm run lint
lint-fix:
npm run lint:fix
# Style linting
stylelint:
lint-css:
npm run stylelint
stylelint-fix:
# Fix lint
lint-fix: lint-php-fix lint-js-fix lint-css-fix
lint-php-fix:
vendor/bin/phpcbf --standard=phpcs.xml appinfo/ lib/
lint-js-fix:
npm run lint:fix
lint-css-fix:
npm run stylelint:fix
# Cleaning
@ -104,4 +119,5 @@ clean:
clean-dev:
rm -rf node_modules
rm -rf vendor

View File

@ -27,4 +27,3 @@ $container->query('OCP\INavigationManager')->add(function () use ($container) {
'name' => $l10n->t('Notes')
];
});

View File

@ -1,5 +1,6 @@
{
"require-dev": {
"christophwurst/nextcloud": "^15.0"
"christophwurst/nextcloud": "^15.0",
"squizlabs/php_codesniffer": "3.*"
}
}

View File

@ -1,13 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Controller;
@ -26,10 +17,10 @@ trait Errors {
* @param $callback
* @return DataResponse
*/
protected function respond ($callback) {
protected function respond($callback) {
try {
return new DataResponse($callback());
} catch(NoteDoesNotExistException $ex) {
} catch (NoteDoesNotExistException $ex) {
return new DataResponse([], Http::STATUS_NOT_FOUND);
}
}

View File

@ -1,13 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Controller;
@ -61,9 +52,9 @@ class NotesApiController extends ApiController {
* @return Note
*/
private function excludeFields(Note &$note, array $exclude) {
if(count($exclude) > 0) {
if (count($exclude) > 0) {
foreach ($exclude as $field) {
if(property_exists($note, $field)) {
if (property_exists($note, $field)) {
unset($note->$field);
}
}
@ -80,14 +71,14 @@ class NotesApiController extends ApiController {
* @param string $exclude
* @return DataResponse
*/
public function index($exclude='', $pruneBefore=0) {
public function index($exclude = '', $pruneBefore = 0) {
$exclude = explode(',', $exclude);
$now = new \DateTime(); // this must be before loading notes if there are concurrent changes possible
$notes = $this->service->getAll($this->getUID());
$metas = $this->metaService->updateAll($this->getUID(), $notes);
foreach ($notes as $note) {
$lastUpdate = $metas[$note->getId()]->getLastUpdate();
if($pruneBefore && $lastUpdate<$pruneBefore) {
if ($pruneBefore && $lastUpdate<$pruneBefore) {
$vars = get_object_vars($note);
unset($vars['id']);
$this->excludeFields($note, array_keys($vars));
@ -114,7 +105,7 @@ class NotesApiController extends ApiController {
* @param string $exclude
* @return DataResponse
*/
public function get($id, $exclude='') {
public function get($id, $exclude = '') {
$exclude = explode(',', $exclude);
return $this->respond(function () use ($id, $exclude) {
@ -136,7 +127,7 @@ class NotesApiController extends ApiController {
* @param boolean $favorite
* @return DataResponse
*/
public function create($content, $category=null, $modified=0, $favorite=null) {
public function create($content, $category = null, $modified = 0, $favorite = null) {
return $this->respond(function () use ($content, $category, $modified, $favorite) {
$note = $this->service->create($this->getUID());
return $this->updateData($note->getId(), $content, $category, $modified, $favorite);
@ -156,7 +147,7 @@ class NotesApiController extends ApiController {
* @param boolean $favorite
* @return DataResponse
*/
public function update($id, $content=null, $category=null, $modified=0, $favorite=null) {
public function update($id, $content = null, $category = null, $modified = 0, $favorite = null) {
return $this->respond(function () use ($id, $content, $category, $modified, $favorite) {
return $this->updateData($id, $content, $category, $modified, $favorite);
});
@ -165,16 +156,16 @@ class NotesApiController extends ApiController {
/**
* Updates a note, used by create and update
* @param int $id
* @param string $content
* @param string|null $content
* @param int $modified
* @param boolean $favorite
* @param boolean|null $favorite
* @return Note
*/
private function updateData($id, $content, $category, $modified, $favorite) {
if($favorite!==null) {
if ($favorite!==null) {
$this->service->favorite($id, $favorite, $this->getUID());
}
if($content===null) {
if ($content===null) {
return $this->service->get($id, $this->getUID());
} else {
return $this->service->update($id, $content, $this->getUID(), $category, $modified);
@ -195,6 +186,4 @@ class NotesApiController extends ApiController {
return [];
});
}
}

View File

@ -1,13 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Controller;
@ -49,13 +40,15 @@ class NotesController extends Controller {
* @param IL10N $l10n
* @param string $UserId
*/
public function __construct($AppName,
public function __construct(
$AppName,
IRequest $request,
NotesService $notesService,
SettingsService $settingsService,
IConfig $settings,
IL10N $l10n,
$UserId) {
$UserId
) {
parent::__construct($AppName, $request);
$this->notesService = $notesService;
$this->settingsService = $settingsService;
@ -73,22 +66,25 @@ class NotesController extends Controller {
$settings = $this->settingsService->getAll($this->userId);
$errorMessage = null;
$lastViewedNote = (int) $this->settings->getUserValue($this->userId,
$this->appName, 'notesLastViewedNote');
$lastViewedNote = (int) $this->settings->getUserValue(
$this->userId,
$this->appName,
'notesLastViewedNote'
);
// check if notes folder is accessible
try {
$this->notesService->checkNotesFolder($this->userId);
if($lastViewedNote) {
if ($lastViewedNote) {
// check if note exists
try {
$this->notesService->get($lastViewedNote, $this->userId);
} catch(\Exception $ex) {
} catch (\Exception $ex) {
$this->settings->deleteUserValue($this->userId, $this->appName, 'notesLastViewedNote');
$lastViewedNote = 0;
$errorMessage = $this->l10n->t('The last viewed note cannot be accessed. ').$ex->getMessage();
}
}
} catch(\Exception $e) {
} catch (\Exception $e) {
$errorMessage = $this->l10n->t('The notes folder is not accessible: %s', $e->getMessage());
}
@ -110,7 +106,10 @@ class NotesController extends Controller {
public function get($id) {
// save the last viewed note
$this->settings->setUserValue(
$this->userId, $this->appName, 'notesLastViewedNote', $id
$this->userId,
$this->appName,
'notesLastViewedNote',
$id
);
return $this->respond(function () use ($id) {
@ -124,10 +123,13 @@ class NotesController extends Controller {
*
* @param string $content
*/
public function create($content='', $category=null) {
public function create($content = '', $category = null) {
$note = $this->notesService->create($this->userId);
$note = $this->notesService->update(
$note->getId(), $content, $this->userId, $category
$note->getId(),
$content,
$this->userId,
$category
);
return new DataResponse($note);
}
@ -189,5 +191,4 @@ class NotesController extends Controller {
return [];
});
}
}

View File

@ -1,13 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Controller;
@ -51,5 +42,4 @@ class PageController extends Controller {
return $response;
}
}

View File

@ -1,5 +1,6 @@
<?php
namespace OCA\Notes\Controller;
use OCP\AppFramework\Controller;
use OCP\IConfig;
@ -10,8 +11,8 @@ use OCP\Files\IRootFolder;
use OCP\AppFramework\Http\JSONResponse;
use OCA\Notes\Service\SettingsService;
class SettingsController extends Controller
{
class SettingsController extends Controller {
private $service;
private $userSession;

View File

@ -1,15 +1,21 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*/
namespace OCA\Notes\Db;
use OCP\AppFramework\Db\Entity;
/**
* Class Meta
* @method string getUserId()
* @method void setUserId(string $value)
* @method integer getFileId()
* @method void setFileId(integer $value)
* @method integer getLastUpdate()
* @method void setLastUpdate(integer $value)
* @method string getEtag()
* @method void setEtag(string $value)
* @package OCA\Notes\Db
*/
class Meta extends Entity {
public $userId;

View File

@ -1,29 +1,24 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*/
namespace OCA\Notes\Db;
use OCP\IDBConnection;
use OCP\AppFramework\Db\Mapper;
use OCP\AppFramework\Db\QBMapper;
use OCP\DB\QueryBuilder\IQueryBuilder;
class MetaMapper extends Mapper {
class MetaMapper extends QBMapper {
public function __construct(IDBConnection $db) {
parent::__construct($db, 'notes_meta');
}
public function getAll($userId) {
$sql = 'SELECT * FROM `*PREFIX*notes_meta` WHERE user_id=?';
return $this->findEntities($sql, [$userId]);
}
public function get($userId, $fileId) {
$sql = 'SELECT * FROM `*PREFIX*notes_meta` WHERE user_id=? AND file_id=?';
return $this->findEntity($sql, [$userId, $fileId]);
$qb = $this->db->getQueryBuilder();
$qb->select('*')
->from('*PREFIX*notes_meta')
->where(
$qb->expr()->eq('user_id', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR))
);
return $this->findEntities($qb);
}
}

View File

@ -1,20 +1,11 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Db;
use OCP\Files\File;
use OCP\Files\Folder;
use OCP\AppFramework\Db\Entity;
use League\Flysystem\FileNotFoundException;
/**
* Class Note
* @method integer getId()
@ -56,45 +47,46 @@ class Note extends Entity {
* @param File $file
* @return static
*/
public static function fromFile(File $file, Folder $notesFolder, $tags=[], $onlyMeta=false) {
public static function fromFile(File $file, Folder $notesFolder, $tags = [], $onlyMeta = false) {
$note = new static();
$note->setId($file->getId());
if(!$onlyMeta) {
if (!$onlyMeta) {
$fileContent=$file->getContent();
if($fileContent===false){
throw new FileNotFoundException("File not found");
if ($fileContent===false) {
throw new \Exception("File not found");
}
$note->setContent(self::convertEncoding($fileContent));
}
$note->setModified($file->getMTime());
$note->setTitle(pathinfo($file->getName(),PATHINFO_FILENAME)); // remove extension
$note->setTitle(pathinfo($file->getName(), PATHINFO_FILENAME)); // remove extension
$subdir = substr(dirname($file->getPath()), strlen($notesFolder->getPath())+1);
$note->setCategory($subdir ? $subdir : '');
if(is_array($tags) && in_array(\OC\Tags::TAG_FAVORITE, $tags)) {
if (is_array($tags) && in_array(\OC\Tags::TAG_FAVORITE, $tags)) {
$note->setFavorite(true);
//unset($tags[array_search(\OC\Tags::TAG_FAVORITE, $tags)]);
}
if(!$onlyMeta) {
if (!$onlyMeta) {
$note->updateETag();
}
$note->resetUpdatedFields();
return $note;
}
/**
* @param File $file
* @return static
*/
public static function fromException($message,File $file,Folder $notesFolder,$tags=[]){
public static function fromException($message, File $file, Folder $notesFolder, $tags = []) {
$note = new static();
$note->setId($file->getId());
$note->setErrorMessage($message);
$note->setError(true);
$note->setContent($message);
$note->setModified(null);
$note->setTitle(pathinfo($file->getName(),PATHINFO_FILENAME)); // remove extension
$note->setTitle(pathinfo($file->getName(), PATHINFO_FILENAME)); // remove extension
$subdir = substr(dirname($file->getPath()), strlen($notesFolder->getPath())+1);
$note->setCategory($subdir ? $subdir : null);
if(is_array($tags) && in_array(\OC\Tags::TAG_FAVORITE, $tags)) {
if (is_array($tags) && in_array(\OC\Tags::TAG_FAVORITE, $tags)) {
$note->setFavorite(true);
//unset($tags[array_search(\OC\Tags::TAG_FAVORITE, $tags)]);
}
@ -104,7 +96,7 @@ class Note extends Entity {
}
private static function convertEncoding($str) {
if(!mb_check_encoding($str, 'UTF-8')) {
if (!mb_check_encoding($str, 'UTF-8')) {
$str = mb_convert_encoding($str, 'UTF-8');
}
return $str;
@ -113,8 +105,8 @@ class Note extends Entity {
private function updateETag() {
// collect all relevant attributes
$data = '';
foreach(get_object_vars($this) as $key => $val) {
if($key!=='etag') {
foreach (get_object_vars($this) as $key => $val) {
if ($key!=='etag') {
$data .= $val;
}
}

View File

@ -1,10 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*/
namespace OCA\Notes\Service;
@ -29,18 +23,18 @@ class MetaService {
$metas = $this->metaMapper->getAll($userId);
$metas = $this->getIndexedArray($metas, 'fileId');
$notes = $this->getIndexedArray($notes, 'id');
foreach($metas as $id=>$meta) {
if(!array_key_exists($id, $notes)) {
foreach ($metas as $id => $meta) {
if (!array_key_exists($id, $notes)) {
// DELETE obsolete notes
$this->metaMapper->delete($meta);
unset($metas[$id]);
}
}
foreach($notes as $id=>$note) {
if(!array_key_exists($id, $metas)) {
foreach ($notes as $id => $note) {
if (!array_key_exists($id, $metas)) {
// INSERT new notes
$metas[$note->getId()] = $this->create($userId, $note);
} elseif($note->getEtag()!==$metas[$id]->getEtag()) {
} elseif ($note->getEtag()!==$metas[$id]->getEtag()) {
// UPDATE changed notes
$meta = $metas[$id];
$this->updateIfNeeded($meta, $note);
@ -53,7 +47,7 @@ class MetaService {
$property = ucfirst($property);
$getter = 'get'.$property;
$result = array();
foreach($data as $entity) {
foreach ($data as $entity) {
$result[$entity->$getter()] = $entity;
}
return $result;
@ -66,7 +60,7 @@ class MetaService {
}
private function updateIfNeeded(&$meta, $note) {
if($note->getEtag()!==$meta->getEtag()) {
if ($note->getEtag()!==$meta->getEtag()) {
$meta->setEtag($note->getEtag());
$meta->setLastUpdate(time());
$this->metaMapper->update($meta);

View File

@ -1,13 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Service;
@ -18,4 +9,5 @@ use Exception;
*
* @package OCA\Notes\Service
*/
class NoteDoesNotExistException extends Exception {}
class NoteDoesNotExistException extends Exception {
}

View File

@ -1,11 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
*/
namespace OCA\Notes\Service;
@ -16,4 +9,5 @@ use Exception;
*
* @package OCA\Notes\Service
*/
class NotesFolderException extends Exception {}
class NotesFolderException extends Exception {
}

View File

@ -1,13 +1,4 @@
<?php
/**
* Nextcloud - Notes
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\Notes\Service;
@ -17,13 +8,11 @@ use OCP\Files\IRootFolder;
use OCP\Files\Folder;
use OCP\ILogger;
use OCP\Encryption\Exceptions\GenericEncryptionException;
use League\Flysystem\FileNotFoundException;
use OCA\Notes\Db\Note;
use OCA\Notes\Service\SettingsService;
use OCP\IConfig;
use OCP\IUserSession;
/**
* Class NotesService
*
@ -46,7 +35,7 @@ class NotesService {
* @param \OCA\Notes\Service\SettingsService $settings
* @param String $appName
*/
public function __construct (IRootFolder $root, IL10N $l10n, ILogger $logger, IConfig $config, SettingsService $settings, $appName) {
public function __construct(IRootFolder $root, IL10N $l10n, ILogger $logger, IConfig $config, SettingsService $settings, $appName) {
$this->root = $root;
$this->l10n = $l10n;
$this->logger = $logger;
@ -60,22 +49,22 @@ class NotesService {
* @param string $userId
* @return array with all notes in the current directory
*/
public function getAll ($userId, $onlyMeta=false) {
public function getAll($userId, $onlyMeta = false) {
$notesFolder = $this->getFolderForUser($userId);
$notes = $this->gatherNoteFiles($notesFolder);
$filesById = [];
foreach($notes as $note) {
foreach ($notes as $note) {
$filesById[$note->getId()] = $note;
}
$tagger = \OC::$server->getTagManager()->load('files');
if($tagger===null) {
if ($tagger===null) {
$tags = [];
} else {
$tags = $tagger->getTagsForObjects(array_keys($filesById));
}
$notes = [];
foreach($filesById as $id=>$file) {
foreach ($filesById as $id => $file) {
$notes[] = $this->getNote($file, $notesFolder, array_key_exists($id, $tags) ? $tags[$id] : [], $onlyMeta);
}
@ -90,14 +79,14 @@ class NotesService {
* @throws NoteDoesNotExistException if note does not exist
* @return Note
*/
public function get ($id, $userId) {
public function get($id, $userId) {
$folder = $this->getFolderForUser($userId);
return $this->getNote($this->getFileById($folder, $id), $folder, $this->getTags($id));
}
private function getTags ($id) {
private function getTags($id) {
$tagger = \OC::$server->getTagManager()->load('files');
if($tagger===null) {
if ($tagger===null) {
$tags = [];
} else {
$tags = $tagger->getTagsForObjects([$id]);
@ -105,15 +94,13 @@ class NotesService {
return array_key_exists($id, $tags) ? $tags[$id] : [];
}
private function getNote($file, $notesFolder, $tags=[], $onlyMeta=false) {
private function getNote($file, $notesFolder, $tags = [], $onlyMeta = false) {
$id = $file->getId();
try {
$note = Note::fromFile($file, $notesFolder, $tags, $onlyMeta);
} catch(FileNotFoundException $e){
$note = Note::fromException($this->l10n->t('File error').': ('.$file->getName().') '.$e->getMessage(), $file, $notesFolder, array_key_exists($id, $tags) ? $tags[$id] : []);
} catch(GenericEncryptionException $e) {
} catch (GenericEncryptionException $e) {
$note = Note::fromException($this->l10n->t('Encryption Error').': ('.$file->getName().') '.$e->getMessage(), $file, $notesFolder, array_key_exists($id, $tags) ? $tags[$id] : []);
} catch(\Exception $e) {
} catch (\Exception $e) {
$note = Note::fromException($this->l10n->t('Error').': ('.$file->getName().') '.$e->getMessage(), $file, $notesFolder, array_key_exists($id, $tags) ? $tags[$id] : []);
}
return $note;
@ -126,7 +113,7 @@ class NotesService {
* @see update for setting note content
* @return Note the newly created note
*/
public function create ($userId) {
public function create($userId) {
$title = $this->l10n->t('New note');
$folder = $this->getFolderForUser($userId);
@ -149,16 +136,17 @@ class NotesService {
* Updates a note. Be sure to check the returned note since the title is
* dynamically generated and filename conflicts are resolved
* @param int $id the id of the note used to update
* @param string $content the content which will be written into the note
* @param string|null $content the content which will be written into the note
* the title is generated from the first line of the content
* @param string|null $category the category in which the note should be saved
* @param int $mtime time of the note modification (optional)
* @throws NoteDoesNotExistException if note does not exist
* @return \OCA\Notes\Db\Note the updated note
*/
public function update ($id, $content, $userId, $category=null, $mtime=0) {
public function update($id, $content, $userId, $category = null, $mtime = 0) {
$notesFolder = $this->getFolderForUser($userId);
$file = $this->getFileById($notesFolder, $id);
$title = $this->getSafeTitleFromContent( $content===null ? $file->getContent() : $content );
$title = $this->getSafeTitleFromContent($content===null ? $file->getContent() : $content);
// rename/move file with respect to title/category
@ -169,15 +157,17 @@ class NotesService {
$fileSuffix = '.' . pathinfo($file->getName(), PATHINFO_EXTENSION);
// detect (new) folder path based on category name
if($category===null) {
if ($category===null) {
$basePath = $currentBasePath;
} else {
$basePath = $notesFolder->getPath();
if(!empty($category)) {
if (!empty($category)) {
// sanitise path
$cats = explode('/', $category);
$cats = array_map([$this, 'sanitisePath'], $cats);
$cats = array_filter($cats, function($str) { return !empty($str); });
$cats = array_filter($cats, function ($str) {
return !empty($str);
});
$basePath .= '/'.implode('/', $cats);
}
}
@ -187,23 +177,23 @@ class NotesService {
$newFilePath = $basePath . '/' . $this->generateFileName($folder, $title, $fileSuffix, $id);
// if the current path is not the new path, the file has to be renamed
if($currentFilePath !== $newFilePath) {
if ($currentFilePath !== $newFilePath) {
$file->move($newFilePath);
}
if($currentBasePath !== $basePath) {
if ($currentBasePath !== $basePath) {
$this->deleteEmptyFolder($notesFolder, $this->root->get($currentBasePath));
}
} catch(\OCP\Files\NotPermittedException $e) {
} catch (\OCP\Files\NotPermittedException $e) {
$this->logger->error('Moving note '.$id.' ('.$title.') to the desired target is not allowed. Please check the note\'s target category ('.$category.').', ['app' => $this->appName]);
} catch(\Exception $e) {
} catch (\Exception $e) {
$this->logger->error('Moving note '.$id.' ('.$title.') to the desired target has failed with a '.get_class($e).': '.$e->getMessage(), ['app' => $this->appName]);
}
if($content !== null) {
if ($content !== null) {
$file->putContent($content);
}
if($mtime) {
if ($mtime) {
$file->touch($mtime);
}
@ -217,17 +207,18 @@ class NotesService {
* @throws NoteDoesNotExistException if note does not exist
* @return boolean the new favorite state of the note
*/
public function favorite ($id, $favorite, $userId){
public function favorite($id, $favorite, $userId) {
$folder = $this->getFolderForUser($userId);
$file = $this->getFileById($folder, $id);
if(!$this->isNote($file)) {
if (!$this->isNote($file)) {
throw new NoteDoesNotExistException();
}
$tagger = \OC::$server->getTagManager()->load('files');
if($favorite)
if ($favorite) {
$tagger->addToFavorites($id);
else
} else {
$tagger->removeFromFavorites($id);
}
$tags = $tagger->getTagsForObjects([$id]);
return array_key_exists($id, $tags) && in_array(\OC\Tags::TAG_FAVORITE, $tags[$id]);
@ -241,7 +232,7 @@ class NotesService {
* @throws NoteDoesNotExistException if note does not
* exist
*/
public function delete ($id, $userId) {
public function delete($id, $userId) {
$notesFolder = $this->getFolderForUser($userId);
$file = $this->getFileById($notesFolder, $id);
$parent = $file->getParent();
@ -286,7 +277,7 @@ class NotesService {
$title = trim($splitContent[0]);
// ensure that title is not empty
if(empty($title)) {
if (empty($title)) {
$title = $this->l10n->t('New note');
}
@ -302,10 +293,10 @@ class NotesService {
* @throws NoteDoesNotExistException
* @return \OCP\Files\File
*/
private function getFileById ($folder, $id) {
private function getFileById($folder, $id) {
$file = $folder->getById($id);
if(count($file) <= 0 || !$this->isNote($file[0])) {
if (count($file) <= 0 || !$this->isNote($file[0])) {
throw new NoteDoesNotExistException();
}
return $file[0];
@ -316,7 +307,7 @@ class NotesService {
* @return boolean true if folder is accessible, or Exception otherwise
*/
public function checkNotesFolder($userId) {
$folder = $this->getFolderForUser($userId);
$this->getFolderForUser($userId);
return true;
}
@ -324,11 +315,11 @@ class NotesService {
* @param string $userId the user id
* @return Folder
*/
private function getFolderForUser ($userId) {
private function getFolderForUser($userId) {
$path = '/' . $userId . '/files/' . $this->settings->get($userId, 'notesPath');
try {
$folder = $this->getOrCreateFolder($path);
} catch(\Exception $e) {
} catch (\Exception $e) {
throw new NotesFolderException($path);
}
return $folder;
@ -358,7 +349,7 @@ class NotesService {
$content = $folder->getDirectoryListing();
$isEmpty = !count($content);
$isNotesFolder = $folder->getPath()===$notesFolder->getPath();
if($isEmpty && !$isNotesFolder) {
if ($isEmpty && !$isNotesFolder) {
$this->logger->info('Deleting empty category folder '.$folder->getPath(), ['app' => $this->appName]);
$parent = $folder->getParent();
$folder->delete();
@ -379,7 +370,7 @@ class NotesService {
* @return string the resolved filename to prevent overwriting different
* files with the same title
*/
private function generateFileName (Folder $folder, $title, $suffix, $id) {
private function generateFileName(Folder $folder, $title, $suffix, $id) {
$path = $title . $suffix;
// if file does not exist, that name has not been taken. Similar we don't
@ -389,10 +380,13 @@ class NotesService {
} else {
// increments name (2) to name (3)
$match = preg_match('/\((?P<id>\d+)\)$/u', $title, $matches);
if($match) {
if ($match) {
$newId = ((int) $matches['id']) + 1;
$newTitle = preg_replace('/(.*)\s\((\d+)\)$/u',
'$1 (' . $newId . ')', $title);
$newTitle = preg_replace(
'/(.*)\s\((\d+)\)$/u',
'$1 (' . $newId . ')',
$title
);
} else {
$newTitle = $title . ' (2)';
}
@ -405,15 +399,15 @@ class NotesService {
* @param Folder $folder
* @return array
*/
private function gatherNoteFiles ($folder) {
private function gatherNoteFiles($folder) {
$notes = [];
$nodes = $folder->getDirectoryListing();
foreach($nodes as $node) {
if($node->getType() === FileInfo::TYPE_FOLDER) {
foreach ($nodes as $node) {
if ($node->getType() === FileInfo::TYPE_FOLDER) {
$notes = array_merge($notes, $this->gatherNoteFiles($node));
continue;
}
if($this->isNote($node)) {
if ($this->isNote($node)) {
$notes[] = $node;
}
}
@ -430,14 +424,15 @@ class NotesService {
private function isNote($file) {
$allowedExtensions = ['txt', 'org', 'markdown', 'md', 'note'];
if($file->getType() !== 'file') return false;
if ($file->getType() !== 'file') {
return false;
}
$ext = pathinfo($file->getName(), PATHINFO_EXTENSION);
$iext = strtolower($ext);
if(!in_array($iext, $allowedExtensions)) {
if (!in_array($iext, $allowedExtensions)) {
return false;
}
return true;
}
}

View File

@ -1,6 +1,7 @@
<?php
namespace OCA\Notes\Service;
use OCP\AppFramework\Controller;
use OCP\IConfig;
@ -10,15 +11,15 @@ use OCP\IUserSession;
use OCP\Files\IRootFolder;
use OCP\AppFramework\Http\JSONResponse;
class SettingsService
{
class SettingsService {
private $config;
private $root;
/* Default values */
private $defaults = [
"notesPath" => "Notes",
"fileSuffix" => ".txt",
'notesPath' => 'Notes',
'fileSuffix' => '.txt',
];
public function __construct(
@ -32,8 +33,8 @@ class SettingsService
*/
public function set($uid, $settings) {
// remove illegal, empty and default settings
foreach($settings as $name => $value) {
if(!array_key_exists($name, $this->defaults)
foreach ($settings as $name => $value) {
if (!array_key_exists($name, $this->defaults)
|| empty($value)
|| $value === $this->defaults[$name]
) {
@ -45,10 +46,10 @@ class SettingsService
public function getAll($uid) {
$settings = json_decode($this->config->getUserValue($uid, 'notes', 'settings'));
if(is_object($settings)) {
if (is_object($settings)) {
// use default for empty settings
foreach($this->defaults as $name => $defaultValue) {
if(!property_exists($settings, $name) || empty($settings->{$name})) {
foreach ($this->defaults as $name => $defaultValue) {
if (!property_exists($settings, $name) || empty($settings->{$name})) {
$settings->{$name} = $defaultValue;
}
}
@ -63,7 +64,7 @@ class SettingsService
*/
public function get($uid, $name) {
$settings = $this->getAll($uid);
if(property_exists($settings, $name)) {
if (property_exists($settings, $name)) {
return $settings->{$name};
} else {
throw new \OCP\PreConditionNotMetException('Setting '.$name.' not found for user '.$uid.'.');

32
phpcs.xml Normal file
View File

@ -0,0 +1,32 @@
<?xml version="1.0"?>
<ruleset name="MyStandard">
<description>
PSR2 with changes:
* tabs instead of spaces (https://gist.github.com/gsherwood/9d22f634c57f990a7c64)
* bracers on end of line instead new line
</description>
<!-- tabs -->
<arg name="tab-width" value="4"/>
<rule ref="PSR2">
<!-- bracers -->
<exclude name="Squiz.Functions.MultiLineFunctionDeclaration.BraceOnSameLine" />
<exclude name="PSR2.Classes.ClassDeclaration.OpenBraceNewLine" />
<!-- tabs -->
<exclude name="Generic.WhiteSpace.DisallowTabIndent"/>
</rule>
<!-- tabs -->
<rule ref="Generic.WhiteSpace.DisallowSpaceIndent"/>
<rule ref="Generic.WhiteSpace.ScopeIndent">
<properties>
<property name="indent" value="4"/>
<property name="tabIndent" value="true"/>
</properties>
</rule>
<!-- bracers -->
<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie" />
<rule ref="Generic.Classes.OpeningBraceSameLine"/>
</ruleset>