diff --git a/public_html/js/Api.js b/public_html/js/Api.js index 63db4057..3d195b92 100644 --- a/public_html/js/Api.js +++ b/public_html/js/Api.js @@ -2,130 +2,130 @@ var App = App || {}; App.API = function(_, jQuery, promise, appState) { - var baseUrl = '/api/'; - var AJAX_UNSENT = 0; - var AJAX_OPENED = 1; - var AJAX_HEADERS_RECEIVED = 2; - var AJAX_LOADING = 3; - var AJAX_DONE = 4; + var baseUrl = '/api/'; + var AJAX_UNSENT = 0; + var AJAX_OPENED = 1; + var AJAX_HEADERS_RECEIVED = 2; + var AJAX_LOADING = 3; + var AJAX_DONE = 4; - var cache = {}; + var cache = {}; - function get(url, data) { - return request('GET', url, data); - } + function get(url, data) { + return request('GET', url, data); + } - function post(url, data) { - return request('POST', url, data); - } + function post(url, data) { + return request('POST', url, data); + } - function put(url, data) { - return request('PUT', url, data); - } + function put(url, data) { + return request('PUT', url, data); + } - function _delete(url, data) { - return request('DELETE', url, data); - } + function _delete(url, data) { + return request('DELETE', url, data); + } - function getCacheKey(method, url, data) { - return JSON.stringify({method: method, url: url, data: data}); - } + function getCacheKey(method, url, data) { + return JSON.stringify({method: method, url: url, data: data}); + } - function clearCache() { - cache = {}; - } + function clearCache() { + cache = {}; + } - function request(method, url, data) { - if (method === 'GET') { - return requestWithCache(method, url, data); - } - clearCache(); - return requestWithAjax(method, url, data); - } + function request(method, url, data) { + if (method === 'GET') { + return requestWithCache(method, url, data); + } + clearCache(); + return requestWithAjax(method, url, data); + } - function requestWithCache(method, url, data) { - var cacheKey = getCacheKey(method, url, data); - if (_.has(cache, cacheKey)) { - return promise.make(function(resolve, reject) { - resolve(cache[cacheKey]); - }); - } + function requestWithCache(method, url, data) { + var cacheKey = getCacheKey(method, url, data); + if (_.has(cache, cacheKey)) { + return promise.make(function(resolve, reject) { + resolve(cache[cacheKey]); + }); + } - return promise.make(function(resolve, reject) { - promise.wait(requestWithAjax(method, url, data)) - .then(function(response) { - setCache(method, url, data, response); - resolve(response); - }).fail(function(response) { - reject(response); - }); - }); - } + return promise.make(function(resolve, reject) { + promise.wait(requestWithAjax(method, url, data)) + .then(function(response) { + setCache(method, url, data, response); + resolve(response); + }).fail(function(response) { + reject(response); + }); + }); + } - function setCache(method, url, data, response) { - var cacheKey = getCacheKey(method, url, data); - cache[cacheKey] = response; - } + function setCache(method, url, data, response) { + var cacheKey = getCacheKey(method, url, data); + cache[cacheKey] = response; + } - function requestWithAjax(method, url, data) { - var fullUrl = baseUrl + '/' + url; - fullUrl = fullUrl.replace(/\/{2,}/, '/'); + function requestWithAjax(method, url, data) { + var fullUrl = baseUrl + '/' + url; + fullUrl = fullUrl.replace(/\/{2,}/, '/'); - var xhr = null; - var apiPromise = promise.make(function(resolve, reject) { - var options = { - headers: { - 'X-Authorization-Token': appState.get('loginToken') || '', - }, - success: function(data, textStatus, xhr) { - resolve({ - status: xhr.status, - json: stripMeta(data)}); - }, - error: function(xhr, textStatus, errorThrown) { - reject({ - status: xhr.status, - json: xhr.responseJSON ? - stripMeta(xhr.responseJSON) : - {error: errorThrown}}); - }, - type: method, - url: fullUrl, - data: data, - cache: false, - }; - if (data instanceof FormData) { - options.processData = false; - options.contentType = false; - } - xhr = jQuery.ajax(options); - }); - apiPromise.xhr = xhr; - return apiPromise; - } + var xhr = null; + var apiPromise = promise.make(function(resolve, reject) { + var options = { + headers: { + 'X-Authorization-Token': appState.get('loginToken') || '', + }, + success: function(data, textStatus, xhr) { + resolve({ + status: xhr.status, + json: stripMeta(data)}); + }, + error: function(xhr, textStatus, errorThrown) { + reject({ + status: xhr.status, + json: xhr.responseJSON ? + stripMeta(xhr.responseJSON) : + {error: errorThrown}}); + }, + type: method, + url: fullUrl, + data: data, + cache: false, + }; + if (data instanceof FormData) { + options.processData = false; + options.contentType = false; + } + xhr = jQuery.ajax(options); + }); + apiPromise.xhr = xhr; + return apiPromise; + } - function stripMeta(data) { - var result = {}; - _.each(data, function(v, k) { - if (!k.match(/^__/)) { - result[k] = v; - } - }); - return result; - } + function stripMeta(data) { + var result = {}; + _.each(data, function(v, k) { + if (!k.match(/^__/)) { + result[k] = v; + } + }); + return result; + } - return { - get: get, - post: post, - put: put, - delete: _delete, + return { + get: get, + post: post, + put: put, + delete: _delete, - AJAX_UNSENT: AJAX_UNSENT, - AJAX_OPENED: AJAX_OPENED, - AJAX_HEADERS_RECEIVED: AJAX_HEADERS_RECEIVED, - AJAX_LOADING: AJAX_LOADING, - AJAX_DONE: AJAX_DONE, - }; + AJAX_UNSENT: AJAX_UNSENT, + AJAX_OPENED: AJAX_OPENED, + AJAX_HEADERS_RECEIVED: AJAX_HEADERS_RECEIVED, + AJAX_LOADING: AJAX_LOADING, + AJAX_DONE: AJAX_DONE, + }; }; diff --git a/public_html/js/Auth.js b/public_html/js/Auth.js index 38ddc97a..468b571c 100644 --- a/public_html/js/Auth.js +++ b/public_html/js/Auth.js @@ -2,198 +2,198 @@ var App = App || {}; App.Auth = function(_, jQuery, util, api, appState, promise) { - var privileges = { - register: 'register', - listUsers: 'listUsers', - viewUsers: 'viewUsers', - viewAllAccessRanks: 'viewAllAccessRanks', - viewAllEmailAddresses: 'viewAllEmailAddresses', - changeAccessRank: 'changeAccessRank', - changeOwnAvatarStyle: 'changeOwnAvatarStyle', - changeOwnEmailAddress: 'changeOwnEmailAddress', - changeOwnName: 'changeOwnName', - changeOwnPassword: 'changeOwnPassword', - changeAllAvatarStyles: 'changeAllAvatarStyles', - changeAllEmailAddresses: 'changeAllEmailAddresses', - changeAllNames: 'changeAllNames', - changeAllPasswords: 'changeAllPasswords', - deleteOwnAccount: 'deleteOwnAccount', - deleteAllAccounts: 'deleteAllAccounts', - banUsers: 'banUsers', + var privileges = { + register: 'register', + listUsers: 'listUsers', + viewUsers: 'viewUsers', + viewAllAccessRanks: 'viewAllAccessRanks', + viewAllEmailAddresses: 'viewAllEmailAddresses', + changeAccessRank: 'changeAccessRank', + changeOwnAvatarStyle: 'changeOwnAvatarStyle', + changeOwnEmailAddress: 'changeOwnEmailAddress', + changeOwnName: 'changeOwnName', + changeOwnPassword: 'changeOwnPassword', + changeAllAvatarStyles: 'changeAllAvatarStyles', + changeAllEmailAddresses: 'changeAllEmailAddresses', + changeAllNames: 'changeAllNames', + changeAllPasswords: 'changeAllPasswords', + deleteOwnAccount: 'deleteOwnAccount', + deleteAllAccounts: 'deleteAllAccounts', + banUsers: 'banUsers', - listPosts: 'listPosts', - viewPosts: 'viewPosts', - uploadPosts: 'uploadPosts', - uploadPostsAnonymously: 'uploadPostsAnonymously', - deletePosts: 'deletePosts', - featurePosts: 'featurePosts', - changePostSafety: 'changePostSafety', - changePostSource: 'changePostSource', - changePostTags: 'changePostTags', - changePostContent: 'changePostContent', - changePostThumbnail: 'changePostThumbnail', - changePostRelations: 'changePostRelations', - changePostFlags: 'changePostFlags', + listPosts: 'listPosts', + viewPosts: 'viewPosts', + uploadPosts: 'uploadPosts', + uploadPostsAnonymously: 'uploadPostsAnonymously', + deletePosts: 'deletePosts', + featurePosts: 'featurePosts', + changePostSafety: 'changePostSafety', + changePostSource: 'changePostSource', + changePostTags: 'changePostTags', + changePostContent: 'changePostContent', + changePostThumbnail: 'changePostThumbnail', + changePostRelations: 'changePostRelations', + changePostFlags: 'changePostFlags', - addPostNotes: 'addPostNotes', - editPostNotes: 'editPostNotes', - deletePostNotes: 'deletePostNotes', + addPostNotes: 'addPostNotes', + editPostNotes: 'editPostNotes', + deletePostNotes: 'deletePostNotes', - listComments: 'listComments', - addComments: 'addComments', - editOwnComments: 'editOwnComments', - editAllComments: 'editAllComments', - deleteOwnComments: 'deleteOwnComments', - deleteAllComments: 'deleteAllComments', - deleteTags: 'deleteTags', - mergeTags: 'mergeTags', + listComments: 'listComments', + addComments: 'addComments', + editOwnComments: 'editOwnComments', + editAllComments: 'editAllComments', + deleteOwnComments: 'deleteOwnComments', + deleteAllComments: 'deleteAllComments', + deleteTags: 'deleteTags', + mergeTags: 'mergeTags', - listTags: 'listTags', - massTag: 'massTag', - changeTagName: 'changeTagName', - changeTagCategory: 'changeTagCategory', - changeTagImplications: 'changeTagImplications', - changeTagSuggestions: 'changeTagSuggestions', - banTags: 'banTags', + listTags: 'listTags', + massTag: 'massTag', + changeTagName: 'changeTagName', + changeTagCategory: 'changeTagCategory', + changeTagImplications: 'changeTagImplications', + changeTagSuggestions: 'changeTagSuggestions', + banTags: 'banTags', - viewHistory: 'viewHistory', - }; + viewHistory: 'viewHistory', + }; - function loginFromCredentials(userNameOrEmail, password, remember) { - return promise.make(function(resolve, reject) { - promise.wait(api.post('/login', {userNameOrEmail: userNameOrEmail, password: password})) - .then(function(response) { - updateAppState(response); - jQuery.cookie( - 'auth', - response.json.token.name, - remember ? { expires: 365 } : {}); - resolve(response); - }).fail(function(response) { - reject(response); - }); - }); - } + function loginFromCredentials(userNameOrEmail, password, remember) { + return promise.make(function(resolve, reject) { + promise.wait(api.post('/login', {userNameOrEmail: userNameOrEmail, password: password})) + .then(function(response) { + updateAppState(response); + jQuery.cookie( + 'auth', + response.json.token.name, + remember ? { expires: 365 } : {}); + resolve(response); + }).fail(function(response) { + reject(response); + }); + }); + } - function loginFromToken(token, isFromCookie) { - return promise.make(function(resolve, reject) { - var fd = { - token: token, - isFromCookie: isFromCookie - }; - promise.wait(api.post('/login', fd)) - .then(function(response) { - updateAppState(response); - resolve(response); - }).fail(function(response) { - reject(response); - }); - }); - } + function loginFromToken(token, isFromCookie) { + return promise.make(function(resolve, reject) { + var fd = { + token: token, + isFromCookie: isFromCookie + }; + promise.wait(api.post('/login', fd)) + .then(function(response) { + updateAppState(response); + resolve(response); + }).fail(function(response) { + reject(response); + }); + }); + } - function loginAnonymous() { - return promise.make(function(resolve, reject) { - promise.wait(api.post('/login')) - .then(function(response) { - updateAppState(response); - resolve(response); - }).fail(function(response) { - reject(response); - }); - }); - } + function loginAnonymous() { + return promise.make(function(resolve, reject) { + promise.wait(api.post('/login')) + .then(function(response) { + updateAppState(response); + resolve(response); + }).fail(function(response) { + reject(response); + }); + }); + } - function logout() { - return promise.make(function(resolve, reject) { - jQuery.removeCookie('auth'); - appState.set('loginToken', null); - return promise.wait(loginAnonymous()) - .then(resolve) - .fail(reject); - }); - } + function logout() { + return promise.make(function(resolve, reject) { + jQuery.removeCookie('auth'); + appState.set('loginToken', null); + return promise.wait(loginAnonymous()) + .then(resolve) + .fail(reject); + }); + } - function tryLoginFromCookie() { - return promise.make(function(resolve, reject) { - if (isLoggedIn()) { - resolve(); - return; - } + function tryLoginFromCookie() { + return promise.make(function(resolve, reject) { + if (isLoggedIn()) { + resolve(); + return; + } - var authCookie = jQuery.cookie('auth'); - if (!authCookie) { - reject(); - return; - } + var authCookie = jQuery.cookie('auth'); + if (!authCookie) { + reject(); + return; + } - promise.wait(loginFromToken(authCookie, true)) - .then(function(response) { - resolve(); - }).fail(function(response) { - jQuery.removeCookie('auth'); - reject(); - }); - }); - } + promise.wait(loginFromToken(authCookie, true)) + .then(function(response) { + resolve(); + }).fail(function(response) { + jQuery.removeCookie('auth'); + reject(); + }); + }); + } - function updateAppState(response) { - appState.set('privileges', response.json.privileges || []); - appState.set('loginToken', response.json.token && response.json.token.name); - appState.set('loggedIn', response.json.user && !!response.json.user.id); - appState.set('loggedInUser', response.json.user); - } + function updateAppState(response) { + appState.set('privileges', response.json.privileges || []); + appState.set('loginToken', response.json.token && response.json.token.name); + appState.set('loggedIn', response.json.user && !!response.json.user.id); + appState.set('loggedInUser', response.json.user); + } - function isLoggedIn(userName) { - if (!appState.get('loggedIn')) { - return false; - } - if (typeof(userName) !== 'undefined') { - if (getCurrentUser().name !== userName) { - return false; - } - } - return true; - } + function isLoggedIn(userName) { + if (!appState.get('loggedIn')) { + return false; + } + if (typeof(userName) !== 'undefined') { + if (getCurrentUser().name !== userName) { + return false; + } + } + return true; + } - function getCurrentUser() { - return appState.get('loggedInUser'); - } + function getCurrentUser() { + return appState.get('loggedInUser'); + } - function getCurrentPrivileges() { - return appState.get('privileges'); - } + function getCurrentPrivileges() { + return appState.get('privileges'); + } - function updateCurrentUser(user) { - if (user.id !== getCurrentUser().id) { - throw new Error('Cannot set current user to other user this way.'); - } - appState.set('loggedInUser', user); - } + function updateCurrentUser(user) { + if (user.id !== getCurrentUser().id) { + throw new Error('Cannot set current user to other user this way.'); + } + appState.set('loggedInUser', user); + } - function hasPrivilege(privilege) { - return _.contains(getCurrentPrivileges(), privilege); - } + function hasPrivilege(privilege) { + return _.contains(getCurrentPrivileges(), privilege); + } - function startObservingLoginChanges(listenerName, callback) { - appState.startObserving('loggedInUser', listenerName, callback); - } + function startObservingLoginChanges(listenerName, callback) { + appState.startObserving('loggedInUser', listenerName, callback); + } - return { - loginFromCredentials: loginFromCredentials, - loginFromToken: loginFromToken, - loginAnonymous: loginAnonymous, - tryLoginFromCookie: tryLoginFromCookie, - logout: logout, + return { + loginFromCredentials: loginFromCredentials, + loginFromToken: loginFromToken, + loginAnonymous: loginAnonymous, + tryLoginFromCookie: tryLoginFromCookie, + logout: logout, - startObservingLoginChanges: startObservingLoginChanges, - isLoggedIn: isLoggedIn, - getCurrentUser: getCurrentUser, - updateCurrentUser: updateCurrentUser, - getCurrentPrivileges: getCurrentPrivileges, - hasPrivilege: hasPrivilege, + startObservingLoginChanges: startObservingLoginChanges, + isLoggedIn: isLoggedIn, + getCurrentUser: getCurrentUser, + updateCurrentUser: updateCurrentUser, + getCurrentPrivileges: getCurrentPrivileges, + hasPrivilege: hasPrivilege, - privileges: privileges, - }; + privileges: privileges, + }; }; diff --git a/public_html/js/Bootstrap.js b/public_html/js/Bootstrap.js index 23429ade..8f5e98d7 100644 --- a/public_html/js/Bootstrap.js +++ b/public_html/js/Bootstrap.js @@ -2,29 +2,29 @@ var App = App || {}; App.Bootstrap = function(auth, router, promise, presenterManager) { - promise.wait(presenterManager.init()) - .then(function() { - promise.wait(auth.tryLoginFromCookie()) - .then(startRouting) - .fail(function(error) { - promise.wait(auth.loginAnonymous()) - .then(startRouting) - .fail(function() { - console.log(arguments); - window.alert('Fatal authentication error'); - }); - }); - }).fail(function() { - console.log(arguments); - }); + promise.wait(presenterManager.init()) + .then(function() { + promise.wait(auth.tryLoginFromCookie()) + .then(startRouting) + .fail(function(error) { + promise.wait(auth.loginAnonymous()) + .then(startRouting) + .fail(function() { + console.log(arguments); + window.alert('Fatal authentication error'); + }); + }); + }).fail(function() { + console.log(arguments); + }); - function startRouting() { - try { - router.start(); - } catch (err) { - console.log(err); - } - } + function startRouting() { + try { + router.start(); + } catch (err) { + console.log(err); + } + } }; diff --git a/public_html/js/BrowsingSettings.js b/public_html/js/BrowsingSettings.js index 79c8a881..142958d8 100644 --- a/public_html/js/BrowsingSettings.js +++ b/public_html/js/BrowsingSettings.js @@ -1,96 +1,96 @@ var App = App || {}; App.BrowsingSettings = function( - promise, - auth, - api) { + promise, + auth, + api) { - var settings = getDefaultSettings(); + var settings = getDefaultSettings(); - auth.startObservingLoginChanges('browsing-settings', loginStateChanged); + auth.startObservingLoginChanges('browsing-settings', loginStateChanged); - readFromLocalStorage(); - if (auth.isLoggedIn()) { - loginStateChanged(); - } + readFromLocalStorage(); + if (auth.isLoggedIn()) { + loginStateChanged(); + } - function setSettings(newSettings) { - settings = newSettings; - return save(); - } + function setSettings(newSettings) { + settings = newSettings; + return save(); + } - function getSettings() { - return settings; - } + function getSettings() { + return settings; + } - function getDefaultSettings() { - return { - hideDownvoted: true, - endlessScroll: false, - listPosts: { - safe: true, - sketchy: true, - unsafe: true, - }, - keyboardShortcuts: true, - }; - } + function getDefaultSettings() { + return { + hideDownvoted: true, + endlessScroll: false, + listPosts: { + safe: true, + sketchy: true, + unsafe: true, + }, + keyboardShortcuts: true, + }; + } - function loginStateChanged() { - readFromUser(auth.getCurrentUser()); - } + function loginStateChanged() { + readFromUser(auth.getCurrentUser()); + } - function readFromLocalStorage() { - readFromString(localStorage.getItem('browsingSettings')); - } + function readFromLocalStorage() { + readFromString(localStorage.getItem('browsingSettings')); + } - function readFromUser(user) { - readFromString(user.browsingSettings); - } + function readFromUser(user) { + readFromString(user.browsingSettings); + } - function readFromString(string) { - if (!string) { - return; - } + function readFromString(string) { + if (!string) { + return; + } - try { - if (typeof(string) === 'string' || string instanceof String) { - settings = JSON.parse(string); - } else { - settings = string; - } - } catch (e) { - } - } + try { + if (typeof(string) === 'string' || string instanceof String) { + settings = JSON.parse(string); + } else { + settings = string; + } + } catch (e) { + } + } - function saveToLocalStorage() { - localStorage.setItem('browsingSettings', JSON.stringify(settings)); - } + function saveToLocalStorage() { + localStorage.setItem('browsingSettings', JSON.stringify(settings)); + } - function saveToUser(user) { - var formData = { - browsingSettings: JSON.stringify(settings), - }; - return api.post('/users/' + user.name, formData); - } + function saveToUser(user) { + var formData = { + browsingSettings: JSON.stringify(settings), + }; + return api.post('/users/' + user.name, formData); + } - function save() { - return promise.make(function(resolve, reject) { - saveToLocalStorage(); - if (auth.isLoggedIn()) { - promise.wait(saveToUser(auth.getCurrentUser())) - .then(resolve) - .fail(reject); - } else { - resolve(); - } - }); - } + function save() { + return promise.make(function(resolve, reject) { + saveToLocalStorage(); + if (auth.isLoggedIn()) { + promise.wait(saveToUser(auth.getCurrentUser())) + .then(resolve) + .fail(reject); + } else { + resolve(); + } + }); + } - return { - getSettings: getSettings, - setSettings: setSettings, - }; + return { + getSettings: getSettings, + setSettings: setSettings, + }; }; diff --git a/public_html/js/Controls/AutoCompleteInput.js b/public_html/js/Controls/AutoCompleteInput.js index 0c268bd6..99aecf91 100644 --- a/public_html/js/Controls/AutoCompleteInput.js +++ b/public_html/js/Controls/AutoCompleteInput.js @@ -2,273 +2,273 @@ var App = App || {}; App.Controls = App.Controls || {}; App.Controls.AutoCompleteInput = function($input) { - var _ = App.DI.get('_'); - var jQuery = App.DI.get('jQuery'); - var tagList = App.DI.get('tagList'); + var _ = App.DI.get('_'); + var jQuery = App.DI.get('jQuery'); + var tagList = App.DI.get('tagList'); - var KEY_TAB = 9; - var KEY_RETURN = 13; - var KEY_DELETE = 46; - var KEY_ESCAPE = 27; - var KEY_UP = 38; - var KEY_DOWN = 40; + var KEY_TAB = 9; + var KEY_RETURN = 13; + var KEY_DELETE = 46; + var KEY_ESCAPE = 27; + var KEY_UP = 38; + var KEY_DOWN = 40; - var options = { - caseSensitive: false, - source: null, - maxResults: 15, - minLengthToArbitrarySearch: 3, - onApply: null, - onDelete: null, - onRender: null, - additionalFilter: null, - }; - var showTimeout = null; - var cachedSource = null; - var results = []; - var activeResult = -1; - var monitorInputHidingInterval = null; + var options = { + caseSensitive: false, + source: null, + maxResults: 15, + minLengthToArbitrarySearch: 3, + onApply: null, + onDelete: null, + onRender: null, + additionalFilter: null, + }; + var showTimeout = null; + var cachedSource = null; + var results = []; + var activeResult = -1; + var monitorInputHidingInterval = null; - if ($input.length === 0) { - throw new Error('Input element was not found'); - } - if ($input.length > 1) { - throw new Error('Cannot add autocompletion to more than one element at once'); - } - if ($input.attr('data-autocomplete')) { - throw new Error('Autocompletion was already added for this element'); - } - $input.attr('data-autocomplete', true); - $input.attr('autocomplete', 'off'); + if ($input.length === 0) { + throw new Error('Input element was not found'); + } + if ($input.length > 1) { + throw new Error('Cannot add autocompletion to more than one element at once'); + } + if ($input.attr('data-autocomplete')) { + throw new Error('Autocompletion was already added for this element'); + } + $input.attr('data-autocomplete', true); + $input.attr('autocomplete', 'off'); - var $div = jQuery('
Page ' + pager.getPage() + ' of ' + pager.getTotalPages() + '
'); - } - $page.append(targetContent); - $target.find('.pagination-content').append($page); - updateCallback($page, response); + if (forceClear) { + clearContent(); + window.scrollTo(0, 0); + } + var $page = jQuery('Page ' + pager.getPage() + ' of ' + pager.getTotalPages() + '
'); + } + $page.append(targetContent); + $target.find('.pagination-content').append($page); + updateCallback($page, response); - refreshPageList(); - if (!response.entities.length) { - messagePresenter.showInfo($messages, 'No data to show'); - if (pager.getVisiblePages().length === 1) { - hidePageList(); - } else { - showPageList(); - } - } else { - showPageList(); - } + refreshPageList(); + if (!response.entities.length) { + messagePresenter.showInfo($messages, 'No data to show'); + if (pager.getVisiblePages().length === 1) { + hidePageList(); + } else { + showPageList(); + } + } else { + showPageList(); + } - if (pager.getPage() < response.totalPages) { - attachNextPageLoader(); - } + if (pager.getPage() < response.totalPages) { + attachNextPageLoader(); + } - resolve(); - }).fail(function(response) { - progress.done(); - clearContent(); - hidePageList(); - messagePresenter.showError($messages, response.json && response.json.error || response); + resolve(); + }).fail(function(response) { + progress.done(); + clearContent(); + hidePageList(); + messagePresenter.showError($messages, response.json && response.json.error || response); - reject(); - }); - }); - } + reject(); + }); + }); + } - function clearContent() { - detachNextPageLoader(); - $target.find('.pagination-content').empty(); - } + function clearContent() { + detachNextPageLoader(); + $target.find('.pagination-content').empty(); + } - function attachNextPageLoader() { - if (!endlessScroll) { - return; - } + function attachNextPageLoader() { + if (!endlessScroll) { + return; + } - detachNextPageLoader(); - scrollInterval = window.setInterval(function() { - var myScrollInterval = scrollInterval; - var baseLine = $target.offset().top + $target.innerHeight(); - var scrollY = jQuery(window).scrollTop() + jQuery(window).height(); - if (scrollY > baseLine) { - syncUrlInplace({page: pager.getPage() + 1}); - window.clearInterval(myScrollInterval); - } - }, 100); - } + detachNextPageLoader(); + scrollInterval = window.setInterval(function() { + var myScrollInterval = scrollInterval; + var baseLine = $target.offset().top + $target.innerHeight(); + var scrollY = jQuery(window).scrollTop() + jQuery(window).height(); + if (scrollY > baseLine) { + syncUrlInplace({page: pager.getPage() + 1}); + window.clearInterval(myScrollInterval); + } + }, 100); + } - function detachNextPageLoader() { - window.clearInterval(scrollInterval); - } + function detachNextPageLoader() { + window.clearInterval(scrollInterval); + } - function showPageList() { - $pageList.show(); - } + function showPageList() { + $pageList.show(); + } - function hidePageList() { - $pageList.hide(); - } + function hidePageList() { + $pageList.hide(); + } - function navigateToPrevPage() { - console.log('!'); - if (pager.prevPage()) { - syncUrl({page: pager.getPage()}); - } - } + function navigateToPrevPage() { + console.log('!'); + if (pager.prevPage()) { + syncUrl({page: pager.getPage()}); + } + } - function navigateToNextPage() { - if (pager.nextPage()) { - syncUrl({page: pager.getPage()}); - } - } + function navigateToNextPage() { + if (pager.nextPage()) { + syncUrl({page: pager.getPage()}); + } + } - function refreshPageList() { - var $lastItem = $pageList.find('li:last-child'); - var currentPage = pager.getPage(); - var pages = pager.getVisiblePages(); - $pageList.find('li.page').remove(); - var lastPage = 0; - _.each(pages, function(page) { - if (page - lastPage > 1) { - jQuery('$1
');
- //spoilers
- text = text.replace(/\[spoiler\]((?:[^\[]|\[(?!\/?spoiler\]))+)\[\/spoiler\]/ig, '$1');
- //[small]
- text = text.replace(/\[small\]((?:[^\[]|\[(?!\/?small\]))+)\[\/small\]/ig, '$1');
- //strike-through
- text = text.replace(/(^|[^\\])(~~|~)([^~]+)\2/g, '$1@$2
');
- //user permalinks
- text = text.replace(/(^|[\s<>\(\)\[\]])\+([a-zA-Z0-9_-]+)/g, '$1+$2
');
- //tag permalinks
- text = text.replace(/(^|[\s<>\(\)\[\]])\#([^\s<>/\\]+)/g, '$1#$2
');
- return text;
- };
+ //search permalinks
+ text = text.replace(/\[search\]((?:[^\[]|\[(?!\/?search\]))+)\[\/search\]/ig, '$1
');
+ //spoilers
+ text = text.replace(/\[spoiler\]((?:[^\[]|\[(?!\/?spoiler\]))+)\[\/spoiler\]/ig, '$1');
+ //[small]
+ text = text.replace(/\[small\]((?:[^\[]|\[(?!\/?small\]))+)\[\/small\]/ig, '$1');
+ //strike-through
+ text = text.replace(/(^|[^\\])(~~|~)([^~]+)\2/g, '$1@$2
');
+ //user permalinks
+ text = text.replace(/(^|[\s<>\(\)\[\]])\+([a-zA-Z0-9_-]+)/g, '$1+$2
');
+ //tag permalinks
+ text = text.replace(/(^|[\s<>\(\)\[\]])\#([^\s<>/\\]+)/g, '$1#$2
');
+ return text;
+ };
- return postDecorator(marked(preDecorator(text), options));
- }
+ return postDecorator(marked(preDecorator(text), options));
+ }
- function appendComplexRouteParam(baseUri, params) {
- var result = baseUri + '/';
- _.each(params, function(v, k) {
- if (typeof(v) !== 'undefined') {
- result += k + '=' + v + ';';
- }
- });
- return result.slice(0, -1);
- }
+ function appendComplexRouteParam(baseUri, params) {
+ var result = baseUri + '/';
+ _.each(params, function(v, k) {
+ if (typeof(v) !== 'undefined') {
+ result += k + '=' + v + ';';
+ }
+ });
+ return result.slice(0, -1);
+ }
- function simplifySearchQuery(query) {
- if (typeof(query) === 'undefined') {
- return {};
- }
- if (query.page === 1) {
- delete query.page;
- }
- query = _.pick(query, _.identity); //remove falsy values
- return query;
- }
+ function simplifySearchQuery(query) {
+ if (typeof(query) === 'undefined') {
+ return {};
+ }
+ if (query.page === 1) {
+ delete query.page;
+ }
+ query = _.pick(query, _.identity); //remove falsy values
+ return query;
+ }
- return {
- promiseTemplate: promiseTemplate,
- formatRelativeTime: formatRelativeTime,
- formatAbsoluteTime: formatAbsoluteTime,
- formatFileSize: formatFileSize,
- formatMarkdown: formatMarkdown,
- enableExitConfirmation: enableExitConfirmation,
- disableExitConfirmation: disableExitConfirmation,
- isExitConfirmationEnabled: isExitConfirmationEnabled,
- transparentPixel: transparentPixel,
- loadImagesNicely: loadImagesNicely,
- appendComplexRouteParam: appendComplexRouteParam,
- simplifySearchQuery: simplifySearchQuery,
- };
+ return {
+ promiseTemplate: promiseTemplate,
+ formatRelativeTime: formatRelativeTime,
+ formatAbsoluteTime: formatAbsoluteTime,
+ formatFileSize: formatFileSize,
+ formatMarkdown: formatMarkdown,
+ enableExitConfirmation: enableExitConfirmation,
+ disableExitConfirmation: disableExitConfirmation,
+ isExitConfirmationEnabled: isExitConfirmationEnabled,
+ transparentPixel: transparentPixel,
+ loadImagesNicely: loadImagesNicely,
+ appendComplexRouteParam: appendComplexRouteParam,
+ simplifySearchQuery: simplifySearchQuery,
+ };
};
diff --git a/public_html/js/Util/Resizable.js b/public_html/js/Util/Resizable.js
index 58c41c17..ca62ed31 100644
--- a/public_html/js/Util/Resizable.js
+++ b/public_html/js/Util/Resizable.js
@@ -2,108 +2,108 @@ var App = App || {};
App.Util = App.Util || {};
App.Util.Resizable = function(jQuery) {
- var KEY_LEFT = 37;
- var KEY_UP = 38;
- var KEY_RIGHT = 39;
- var KEY_DOWN = 40;
+ var KEY_LEFT = 37;
+ var KEY_UP = 38;
+ var KEY_RIGHT = 39;
+ var KEY_DOWN = 40;
- function relativeResizeStrategy($element) {
- var $parent = $element.parent();
- var delta;
- var width = $element.width();
- var height = $element.height();
+ function relativeResizeStrategy($element) {
+ var $parent = $element.parent();
+ var delta;
+ var width = $element.width();
+ var height = $element.height();
- var getSize = function() {
- return {width: width, height: height};
- };
+ var getSize = function() {
+ return {width: width, height: height};
+ };
- var setSize = function(newWidth, newHeight) {
- width = newWidth;
- height = newHeight;
- var screenWidth = Math.min(Math.max(width, 20), $parent.outerWidth() + $parent.offset().left - $element.offset().left);
- var screenHeight = Math.min(Math.max(height, 20), $parent.outerHeight() + $parent.offset().top - $element.offset().top);
- screenWidth *= 100.0 / $parent.outerWidth();
- screenHeight *= 100.0 / $parent.outerHeight();
- $element.css({
- width: screenWidth + '%',
- height: screenHeight + '%'});
- };
+ var setSize = function(newWidth, newHeight) {
+ width = newWidth;
+ height = newHeight;
+ var screenWidth = Math.min(Math.max(width, 20), $parent.outerWidth() + $parent.offset().left - $element.offset().left);
+ var screenHeight = Math.min(Math.max(height, 20), $parent.outerHeight() + $parent.offset().top - $element.offset().top);
+ screenWidth *= 100.0 / $parent.outerWidth();
+ screenHeight *= 100.0 / $parent.outerHeight();
+ $element.css({
+ width: screenWidth + '%',
+ height: screenHeight + '%'});
+ };
- return {
- mouseClicked: function(e) {
- delta = {
- x: $element.width() - e.clientX,
- y: $element.height() - e.clientY,
- };
- },
+ return {
+ mouseClicked: function(e) {
+ delta = {
+ x: $element.width() - e.clientX,
+ y: $element.height() - e.clientY,
+ };
+ },
- mouseMoved: function(e) {
- setSize(
- e.clientX + delta.x,
- e.clientY + delta.y);
- },
+ mouseMoved: function(e) {
+ setSize(
+ e.clientX + delta.x,
+ e.clientY + delta.y);
+ },
- getSize: getSize,
- setSize: setSize,
- };
- }
+ getSize: getSize,
+ setSize: setSize,
+ };
+ }
- function makeResizable($element, enableHotkeys) {
- var $resizer = jQuery('');
- var strategy = relativeResizeStrategy($element);
- $element.append($resizer);
+ function makeResizable($element, enableHotkeys) {
+ var $resizer = jQuery('');
+ var strategy = relativeResizeStrategy($element);
+ $element.append($resizer);
- $resizer.mousedown(function(e) {
- e.preventDefault();
- e.stopPropagation();
- $element.focus();
- $element.addClass('resizing');
+ $resizer.mousedown(function(e) {
+ e.preventDefault();
+ e.stopPropagation();
+ $element.focus();
+ $element.addClass('resizing');
- strategy.mouseClicked(e);
+ strategy.mouseClicked(e);
- jQuery(window).bind('mousemove.elemsize', function(e) {
- strategy.mouseMoved(e);
- }).bind('mouseup.elemsize', function(e) {
- e.preventDefault();
- strategy.mouseMoved(e);
- $element.removeClass('resizing');
- jQuery(window).unbind('mousemove.elemsize');
- jQuery(window).unbind('mouseup.elemsize');
- });
- });
+ jQuery(window).bind('mousemove.elemsize', function(e) {
+ strategy.mouseMoved(e);
+ }).bind('mouseup.elemsize', function(e) {
+ e.preventDefault();
+ strategy.mouseMoved(e);
+ $element.removeClass('resizing');
+ jQuery(window).unbind('mousemove.elemsize');
+ jQuery(window).unbind('mouseup.elemsize');
+ });
+ });
- if (enableHotkeys) {
- $element.keydown(function(e) {
- var size = strategy.getSize();
- var oldSize = {width: size.width, height: size.height};
- if (!e.shiftKey) {
- return;
- }
+ if (enableHotkeys) {
+ $element.keydown(function(e) {
+ var size = strategy.getSize();
+ var oldSize = {width: size.width, height: size.height};
+ if (!e.shiftKey) {
+ return;
+ }
- var delta = e.ctrlKey ? 10 : 1;
- if (e.which === KEY_LEFT) {
- size.width -= delta;
- } else if (e.which === KEY_RIGHT) {
- size.width += delta;
- } else if (e.which === KEY_UP) {
- size.height -= delta;
- } else if (e.which === KEY_DOWN) {
- size.height += delta;
- }
+ var delta = e.ctrlKey ? 10 : 1;
+ if (e.which === KEY_LEFT) {
+ size.width -= delta;
+ } else if (e.which === KEY_RIGHT) {
+ size.width += delta;
+ } else if (e.which === KEY_UP) {
+ size.height -= delta;
+ } else if (e.which === KEY_DOWN) {
+ size.height += delta;
+ }
- if (size.width !== oldSize.width || size.height !== oldSize.height) {
- e.stopPropagation();
- e.stopImmediatePropagation();
- e.preventDefault();
- strategy.setSize(size.width, size.height);
- }
- });
- }
- }
+ if (size.width !== oldSize.width || size.height !== oldSize.height) {
+ e.stopPropagation();
+ e.stopImmediatePropagation();
+ e.preventDefault();
+ strategy.setSize(size.width, size.height);
+ }
+ });
+ }
+ }
- return {
- makeResizable: makeResizable,
- };
+ return {
+ makeResizable: makeResizable,
+ };
};
diff --git a/src/Bootstrap.php b/src/Bootstrap.php
index 14e9360c..c83394e8 100644
--- a/src/Bootstrap.php
+++ b/src/Bootstrap.php
@@ -5,42 +5,42 @@ $startTime = microtime(true);
final class Bootstrap
{
- private static $startTime;
+ private static $startTime;
- public static function init($startTime)
- {
- self::$startTime = $startTime;
- self::setTimezone();
- self::turnErrorsIntoExceptions();
- self::initAutoloader();
- }
+ public static function init($startTime)
+ {
+ self::$startTime = $startTime;
+ self::setTimezone();
+ self::turnErrorsIntoExceptions();
+ self::initAutoloader();
+ }
- public static function getStartTime()
- {
- return self::$startTime;
- }
+ public static function getStartTime()
+ {
+ return self::$startTime;
+ }
- private static function setTimezone()
- {
- date_default_timezone_set('UTC');
- }
+ private static function setTimezone()
+ {
+ date_default_timezone_set('UTC');
+ }
- private static function initAutoloader()
- {
- require(__DIR__
- . DIRECTORY_SEPARATOR . '..'
- . DIRECTORY_SEPARATOR . 'vendor'
- . DIRECTORY_SEPARATOR . 'autoload.php');
- }
+ private static function initAutoloader()
+ {
+ require(__DIR__
+ . DIRECTORY_SEPARATOR . '..'
+ . DIRECTORY_SEPARATOR . 'vendor'
+ . DIRECTORY_SEPARATOR . 'autoload.php');
+ }
- private static function turnErrorsIntoExceptions()
- {
- set_error_handler(
- function($errno, $errstr, $errfile, $errline, array $errcontext)
- {
- throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
- });
- }
+ private static function turnErrorsIntoExceptions()
+ {
+ set_error_handler(
+ function($errno, $errstr, $errfile, $errline, array $errcontext)
+ {
+ throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
+ });
+ }
}
Bootstrap::init($startTime);
diff --git a/src/Config.php b/src/Config.php
index e2cef918..9c47b7f3 100644
--- a/src/Config.php
+++ b/src/Config.php
@@ -3,79 +3,79 @@ namespace Szurubooru;
class Config extends \ArrayObject
{
- private $dataDirectory;
- private $publicDataDirectory;
+ private $dataDirectory;
+ private $publicDataDirectory;
- public function __construct($dataDirectory, $publicDataDirectory)
- {
- $this->setFlags($this->getArrayObjectFlags());
- $this->dataDirectory = $dataDirectory;
- $this->publicDataDirectory = $publicDataDirectory;
- $this->tryLoadFromIni([
- $dataDirectory . DIRECTORY_SEPARATOR . 'config.ini',
- $dataDirectory . DIRECTORY_SEPARATOR . 'local.ini']);
- }
+ public function __construct($dataDirectory, $publicDataDirectory)
+ {
+ $this->setFlags($this->getArrayObjectFlags());
+ $this->dataDirectory = $dataDirectory;
+ $this->publicDataDirectory = $publicDataDirectory;
+ $this->tryLoadFromIni([
+ $dataDirectory . DIRECTORY_SEPARATOR . 'config.ini',
+ $dataDirectory . DIRECTORY_SEPARATOR . 'local.ini']);
+ }
- public function tryLoadFromIni($configPaths)
- {
- if (!is_array($configPaths))
- $configPaths = [$configPaths];
+ public function tryLoadFromIni($configPaths)
+ {
+ if (!is_array($configPaths))
+ $configPaths = [$configPaths];
- foreach ($configPaths as $configPath)
- {
- if (file_exists($configPath))
- $this->loadFromIni($configPath);
- }
- }
+ foreach ($configPaths as $configPath)
+ {
+ if (file_exists($configPath))
+ $this->loadFromIni($configPath);
+ }
+ }
- public function getDataDirectory()
- {
- return $this->dataDirectory;
- }
+ public function getDataDirectory()
+ {
+ return $this->dataDirectory;
+ }
- public function getPublicDataDirectory()
- {
- return $this->publicDataDirectory;
- }
+ public function getPublicDataDirectory()
+ {
+ return $this->publicDataDirectory;
+ }
- public function offsetGet($index)
- {
- if (!parent::offsetExists($index))
- return null;
- return parent::offsetGet($index);
- }
+ public function offsetGet($index)
+ {
+ if (!parent::offsetExists($index))
+ return null;
+ return parent::offsetGet($index);
+ }
- public function loadFromIni($configPath)
- {
- $array = parse_ini_file($configPath, true, INI_SCANNER_RAW);
+ public function loadFromIni($configPath)
+ {
+ $array = parse_ini_file($configPath, true, INI_SCANNER_RAW);
- foreach ($array as $key => $value)
- {
- if (!is_array($value))
- {
- $this->offsetSet($key, $value);
- }
- else
- {
- $section = $key;
- $ptr = $this;
+ foreach ($array as $key => $value)
+ {
+ if (!is_array($value))
+ {
+ $this->offsetSet($key, $value);
+ }
+ else
+ {
+ $section = $key;
+ $ptr = $this;
- foreach (explode('.', $section) as $subSection)
- {
- if (!$ptr->offsetExists($subSection))
- $ptr->offsetSet($subSection, new \ArrayObject([], $this->getArrayObjectFlags()));
+ foreach (explode('.', $section) as $subSection)
+ {
+ if (!$ptr->offsetExists($subSection))
+ $ptr->offsetSet($subSection, new \ArrayObject([], $this->getArrayObjectFlags()));
- $ptr = $ptr->$subSection;
- }
+ $ptr = $ptr->$subSection;
+ }
- foreach ($value as $sectionKey => $sectionValue)
- $ptr->offsetSet($sectionKey, $sectionValue);
- }
- }
- }
+ foreach ($value as $sectionKey => $sectionValue)
+ $ptr->offsetSet($sectionKey, $sectionValue);
+ }
+ }
+ }
- private function getArrayObjectFlags()
- {
- return parent::ARRAY_AS_PROPS | parent::STD_PROP_LIST;
- }
+ private function getArrayObjectFlags()
+ {
+ return parent::ARRAY_AS_PROPS | parent::STD_PROP_LIST;
+ }
}
diff --git a/src/Dao/AbstractDao.php b/src/Dao/AbstractDao.php
index 7b2d9579..e31d60c7 100644
--- a/src/Dao/AbstractDao.php
+++ b/src/Dao/AbstractDao.php
@@ -12,300 +12,300 @@ use Szurubooru\Search\Result;
abstract class AbstractDao implements ICrudDao, IBatchDao
{
- protected $pdo;
- protected $tableName;
- protected $entityConverter;
- protected $driver;
+ protected $pdo;
+ protected $tableName;
+ protected $entityConverter;
+ protected $driver;
- public function __construct(
- DatabaseConnection $databaseConnection,
- $tableName,
- IEntityConverter $entityConverter)
- {
- $this->setDatabaseConnection($databaseConnection);
- $this->tableName = $tableName;
- $this->entityConverter = $entityConverter;
- $this->entityConverter->setEntityDecorator(function($entity)
- {
- $this->afterLoad($entity);
- });
- }
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ $tableName,
+ IEntityConverter $entityConverter)
+ {
+ $this->setDatabaseConnection($databaseConnection);
+ $this->tableName = $tableName;
+ $this->entityConverter = $entityConverter;
+ $this->entityConverter->setEntityDecorator(function($entity)
+ {
+ $this->afterLoad($entity);
+ });
+ }
- public function getTableName()
- {
- return $this->tableName;
- }
+ public function getTableName()
+ {
+ return $this->tableName;
+ }
- public function getEntityConverter()
- {
- return $this->entityConverter;
- }
+ public function getEntityConverter()
+ {
+ return $this->entityConverter;
+ }
- public function save(&$entity)
- {
- $entity = $this->upsert($entity);
- $this->afterSave($entity);
- $this->afterBatchSave([$entity]);
- return $entity;
- }
+ public function save(&$entity)
+ {
+ $entity = $this->upsert($entity);
+ $this->afterSave($entity);
+ $this->afterBatchSave([$entity]);
+ return $entity;
+ }
- public function batchSave(array $entities)
- {
- foreach ($entities as $key => $entity)
- {
- $entities[$key] = $this->upsert($entity);
- $this->afterSave($entity);
- }
- if (count($entities) > 0)
- $this->afterBatchSave([$entity]);
- return $entities;
- }
+ public function batchSave(array $entities)
+ {
+ foreach ($entities as $key => $entity)
+ {
+ $entities[$key] = $this->upsert($entity);
+ $this->afterSave($entity);
+ }
+ if (count($entities) > 0)
+ $this->afterBatchSave([$entity]);
+ return $entities;
+ }
- public function findAll()
- {
- $query = $this->pdo->from($this->tableName);
- return $this->arrayToEntities($query);
- }
+ public function findAll()
+ {
+ $query = $this->pdo->from($this->tableName);
+ return $this->arrayToEntities($query);
+ }
- public function findById($entityId)
- {
- return $this->findOneBy($this->getIdColumn(), $entityId);
- }
+ public function findById($entityId)
+ {
+ return $this->findOneBy($this->getIdColumn(), $entityId);
+ }
- public function findByIds($entityIds)
- {
- return $this->findBy($this->getIdColumn(), $entityIds);
- }
+ public function findByIds($entityIds)
+ {
+ return $this->findBy($this->getIdColumn(), $entityIds);
+ }
- public function findFiltered(IFilter $searchFilter)
- {
- $query = $this->pdo->from($this->tableName);
+ public function findFiltered(IFilter $searchFilter)
+ {
+ $query = $this->pdo->from($this->tableName);
- $orderByString = self::compileOrderBy($searchFilter->getOrder());
- if ($orderByString)
- $query->orderBy($orderByString);
+ $orderByString = self::compileOrderBy($searchFilter->getOrder());
+ if ($orderByString)
+ $query->orderBy($orderByString);
- $this->decorateQueryFromFilter($query, $searchFilter);
- if ($searchFilter->getPageSize() > 0)
- {
- $query->limit($searchFilter->getPageSize());
- $query->offset($searchFilter->getPageSize() * max(0, $searchFilter->getPageNumber() - 1));
- }
- $entities = $this->arrayToEntities(iterator_to_array($query));
+ $this->decorateQueryFromFilter($query, $searchFilter);
+ if ($searchFilter->getPageSize() > 0)
+ {
+ $query->limit($searchFilter->getPageSize());
+ $query->offset($searchFilter->getPageSize() * max(0, $searchFilter->getPageNumber() - 1));
+ }
+ $entities = $this->arrayToEntities(iterator_to_array($query));
- $query = $this->pdo->from($this->tableName);
- $this->decorateQueryFromFilter($query, $searchFilter);
- $totalRecords = count($query);
+ $query = $this->pdo->from($this->tableName);
+ $this->decorateQueryFromFilter($query, $searchFilter);
+ $totalRecords = count($query);
- $searchResult = new Result();
- $searchResult->setSearchFilter($searchFilter);
- $searchResult->setEntities($entities);
- $searchResult->setTotalRecords($totalRecords);
- $searchResult->setPageNumber($searchFilter->getPageNumber());
- $searchResult->setPageSize($searchFilter->getPageSize());
- return $searchResult;
- }
+ $searchResult = new Result();
+ $searchResult->setSearchFilter($searchFilter);
+ $searchResult->setEntities($entities);
+ $searchResult->setTotalRecords($totalRecords);
+ $searchResult->setPageNumber($searchFilter->getPageNumber());
+ $searchResult->setPageSize($searchFilter->getPageSize());
+ return $searchResult;
+ }
- public function deleteAll()
- {
- foreach ($this->findAll() as $entity)
- {
- $this->beforeDelete($entity);
- }
- $this->pdo->deleteFrom($this->tableName)->execute();
- }
+ public function deleteAll()
+ {
+ foreach ($this->findAll() as $entity)
+ {
+ $this->beforeDelete($entity);
+ }
+ $this->pdo->deleteFrom($this->tableName)->execute();
+ }
- public function deleteById($entityId)
- {
- return $this->deleteBy($this->getIdColumn(), $entityId);
- }
+ public function deleteById($entityId)
+ {
+ return $this->deleteBy($this->getIdColumn(), $entityId);
+ }
- public function update(Entity $entity)
- {
- $arrayEntity = $this->entityConverter->toArray($entity);
- unset($arrayEntity['id']);
- $this->pdo->update($this->tableName)->set($arrayEntity)->where($this->getIdColumn(), $entity->getId())->execute();
- return $entity;
- }
+ public function update(Entity $entity)
+ {
+ $arrayEntity = $this->entityConverter->toArray($entity);
+ unset($arrayEntity['id']);
+ $this->pdo->update($this->tableName)->set($arrayEntity)->where($this->getIdColumn(), $entity->getId())->execute();
+ return $entity;
+ }
- public function create(Entity $entity)
- {
- $sql = 'UPDATE sequencer SET lastUsedId = (@lastUsedId := (lastUsedId + 1)) WHERE tableName = :tableName';
- $query = $this->pdo->prepare($sql);
- $query->bindValue(':tableName', $this->tableName);
- $query->execute();
- $lastUsedId = $this->pdo->query('SELECT @lastUsedId')->fetchColumn();
+ public function create(Entity $entity)
+ {
+ $sql = 'UPDATE sequencer SET lastUsedId = (@lastUsedId := (lastUsedId + 1)) WHERE tableName = :tableName';
+ $query = $this->pdo->prepare($sql);
+ $query->bindValue(':tableName', $this->tableName);
+ $query->execute();
+ $lastUsedId = $this->pdo->query('SELECT @lastUsedId')->fetchColumn();
- $entity->setId(intval($lastUsedId));
- $arrayEntity = $this->entityConverter->toArray($entity);
- $this->pdo->insertInto($this->tableName)->values($arrayEntity)->execute();
- return $entity;
- }
+ $entity->setId(intval($lastUsedId));
+ $arrayEntity = $this->entityConverter->toArray($entity);
+ $this->pdo->insertInto($this->tableName)->values($arrayEntity)->execute();
+ return $entity;
+ }
- protected function getIdColumn()
- {
- return 'id';
- }
+ protected function getIdColumn()
+ {
+ return 'id';
+ }
- protected function hasAnyRecords()
- {
- return count(iterator_to_array($this->pdo->from($this->tableName)->limit(1))) > 0;
- }
+ protected function hasAnyRecords()
+ {
+ return count(iterator_to_array($this->pdo->from($this->tableName)->limit(1))) > 0;
+ }
- protected function findBy($columnName, $value)
- {
- if (is_array($value) && empty($value))
- return [];
- $query = $this->pdo->from($this->tableName)->where($columnName, $value);
- $arrayEntities = iterator_to_array($query);
- return $this->arrayToEntities($arrayEntities);
- }
+ protected function findBy($columnName, $value)
+ {
+ if (is_array($value) && empty($value))
+ return [];
+ $query = $this->pdo->from($this->tableName)->where($columnName, $value);
+ $arrayEntities = iterator_to_array($query);
+ return $this->arrayToEntities($arrayEntities);
+ }
- protected function findOneBy($columnName, $value)
- {
- $entities = $this->findBy($columnName, $value);
- if (!$entities)
- return null;
- return array_shift($entities);
- }
+ protected function findOneBy($columnName, $value)
+ {
+ $entities = $this->findBy($columnName, $value);
+ if (!$entities)
+ return null;
+ return array_shift($entities);
+ }
- protected function deleteBy($columnName, $value)
- {
- foreach ($this->findBy($columnName, $value) as $entity)
- {
- $this->beforeDelete($entity);
- }
- $this->pdo->deleteFrom($this->tableName)->where($columnName, $value)->execute();
- }
+ protected function deleteBy($columnName, $value)
+ {
+ foreach ($this->findBy($columnName, $value) as $entity)
+ {
+ $this->beforeDelete($entity);
+ }
+ $this->pdo->deleteFrom($this->tableName)->where($columnName, $value)->execute();
+ }
- protected function afterLoad(Entity $entity)
- {
- }
+ protected function afterLoad(Entity $entity)
+ {
+ }
- protected function afterSave(Entity $entity)
- {
- }
+ protected function afterSave(Entity $entity)
+ {
+ }
- protected function afterBatchSave(array $entities)
- {
- }
+ protected function afterBatchSave(array $entities)
+ {
+ }
- protected function beforeDelete(Entity $entity)
- {
- }
+ protected function beforeDelete(Entity $entity)
+ {
+ }
- protected function decorateQueryFromRequirement($query, Requirement $requirement)
- {
- $value = $requirement->getValue();
- $sqlColumn = $requirement->getType();
+ protected function decorateQueryFromRequirement($query, Requirement $requirement)
+ {
+ $value = $requirement->getValue();
+ $sqlColumn = $requirement->getType();
- if ($value instanceof RequirementCompositeValue)
- {
- $sql = $sqlColumn;
- $bindings = $value->getValues();
+ if ($value instanceof RequirementCompositeValue)
+ {
+ $sql = $sqlColumn;
+ $bindings = $value->getValues();
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
- }
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
+ }
- else if ($value instanceof RequirementRangedValue)
- {
- if ($value->getMinValue() && $value->getMaxValue())
- {
- $sql = $sqlColumn . ' >= ? AND ' . $sqlColumn . ' <= ?';
- $bindings = [$value->getMinValue(), $value->getMaxValue()];
- }
- elseif ($value->getMinValue())
- {
- $sql = $sqlColumn . ' >= ?';
- $bindings = [$value->getMinValue()];
- }
- elseif ($value->getMaxValue())
- {
- $sql = $sqlColumn . ' <= ?';
- $bindings = [$value->getMaxValue()];
- }
- else
- throw new \RuntimeException('Neither min or max value was supplied');
+ else if ($value instanceof RequirementRangedValue)
+ {
+ if ($value->getMinValue() && $value->getMaxValue())
+ {
+ $sql = $sqlColumn . ' >= ? AND ' . $sqlColumn . ' <= ?';
+ $bindings = [$value->getMinValue(), $value->getMaxValue()];
+ }
+ elseif ($value->getMinValue())
+ {
+ $sql = $sqlColumn . ' >= ?';
+ $bindings = [$value->getMinValue()];
+ }
+ elseif ($value->getMaxValue())
+ {
+ $sql = $sqlColumn . ' <= ?';
+ $bindings = [$value->getMaxValue()];
+ }
+ else
+ throw new \RuntimeException('Neither min or max value was supplied');
- if ($requirement->isNegated())
- $sql = 'NOT (' . $sql . ')';
- }
+ if ($requirement->isNegated())
+ $sql = 'NOT (' . $sql . ')';
+ }
- else if ($value instanceof RequirementSingleValue)
- {
- $sql = $sqlColumn;
- $bindings = [$value->getValue()];
+ else if ($value instanceof RequirementSingleValue)
+ {
+ $sql = $sqlColumn;
+ $bindings = [$value->getValue()];
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
- }
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
+ }
- else
- throw new \Exception('Bad value: ' . get_class($value));
+ else
+ throw new \Exception('Bad value: ' . get_class($value));
- $query->where($sql, $bindings);
- }
+ $query->where($sql, $bindings);
+ }
- protected function arrayToEntities($arrayEntities, $entityConverter = null)
- {
- if ($entityConverter === null)
- $entityConverter = $this->entityConverter;
+ protected function arrayToEntities($arrayEntities, $entityConverter = null)
+ {
+ if ($entityConverter === null)
+ $entityConverter = $this->entityConverter;
- $entities = [];
- foreach ($arrayEntities as $arrayEntity)
- {
- $entity = $entityConverter->toEntity($arrayEntity);
- $entities[$entity->getId()] = $entity;
- }
- return $entities;
- }
+ $entities = [];
+ foreach ($arrayEntities as $arrayEntity)
+ {
+ $entity = $entityConverter->toEntity($arrayEntity);
+ $entities[$entity->getId()] = $entity;
+ }
+ return $entities;
+ }
- private function setDatabaseConnection(DatabaseConnection $databaseConnection)
- {
- $this->pdo = $databaseConnection->getPDO();
- $this->driver = $databaseConnection->getDriver();
- }
+ private function setDatabaseConnection(DatabaseConnection $databaseConnection)
+ {
+ $this->pdo = $databaseConnection->getPDO();
+ $this->driver = $databaseConnection->getDriver();
+ }
- private function decorateQueryFromFilter($query, IFilter $filter)
- {
- foreach ($filter->getRequirements() as $requirement)
- {
- $this->decorateQueryFromRequirement($query, $requirement);
- }
- }
+ private function decorateQueryFromFilter($query, IFilter $filter)
+ {
+ foreach ($filter->getRequirements() as $requirement)
+ {
+ $this->decorateQueryFromRequirement($query, $requirement);
+ }
+ }
- private function compileOrderBy($order)
- {
- $orderByString = '';
- foreach ($order as $orderColumn => $orderDir)
- {
- if ($orderColumn === IFilter::ORDER_RANDOM)
- {
- $driver = $this->driver;
- if ($driver === 'sqlite')
- {
- $orderColumn = 'RANDOM()';
- }
- else
- {
- $orderColumn = 'RAND()';
- }
- }
- $orderByString .= $orderColumn . ' ' . ($orderDir === IFilter::ORDER_DESC ? 'DESC' : 'ASC') . ', ';
- }
- return substr($orderByString, 0, -2);
- }
+ private function compileOrderBy($order)
+ {
+ $orderByString = '';
+ foreach ($order as $orderColumn => $orderDir)
+ {
+ if ($orderColumn === IFilter::ORDER_RANDOM)
+ {
+ $driver = $this->driver;
+ if ($driver === 'sqlite')
+ {
+ $orderColumn = 'RANDOM()';
+ }
+ else
+ {
+ $orderColumn = 'RAND()';
+ }
+ }
+ $orderByString .= $orderColumn . ' ' . ($orderDir === IFilter::ORDER_DESC ? 'DESC' : 'ASC') . ', ';
+ }
+ return substr($orderByString, 0, -2);
+ }
- private function upsert(Entity $entity)
- {
- if ($entity->getId())
- {
- return $this->update($entity);
- }
- else
- {
- return $this->create($entity);
- }
- }
+ private function upsert(Entity $entity)
+ {
+ if ($entity->getId())
+ {
+ return $this->update($entity);
+ }
+ else
+ {
+ return $this->create($entity);
+ }
+ }
}
diff --git a/src/Dao/CommentDao.php b/src/Dao/CommentDao.php
index cfa84f0b..1f806af2 100644
--- a/src/Dao/CommentDao.php
+++ b/src/Dao/CommentDao.php
@@ -10,42 +10,42 @@ use Szurubooru\Entities\Post;
class CommentDao extends AbstractDao implements ICrudDao
{
- private $userDao;
- private $postDao;
+ private $userDao;
+ private $postDao;
- public function __construct(
- DatabaseConnection $databaseConnection,
- UserDao $userDao,
- PostDao $postDao)
- {
- parent::__construct(
- $databaseConnection,
- 'comments',
- new CommentEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ UserDao $userDao,
+ PostDao $postDao)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'comments',
+ new CommentEntityConverter());
- $this->userDao = $userDao;
- $this->postDao = $postDao;
- }
+ $this->userDao = $userDao;
+ $this->postDao = $postDao;
+ }
- public function findByPost(Post $post)
- {
- return $this->findBy('postId', $post->getId());
- }
+ public function findByPost(Post $post)
+ {
+ return $this->findBy('postId', $post->getId());
+ }
- protected function afterLoad(Entity $comment)
- {
- $comment->setLazyLoader(
- Comment::LAZY_LOADER_USER,
- function (Comment $comment)
- {
- return $this->userDao->findById($comment->getUserId());
- });
+ protected function afterLoad(Entity $comment)
+ {
+ $comment->setLazyLoader(
+ Comment::LAZY_LOADER_USER,
+ function (Comment $comment)
+ {
+ return $this->userDao->findById($comment->getUserId());
+ });
- $comment->setLazyLoader(
- Comment::LAZY_LOADER_POST,
- function (Comment $comment)
- {
- return $this->postDao->findById($comment->getPostId());
- });
- }
+ $comment->setLazyLoader(
+ Comment::LAZY_LOADER_POST,
+ function (Comment $comment)
+ {
+ return $this->postDao->findById($comment->getPostId());
+ });
+ }
}
diff --git a/src/Dao/EntityConverters/AbstractEntityConverter.php b/src/Dao/EntityConverters/AbstractEntityConverter.php
index 7e92465e..3045a38e 100644
--- a/src/Dao/EntityConverters/AbstractEntityConverter.php
+++ b/src/Dao/EntityConverters/AbstractEntityConverter.php
@@ -5,43 +5,43 @@ use Szurubooru\Entities\Entity;
abstract class AbstractEntityConverter implements IEntityConverter
{
- private $entityDecorator = null;
+ private $entityDecorator = null;
- public function setEntityDecorator(callable $entityDecorator)
- {
- $this->entityDecorator = $entityDecorator;
- }
+ public function setEntityDecorator(callable $entityDecorator)
+ {
+ $this->entityDecorator = $entityDecorator;
+ }
- public function toEntity(array $array)
- {
- $entity = $this->toBasicEntity($array);
- $func = $this->entityDecorator;
- if ($func !== null)
- $func($entity);
- return $entity;
- }
+ public function toEntity(array $array)
+ {
+ $entity = $this->toBasicEntity($array);
+ $func = $this->entityDecorator;
+ if ($func !== null)
+ $func($entity);
+ return $entity;
+ }
- public function toArray(Entity $entity)
- {
- $array = $this->toBasicArray($entity);
- if ($entity->getId() !== null)
- $array['id'] = $entity->getId();
- return $array;
- }
+ public function toArray(Entity $entity)
+ {
+ $array = $this->toBasicArray($entity);
+ if ($entity->getId() !== null)
+ $array['id'] = $entity->getId();
+ return $array;
+ }
- protected abstract function toBasicEntity(array $array);
+ protected abstract function toBasicEntity(array $array);
- protected abstract function toBasicArray(Entity $entity);
+ protected abstract function toBasicArray(Entity $entity);
- protected function dbTimeToEntityTime($time)
- {
- if ($time === null)
- return null;
- return date('c', strtotime($time));
- }
+ protected function dbTimeToEntityTime($time)
+ {
+ if ($time === null)
+ return null;
+ return date('c', strtotime($time));
+ }
- protected function entityTimeToDbTime($time)
- {
- return $time === null ? null : date('Y-m-d H:i:s', strtotime($time));
- }
+ protected function entityTimeToDbTime($time)
+ {
+ return $time === null ? null : date('Y-m-d H:i:s', strtotime($time));
+ }
}
diff --git a/src/Dao/EntityConverters/CommentEntityConverter.php b/src/Dao/EntityConverters/CommentEntityConverter.php
index 9e772ec2..5b30708c 100644
--- a/src/Dao/EntityConverters/CommentEntityConverter.php
+++ b/src/Dao/EntityConverters/CommentEntityConverter.php
@@ -5,27 +5,27 @@ use Szurubooru\Entities\Entity;
class CommentEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'userId' => $entity->getUserId(),
- 'postId' => $entity->getPostId(),
- 'text' => $entity->getText(),
- 'creationTime' => $this->entityTimeToDbTime($entity->getCreationTime()),
- 'lastEditTime' => $this->entityTimeToDbTime($entity->getLastEditTime()),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'userId' => $entity->getUserId(),
+ 'postId' => $entity->getPostId(),
+ 'text' => $entity->getText(),
+ 'creationTime' => $this->entityTimeToDbTime($entity->getCreationTime()),
+ 'lastEditTime' => $this->entityTimeToDbTime($entity->getLastEditTime()),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Comment(intval($array['id']));
- $entity->setUserId($array['userId']);
- $entity->setPostId($array['postId']);
- $entity->setText($array['text']);
- $entity->setCreationTime($this->dbTimeToEntityTime($array['creationTime']));
- $entity->setLastEditTime($this->dbTimeToEntityTime($array['lastEditTime']));
- $entity->setMeta(Comment::META_SCORE, intval($array['score']));
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Comment(intval($array['id']));
+ $entity->setUserId($array['userId']);
+ $entity->setPostId($array['postId']);
+ $entity->setText($array['text']);
+ $entity->setCreationTime($this->dbTimeToEntityTime($array['creationTime']));
+ $entity->setLastEditTime($this->dbTimeToEntityTime($array['lastEditTime']));
+ $entity->setMeta(Comment::META_SCORE, intval($array['score']));
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/FavoriteEntityConverter.php b/src/Dao/EntityConverters/FavoriteEntityConverter.php
index 21bdc985..e04f003e 100644
--- a/src/Dao/EntityConverters/FavoriteEntityConverter.php
+++ b/src/Dao/EntityConverters/FavoriteEntityConverter.php
@@ -5,22 +5,22 @@ use Szurubooru\Entities\Favorite;
class FavoriteEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'userId' => $entity->getUserId(),
- 'postId' => $entity->getPostId(),
- 'time' => $this->entityTimeToDbTime($entity->getTime()),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'userId' => $entity->getUserId(),
+ 'postId' => $entity->getPostId(),
+ 'time' => $this->entityTimeToDbTime($entity->getTime()),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Favorite(intval($array['id']));
- $entity->setUserId($array['userId']);
- $entity->setPostId($array['postId']);
- $entity->setTime($this->dbTimeToEntityTime($array['time']));
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Favorite(intval($array['id']));
+ $entity->setUserId($array['userId']);
+ $entity->setPostId($array['postId']);
+ $entity->setTime($this->dbTimeToEntityTime($array['time']));
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/GlobalParamEntityConverter.php b/src/Dao/EntityConverters/GlobalParamEntityConverter.php
index 060d60e6..0d37266e 100644
--- a/src/Dao/EntityConverters/GlobalParamEntityConverter.php
+++ b/src/Dao/EntityConverters/GlobalParamEntityConverter.php
@@ -5,20 +5,20 @@ use Szurubooru\Entities\GlobalParam;
class GlobalParamEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'dataKey' => $entity->getKey(),
- 'dataValue' => $entity->getValue(),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'dataKey' => $entity->getKey(),
+ 'dataValue' => $entity->getValue(),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new GlobalParam(intval($array['id']));
- $entity->setKey($array['dataKey']);
- $entity->setValue($array['dataValue']);
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new GlobalParam(intval($array['id']));
+ $entity->setKey($array['dataKey']);
+ $entity->setValue($array['dataValue']);
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/IEntityConverter.php b/src/Dao/EntityConverters/IEntityConverter.php
index f35b50a1..aa7daf6b 100644
--- a/src/Dao/EntityConverters/IEntityConverter.php
+++ b/src/Dao/EntityConverters/IEntityConverter.php
@@ -4,7 +4,7 @@ use Szurubooru\Entities\Entity;
interface IEntityConverter
{
- public function toArray(Entity $entity);
+ public function toArray(Entity $entity);
- public function toEntity(array $array);
+ public function toEntity(array $array);
}
diff --git a/src/Dao/EntityConverters/PostEntityConverter.php b/src/Dao/EntityConverters/PostEntityConverter.php
index df3b1901..532d78e0 100644
--- a/src/Dao/EntityConverters/PostEntityConverter.php
+++ b/src/Dao/EntityConverters/PostEntityConverter.php
@@ -5,52 +5,52 @@ use Szurubooru\Entities\Post;
class PostEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'name' => $entity->getName(),
- 'userId' => $entity->getUserId(),
- 'uploadTime' => $this->entityTimeToDbTime($entity->getUploadTime()),
- 'lastEditTime' => $this->entityTimeToDbTime($entity->getLastEditTime()),
- 'safety' => $entity->getSafety(),
- 'contentType' => $entity->getContentType(),
- 'contentChecksum' => $entity->getContentChecksum(),
- 'contentMimeType' => $entity->getContentMimeType(),
- 'source' => $entity->getSource(),
- 'imageWidth' => $entity->getImageWidth(),
- 'imageHeight' => $entity->getImageHeight(),
- 'originalFileSize' => $entity->getOriginalFileSize(),
- 'originalFileName' => $entity->getOriginalFileName(),
- 'featureCount' => $entity->getFeatureCount(),
- 'lastFeatureTime' => $this->entityTimeToDbTime($entity->getLastFeatureTime()),
- 'flags' => $entity->getFlags(),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'name' => $entity->getName(),
+ 'userId' => $entity->getUserId(),
+ 'uploadTime' => $this->entityTimeToDbTime($entity->getUploadTime()),
+ 'lastEditTime' => $this->entityTimeToDbTime($entity->getLastEditTime()),
+ 'safety' => $entity->getSafety(),
+ 'contentType' => $entity->getContentType(),
+ 'contentChecksum' => $entity->getContentChecksum(),
+ 'contentMimeType' => $entity->getContentMimeType(),
+ 'source' => $entity->getSource(),
+ 'imageWidth' => $entity->getImageWidth(),
+ 'imageHeight' => $entity->getImageHeight(),
+ 'originalFileSize' => $entity->getOriginalFileSize(),
+ 'originalFileName' => $entity->getOriginalFileName(),
+ 'featureCount' => $entity->getFeatureCount(),
+ 'lastFeatureTime' => $this->entityTimeToDbTime($entity->getLastFeatureTime()),
+ 'flags' => $entity->getFlags(),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Post(intval($array['id']));
- $entity->setName($array['name']);
- $entity->setUserId($array['userId']);
- $entity->setUploadTime($this->dbTimeToEntityTime($array['uploadTime']));
- $entity->setLastEditTime($this->dbTimeToEntityTime($array['lastEditTime']));
- $entity->setSafety(intval($array['safety']));
- $entity->setContentType(intval($array['contentType']));
- $entity->setContentChecksum($array['contentChecksum']);
- $entity->setContentMimeType($array['contentMimeType']);
- $entity->setSource($array['source']);
- $entity->setImageWidth($array['imageWidth']);
- $entity->setImageHeight($array['imageHeight']);
- $entity->setOriginalFileSize($array['originalFileSize']);
- $entity->setOriginalFileName($array['originalFileName']);
- $entity->setFeatureCount(intval($array['featureCount']));
- $entity->setLastFeatureTime($this->dbTimeToEntityTime($array['lastFeatureTime']));
- $entity->setFlags(intval($array['flags']));
- $entity->setMeta(Post::META_TAG_COUNT, intval($array['tagCount']));
- $entity->setMeta(Post::META_FAV_COUNT, intval($array['favCount']));
- $entity->setMeta(Post::META_COMMENT_COUNT, intval($array['commentCount']));
- $entity->setMeta(Post::META_SCORE, intval($array['score']));
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Post(intval($array['id']));
+ $entity->setName($array['name']);
+ $entity->setUserId($array['userId']);
+ $entity->setUploadTime($this->dbTimeToEntityTime($array['uploadTime']));
+ $entity->setLastEditTime($this->dbTimeToEntityTime($array['lastEditTime']));
+ $entity->setSafety(intval($array['safety']));
+ $entity->setContentType(intval($array['contentType']));
+ $entity->setContentChecksum($array['contentChecksum']);
+ $entity->setContentMimeType($array['contentMimeType']);
+ $entity->setSource($array['source']);
+ $entity->setImageWidth($array['imageWidth']);
+ $entity->setImageHeight($array['imageHeight']);
+ $entity->setOriginalFileSize($array['originalFileSize']);
+ $entity->setOriginalFileName($array['originalFileName']);
+ $entity->setFeatureCount(intval($array['featureCount']));
+ $entity->setLastFeatureTime($this->dbTimeToEntityTime($array['lastFeatureTime']));
+ $entity->setFlags(intval($array['flags']));
+ $entity->setMeta(Post::META_TAG_COUNT, intval($array['tagCount']));
+ $entity->setMeta(Post::META_FAV_COUNT, intval($array['favCount']));
+ $entity->setMeta(Post::META_COMMENT_COUNT, intval($array['commentCount']));
+ $entity->setMeta(Post::META_SCORE, intval($array['score']));
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/PostNoteEntityConverter.php b/src/Dao/EntityConverters/PostNoteEntityConverter.php
index 1ae357ba..69ffe79b 100644
--- a/src/Dao/EntityConverters/PostNoteEntityConverter.php
+++ b/src/Dao/EntityConverters/PostNoteEntityConverter.php
@@ -5,28 +5,28 @@ use Szurubooru\Entities\PostNote;
class PostNoteEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'postId' => $entity->getPostId(),
- 'x' => $entity->getLeft(),
- 'y' => $entity->getTop(),
- 'width' => $entity->getWidth(),
- 'height' => $entity->getHeight(),
- 'text' => $entity->getText(),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'postId' => $entity->getPostId(),
+ 'x' => $entity->getLeft(),
+ 'y' => $entity->getTop(),
+ 'width' => $entity->getWidth(),
+ 'height' => $entity->getHeight(),
+ 'text' => $entity->getText(),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new PostNote(intval($array['id']));
- $entity->setPostId($array['postId']);
- $entity->setLeft(floatval($array['x']));
- $entity->setTop(floatval($array['y']));
- $entity->setWidth(floatval($array['width']));
- $entity->setHeight(floatval($array['height']));
- $entity->setText($array['text']);
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new PostNote(intval($array['id']));
+ $entity->setPostId($array['postId']);
+ $entity->setLeft(floatval($array['x']));
+ $entity->setTop(floatval($array['y']));
+ $entity->setWidth(floatval($array['width']));
+ $entity->setHeight(floatval($array['height']));
+ $entity->setText($array['text']);
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/ScoreEntityConverter.php b/src/Dao/EntityConverters/ScoreEntityConverter.php
index f860b31f..c739a1bd 100644
--- a/src/Dao/EntityConverters/ScoreEntityConverter.php
+++ b/src/Dao/EntityConverters/ScoreEntityConverter.php
@@ -5,26 +5,26 @@ use Szurubooru\Entities\Score;
class ScoreEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'userId' => $entity->getUserId(),
- 'postId' => $entity->getPostId(),
- 'commentId' => $entity->getCommentId(),
- 'time' => $this->entityTimeToDbTime($entity->getTime()),
- 'score' => $entity->getScore(),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'userId' => $entity->getUserId(),
+ 'postId' => $entity->getPostId(),
+ 'commentId' => $entity->getCommentId(),
+ 'time' => $this->entityTimeToDbTime($entity->getTime()),
+ 'score' => $entity->getScore(),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Score(intval($array['id']));
- $entity->setUserId($array['userId']);
- $entity->setPostId($array['postId']);
- $entity->setCommentId($array['commentId']);
- $entity->setTime($this->dbTimeToEntityTime($array['time']));
- $entity->setScore(intval($array['score']));
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Score(intval($array['id']));
+ $entity->setUserId($array['userId']);
+ $entity->setPostId($array['postId']);
+ $entity->setCommentId($array['commentId']);
+ $entity->setTime($this->dbTimeToEntityTime($array['time']));
+ $entity->setScore(intval($array['score']));
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/SnapshotEntityConverter.php b/src/Dao/EntityConverters/SnapshotEntityConverter.php
index 17c37a81..65fc96d1 100644
--- a/src/Dao/EntityConverters/SnapshotEntityConverter.php
+++ b/src/Dao/EntityConverters/SnapshotEntityConverter.php
@@ -5,30 +5,30 @@ use Szurubooru\Entities\Snapshot;
class SnapshotEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'time' => $this->entityTimeToDbTime($entity->getTime()),
- 'type' => $entity->getType(),
- 'primaryKey' => $entity->getPrimaryKey(),
- 'userId' => $entity->getUserId(),
- 'operation' => $entity->getOperation(),
- 'data' => gzdeflate(json_encode($entity->getData())),
- 'dataDifference' => gzdeflate(json_encode($entity->getDataDifference())),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'time' => $this->entityTimeToDbTime($entity->getTime()),
+ 'type' => $entity->getType(),
+ 'primaryKey' => $entity->getPrimaryKey(),
+ 'userId' => $entity->getUserId(),
+ 'operation' => $entity->getOperation(),
+ 'data' => gzdeflate(json_encode($entity->getData())),
+ 'dataDifference' => gzdeflate(json_encode($entity->getDataDifference())),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Snapshot(intval($array['id']));
- $entity->setTime($this->dbTimeToEntityTime($array['time']));
- $entity->setType(intval($array['type']));
- $entity->setPrimaryKey($array['primaryKey']);
- $entity->setUserId(intval($array['userId']));
- $entity->setOperation($array['operation']);
- $entity->setData(json_decode(gzinflate($array['data']), true));
- $entity->setDataDifference(json_decode(gzinflate($array['dataDifference']), true));
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Snapshot(intval($array['id']));
+ $entity->setTime($this->dbTimeToEntityTime($array['time']));
+ $entity->setType(intval($array['type']));
+ $entity->setPrimaryKey($array['primaryKey']);
+ $entity->setUserId(intval($array['userId']));
+ $entity->setOperation($array['operation']);
+ $entity->setData(json_decode(gzinflate($array['data']), true));
+ $entity->setDataDifference(json_decode(gzinflate($array['dataDifference']), true));
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/TagEntityConverter.php b/src/Dao/EntityConverters/TagEntityConverter.php
index 2f012a76..d340b27d 100644
--- a/src/Dao/EntityConverters/TagEntityConverter.php
+++ b/src/Dao/EntityConverters/TagEntityConverter.php
@@ -5,25 +5,25 @@ use Szurubooru\Entities\Tag;
class TagEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'name' => $entity->getName(),
- 'creationTime' => $this->entityTimeToDbTime($entity->getCreationTime()),
- 'banned' => intval($entity->isBanned()),
- 'category' => $entity->getCategory(),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'name' => $entity->getName(),
+ 'creationTime' => $this->entityTimeToDbTime($entity->getCreationTime()),
+ 'banned' => intval($entity->isBanned()),
+ 'category' => $entity->getCategory(),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Tag(intval($array['id']));
- $entity->setName($array['name']);
- $entity->setCreationTime($this->dbTimeToEntityTime($array['creationTime']));
- $entity->setMeta(Tag::META_USAGES, intval($array['usages']));
- $entity->setBanned($array['banned']);
- $entity->setCategory($array['category']);
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Tag(intval($array['id']));
+ $entity->setName($array['name']);
+ $entity->setCreationTime($this->dbTimeToEntityTime($array['creationTime']));
+ $entity->setMeta(Tag::META_USAGES, intval($array['usages']));
+ $entity->setBanned($array['banned']);
+ $entity->setCategory($array['category']);
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/TokenEntityConverter.php b/src/Dao/EntityConverters/TokenEntityConverter.php
index 5d80fcb6..31063b9d 100644
--- a/src/Dao/EntityConverters/TokenEntityConverter.php
+++ b/src/Dao/EntityConverters/TokenEntityConverter.php
@@ -5,22 +5,22 @@ use Szurubooru\Entities\Token;
class TokenEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'name' => $entity->getName(),
- 'purpose' => $entity->getPurpose(),
- 'additionalData' => $entity->getAdditionalData(),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'name' => $entity->getName(),
+ 'purpose' => $entity->getPurpose(),
+ 'additionalData' => $entity->getAdditionalData(),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new Token(intval($array['id']));
- $entity->setName($array['name']);
- $entity->setPurpose($array['purpose']);
- $entity->setAdditionalData($array['additionalData']);
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new Token(intval($array['id']));
+ $entity->setName($array['name']);
+ $entity->setPurpose($array['purpose']);
+ $entity->setAdditionalData($array['additionalData']);
+ return $entity;
+ }
}
diff --git a/src/Dao/EntityConverters/UserEntityConverter.php b/src/Dao/EntityConverters/UserEntityConverter.php
index 6186fd25..a385299d 100644
--- a/src/Dao/EntityConverters/UserEntityConverter.php
+++ b/src/Dao/EntityConverters/UserEntityConverter.php
@@ -5,40 +5,40 @@ use Szurubooru\Entities\User;
class UserEntityConverter extends AbstractEntityConverter implements IEntityConverter
{
- public function toBasicArray(Entity $entity)
- {
- return
- [
- 'name' => $entity->getName(),
- 'email' => $entity->getEmail(),
- 'emailUnconfirmed' => $entity->getEmailUnconfirmed(),
- 'passwordHash' => $entity->getPasswordHash(),
- 'passwordSalt' => $entity->getPasswordSalt(),
- 'accessRank' => $entity->getAccessRank(),
- 'registrationTime' => $this->entityTimeToDbTime($entity->getRegistrationTime()),
- 'lastLoginTime' => $this->entityTimeToDbTime($entity->getLastLoginTime()),
- 'avatarStyle' => $entity->getAvatarStyle(),
- 'browsingSettings' => json_encode($entity->getBrowsingSettings()),
- 'accountConfirmed' => intval($entity->isAccountConfirmed()),
- 'banned' => intval($entity->isBanned()),
- ];
- }
+ public function toBasicArray(Entity $entity)
+ {
+ return
+ [
+ 'name' => $entity->getName(),
+ 'email' => $entity->getEmail(),
+ 'emailUnconfirmed' => $entity->getEmailUnconfirmed(),
+ 'passwordHash' => $entity->getPasswordHash(),
+ 'passwordSalt' => $entity->getPasswordSalt(),
+ 'accessRank' => $entity->getAccessRank(),
+ 'registrationTime' => $this->entityTimeToDbTime($entity->getRegistrationTime()),
+ 'lastLoginTime' => $this->entityTimeToDbTime($entity->getLastLoginTime()),
+ 'avatarStyle' => $entity->getAvatarStyle(),
+ 'browsingSettings' => json_encode($entity->getBrowsingSettings()),
+ 'accountConfirmed' => intval($entity->isAccountConfirmed()),
+ 'banned' => intval($entity->isBanned()),
+ ];
+ }
- public function toBasicEntity(array $array)
- {
- $entity = new User(intval($array['id']));
- $entity->setName($array['name']);
- $entity->setEmail($array['email']);
- $entity->setEmailUnconfirmed($array['emailUnconfirmed']);
- $entity->setPasswordHash($array['passwordHash']);
- $entity->setPasswordSalt($array['passwordSalt']);
- $entity->setAccessRank(intval($array['accessRank']));
- $entity->setRegistrationTime($this->dbTimeToEntityTime($array['registrationTime']));
- $entity->setLastLoginTime($this->dbTimeToEntityTime($array['lastLoginTime']));
- $entity->setAvatarStyle(intval($array['avatarStyle']));
- $entity->setBrowsingSettings(json_decode($array['browsingSettings']));
- $entity->setAccountConfirmed($array['accountConfirmed']);
- $entity->setBanned($array['banned']);
- return $entity;
- }
+ public function toBasicEntity(array $array)
+ {
+ $entity = new User(intval($array['id']));
+ $entity->setName($array['name']);
+ $entity->setEmail($array['email']);
+ $entity->setEmailUnconfirmed($array['emailUnconfirmed']);
+ $entity->setPasswordHash($array['passwordHash']);
+ $entity->setPasswordSalt($array['passwordSalt']);
+ $entity->setAccessRank(intval($array['accessRank']));
+ $entity->setRegistrationTime($this->dbTimeToEntityTime($array['registrationTime']));
+ $entity->setLastLoginTime($this->dbTimeToEntityTime($array['lastLoginTime']));
+ $entity->setAvatarStyle(intval($array['avatarStyle']));
+ $entity->setBrowsingSettings(json_decode($array['browsingSettings']));
+ $entity->setAccountConfirmed($array['accountConfirmed']);
+ $entity->setBanned($array['banned']);
+ return $entity;
+ }
}
diff --git a/src/Dao/FavoritesDao.php b/src/Dao/FavoritesDao.php
index 99efea03..4f23cc89 100644
--- a/src/Dao/FavoritesDao.php
+++ b/src/Dao/FavoritesDao.php
@@ -10,65 +10,65 @@ use Szurubooru\Services\TimeService;
class FavoritesDao extends AbstractDao implements ICrudDao
{
- private $timeService;
+ private $timeService;
- public function __construct(
- DatabaseConnection $databaseConnection,
- TimeService $timeService)
- {
- parent::__construct(
- $databaseConnection,
- 'favorites',
- new FavoriteEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ TimeService $timeService)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'favorites',
+ new FavoriteEntityConverter());
- $this->timeService = $timeService;
- }
+ $this->timeService = $timeService;
+ }
- public function findByEntity(Entity $entity)
- {
- if ($entity instanceof Post)
- return $this->findBy('postId', $entity->getId());
- else
- throw new \InvalidArgumentException();
- }
+ public function findByEntity(Entity $entity)
+ {
+ if ($entity instanceof Post)
+ return $this->findBy('postId', $entity->getId());
+ else
+ throw new \InvalidArgumentException();
+ }
- public function set(User $user, Entity $entity)
- {
- $favorite = $this->get($user, $entity);
- if (!$favorite)
- {
- $favorite = new Favorite();
- $favorite->setTime($this->timeService->getCurrentTime());
- $favorite->setUserId($user->getId());
+ public function set(User $user, Entity $entity)
+ {
+ $favorite = $this->get($user, $entity);
+ if (!$favorite)
+ {
+ $favorite = new Favorite();
+ $favorite->setTime($this->timeService->getCurrentTime());
+ $favorite->setUserId($user->getId());
- if ($entity instanceof Post)
- $favorite->setPostId($entity->getId());
- else
- throw new \InvalidArgumentException();
+ if ($entity instanceof Post)
+ $favorite->setPostId($entity->getId());
+ else
+ throw new \InvalidArgumentException();
- $this->save($favorite);
- }
- return $favorite;
- }
+ $this->save($favorite);
+ }
+ return $favorite;
+ }
- public function delete(User $user, Entity $entity)
- {
- $favorite = $this->get($user, $entity);
- if ($favorite)
- $this->deleteById($favorite->getId());
- }
+ public function delete(User $user, Entity $entity)
+ {
+ $favorite = $this->get($user, $entity);
+ if ($favorite)
+ $this->deleteById($favorite->getId());
+ }
- private function get(User $user, Entity $entity)
- {
- $query = $this->pdo->from($this->tableName)->where('userId', $user->getId());
+ private function get(User $user, Entity $entity)
+ {
+ $query = $this->pdo->from($this->tableName)->where('userId', $user->getId());
- if ($entity instanceof Post)
- $query->where('postId', $entity->getId());
- else
- throw new \InvalidArgumentException();
+ if ($entity instanceof Post)
+ $query->where('postId', $entity->getId());
+ else
+ throw new \InvalidArgumentException();
- $arrayEntities = iterator_to_array($query);
- $entities = $this->arrayToEntities($arrayEntities);
- return array_shift($entities);
- }
+ $arrayEntities = iterator_to_array($query);
+ $entities = $this->arrayToEntities($arrayEntities);
+ return array_shift($entities);
+ }
}
diff --git a/src/Dao/FileDao.php b/src/Dao/FileDao.php
index 512996cb..83a40146 100644
--- a/src/Dao/FileDao.php
+++ b/src/Dao/FileDao.php
@@ -4,93 +4,93 @@ use Szurubooru\Dao\IFileDao;
class FileDao implements IFileDao
{
- private $directory;
+ private $directory;
- public function __construct($directory)
- {
- $this->directory = $directory;
- }
+ public function __construct($directory)
+ {
+ $this->directory = $directory;
+ }
- public function load($fileName)
- {
- $fullPath = $this->getFullPath($fileName);
- return file_exists($fullPath)
- ? file_get_contents($fullPath)
- : null;
- }
+ public function load($fileName)
+ {
+ $fullPath = $this->getFullPath($fileName);
+ return file_exists($fullPath)
+ ? file_get_contents($fullPath)
+ : null;
+ }
- public function save($fileName, $data)
- {
- $fullPath = $this->getFullPath($fileName);
- $this->createFolders($fileName);
- file_put_contents($fullPath, $data);
- }
+ public function save($fileName, $data)
+ {
+ $fullPath = $this->getFullPath($fileName);
+ $this->createFolders($fileName);
+ file_put_contents($fullPath, $data);
+ }
- public function delete($fileName)
- {
- $fullPath = $this->getFullPath($fileName);
- if (file_exists($fullPath))
- unlink($fullPath);
- }
+ public function delete($fileName)
+ {
+ $fullPath = $this->getFullPath($fileName);
+ if (file_exists($fullPath))
+ unlink($fullPath);
+ }
- public function exists($fileName)
- {
- $fullPath = $this->getFullPath($fileName);
- return file_exists($fullPath);
- }
+ public function exists($fileName)
+ {
+ $fullPath = $this->getFullPath($fileName);
+ return file_exists($fullPath);
+ }
- public function getFullPath($fileName)
- {
- return $this->directory . DIRECTORY_SEPARATOR . $fileName;
- }
+ public function getFullPath($fileName)
+ {
+ return $this->directory . DIRECTORY_SEPARATOR . $fileName;
+ }
- public function listAll()
- {
- $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory));
- $files = [];
- foreach ($iterator as $path)
- {
- if (!$path->isDir())
- $files[] = $this->getRelativePath($this->directory, $path->getPathName());
- }
- return $files;
- }
+ public function listAll()
+ {
+ $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory));
+ $files = [];
+ foreach ($iterator as $path)
+ {
+ if (!$path->isDir())
+ $files[] = $this->getRelativePath($this->directory, $path->getPathName());
+ }
+ return $files;
+ }
- private function createFolders($fileName)
- {
- $fullPath = dirname($this->getFullPath($fileName));
- if (!file_exists($fullPath))
- mkdir($fullPath, 0777, true);
- }
+ private function createFolders($fileName)
+ {
+ $fullPath = dirname($this->getFullPath($fileName));
+ if (!file_exists($fullPath))
+ mkdir($fullPath, 0777, true);
+ }
- private function getRelativePath($from, $to)
- {
- $from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
- $to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
- $from = explode('/', str_replace('\\', '/', $from));
- $to = explode('/', str_replace('\\', '/', $to));
- $relPath = $to;
- foreach($from as $depth => $dir)
- {
- if($dir === $to[$depth])
- {
- array_shift($relPath);
- }
- else
- {
- $remaining = count($from) - $depth;
- if ($remaining > 1)
- {
- $padLength = (count($relPath) + $remaining - 1) * -1;
- $relPath = array_pad($relPath, $padLength, '..');
- break;
- }
- else
- {
- $relPath[0] = $relPath[0];
- }
- }
- }
- return implode('/', $relPath);
- }
+ private function getRelativePath($from, $to)
+ {
+ $from = is_dir($from) ? rtrim($from, '\/') . '/' : $from;
+ $to = is_dir($to) ? rtrim($to, '\/') . '/' : $to;
+ $from = explode('/', str_replace('\\', '/', $from));
+ $to = explode('/', str_replace('\\', '/', $to));
+ $relPath = $to;
+ foreach($from as $depth => $dir)
+ {
+ if($dir === $to[$depth])
+ {
+ array_shift($relPath);
+ }
+ else
+ {
+ $remaining = count($from) - $depth;
+ if ($remaining > 1)
+ {
+ $padLength = (count($relPath) + $remaining - 1) * -1;
+ $relPath = array_pad($relPath, $padLength, '..');
+ break;
+ }
+ else
+ {
+ $relPath[0] = $relPath[0];
+ }
+ }
+ }
+ return implode('/', $relPath);
+ }
}
diff --git a/src/Dao/GlobalParamDao.php b/src/Dao/GlobalParamDao.php
index ba0817c5..1a4631de 100644
--- a/src/Dao/GlobalParamDao.php
+++ b/src/Dao/GlobalParamDao.php
@@ -5,32 +5,32 @@ use Szurubooru\DatabaseConnection;
class GlobalParamDao extends AbstractDao implements ICrudDao
{
- public function __construct(DatabaseConnection $databaseConnection)
- {
- parent::__construct(
- $databaseConnection,
- 'globals',
- new GlobalParamEntityConverter());
- }
+ public function __construct(DatabaseConnection $databaseConnection)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'globals',
+ new GlobalParamEntityConverter());
+ }
- public function save(&$entity)
- {
- if (!$entity->getId())
- {
- $otherEntityWithThisKey = $this->findByKey($entity->getKey());
- if ($otherEntityWithThisKey)
- $entity->setId($otherEntityWithThisKey->getId());
- }
- parent::save($entity);
- }
+ public function save(&$entity)
+ {
+ if (!$entity->getId())
+ {
+ $otherEntityWithThisKey = $this->findByKey($entity->getKey());
+ if ($otherEntityWithThisKey)
+ $entity->setId($otherEntityWithThisKey->getId());
+ }
+ parent::save($entity);
+ }
- public function findByKey($key)
- {
- return $this->findOneBy('dataKey', $key);
- }
+ public function findByKey($key)
+ {
+ return $this->findOneBy('dataKey', $key);
+ }
- public function deleteByKey($key)
- {
- return $this->deleteBy('dataKey', $key);
- }
+ public function deleteByKey($key)
+ {
+ return $this->deleteBy('dataKey', $key);
+ }
}
diff --git a/src/Dao/IBatchDao.php b/src/Dao/IBatchDao.php
index 2e6a459f..1847c369 100644
--- a/src/Dao/IBatchDao.php
+++ b/src/Dao/IBatchDao.php
@@ -3,9 +3,9 @@ namespace Szurubooru\Dao;
interface IBatchDao
{
- public function findAll();
+ public function findAll();
- public function deleteAll();
+ public function deleteAll();
- public function batchSave(array $objects);
+ public function batchSave(array $objects);
}
diff --git a/src/Dao/ICrudDao.php b/src/Dao/ICrudDao.php
index 34ac7a7c..f4e17fb0 100644
--- a/src/Dao/ICrudDao.php
+++ b/src/Dao/ICrudDao.php
@@ -3,9 +3,9 @@ namespace Szurubooru\Dao;
interface ICrudDao
{
- public function findById($objectId);
+ public function findById($objectId);
- public function save(&$object);
+ public function save(&$object);
- public function deleteById($objectId);
+ public function deleteById($objectId);
}
diff --git a/src/Dao/IFileDao.php b/src/Dao/IFileDao.php
index 9f6d8aac..6d8b678c 100644
--- a/src/Dao/IFileDao.php
+++ b/src/Dao/IFileDao.php
@@ -3,11 +3,11 @@ namespace Szurubooru\Dao;
interface IFileDao
{
- public function load($fileName);
+ public function load($fileName);
- public function save($fileName, $contents);
+ public function save($fileName, $contents);
- public function delete($fileName);
+ public function delete($fileName);
- public function exists($fileName);
+ public function exists($fileName);
}
diff --git a/src/Dao/PostDao.php b/src/Dao/PostDao.php
index 6c473fe5..c9a59f61 100644
--- a/src/Dao/PostDao.php
+++ b/src/Dao/PostDao.php
@@ -13,295 +13,295 @@ use Szurubooru\Services\ThumbnailService;
class PostDao extends AbstractDao implements ICrudDao
{
- private $tagDao;
- private $userDao;
- private $fileDao;
- private $thumbnailService;
+ private $tagDao;
+ private $userDao;
+ private $fileDao;
+ private $thumbnailService;
- public function __construct(
- DatabaseConnection $databaseConnection,
- TagDao $tagDao,
- UserDao $userDao,
- PublicFileDao $fileDao,
- ThumbnailService $thumbnailService)
- {
- parent::__construct(
- $databaseConnection,
- 'posts',
- new PostEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ TagDao $tagDao,
+ UserDao $userDao,
+ PublicFileDao $fileDao,
+ ThumbnailService $thumbnailService)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'posts',
+ new PostEntityConverter());
- $this->tagDao = $tagDao;
- $this->userDao = $userDao;
- $this->fileDao = $fileDao;
- $this->thumbnailService = $thumbnailService;
- }
+ $this->tagDao = $tagDao;
+ $this->userDao = $userDao;
+ $this->fileDao = $fileDao;
+ $this->thumbnailService = $thumbnailService;
+ }
- public function getCount()
- {
- return count($this->pdo->from($this->tableName));
- }
+ public function getCount()
+ {
+ return count($this->pdo->from($this->tableName));
+ }
- public function getTotalFileSize()
- {
- $query = $this->pdo->from($this->tableName)->select('SUM(originalFileSize) AS __sum');
- return iterator_to_array($query)[0]['__sum'];
- }
+ public function getTotalFileSize()
+ {
+ $query = $this->pdo->from($this->tableName)->select('SUM(originalFileSize) AS __sum');
+ return iterator_to_array($query)[0]['__sum'];
+ }
- public function findByName($name)
- {
- return $this->findOneBy('name', $name);
- }
+ public function findByName($name)
+ {
+ return $this->findOneBy('name', $name);
+ }
- public function findByTagName($tagName)
- {
- $query = $this->pdo->from('posts')
- ->innerJoin('postTags', 'postTags.postId = posts.id')
- ->innerJoin('tags', 'postTags.tagId = tags.id')
- ->where('tags.name', $tagName);
- $arrayEntities = iterator_to_array($query);
- return $this->arrayToEntities($arrayEntities);
- }
+ public function findByTagName($tagName)
+ {
+ $query = $this->pdo->from('posts')
+ ->innerJoin('postTags', 'postTags.postId = posts.id')
+ ->innerJoin('tags', 'postTags.tagId = tags.id')
+ ->where('tags.name', $tagName);
+ $arrayEntities = iterator_to_array($query);
+ return $this->arrayToEntities($arrayEntities);
+ }
- public function findByContentChecksum($checksum)
- {
- return $this->findOneBy('contentChecksum', $checksum);
- }
+ public function findByContentChecksum($checksum)
+ {
+ return $this->findOneBy('contentChecksum', $checksum);
+ }
- protected function afterLoad(Entity $post)
- {
- $post->setLazyLoader(
- Post::LAZY_LOADER_CONTENT,
- function (Post $post)
- {
- return $this->fileDao->load($post->getContentPath());
- });
+ protected function afterLoad(Entity $post)
+ {
+ $post->setLazyLoader(
+ Post::LAZY_LOADER_CONTENT,
+ function (Post $post)
+ {
+ return $this->fileDao->load($post->getContentPath());
+ });
- $post->setLazyLoader(
- Post::LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT,
- function (Post $post)
- {
- return $this->fileDao->load($post->getThumbnailSourceContentPath());
- });
+ $post->setLazyLoader(
+ Post::LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT,
+ function (Post $post)
+ {
+ return $this->fileDao->load($post->getThumbnailSourceContentPath());
+ });
- $post->setLazyLoader(
- Post::LAZY_LOADER_USER,
- function (Post $post)
- {
- return $this->getUser($post);
- });
+ $post->setLazyLoader(
+ Post::LAZY_LOADER_USER,
+ function (Post $post)
+ {
+ return $this->getUser($post);
+ });
- $post->setLazyLoader(
- Post::LAZY_LOADER_TAGS,
- function (Post $post)
- {
- return $this->getTags($post);
- });
+ $post->setLazyLoader(
+ Post::LAZY_LOADER_TAGS,
+ function (Post $post)
+ {
+ return $this->getTags($post);
+ });
- $post->setLazyLoader(
- Post::LAZY_LOADER_RELATED_POSTS,
- function (Post $post)
- {
- return $this->getRelatedPosts($post);
- });
- }
+ $post->setLazyLoader(
+ Post::LAZY_LOADER_RELATED_POSTS,
+ function (Post $post)
+ {
+ return $this->getRelatedPosts($post);
+ });
+ }
- protected function afterSave(Entity $post)
- {
- $this->syncContent($post);
- $this->syncThumbnailSourceContent($post);
- $this->syncTags($post);
- $this->syncPostRelations($post);
- }
+ protected function afterSave(Entity $post)
+ {
+ $this->syncContent($post);
+ $this->syncThumbnailSourceContent($post);
+ $this->syncTags($post);
+ $this->syncPostRelations($post);
+ }
- protected function decorateQueryFromRequirement($query, Requirement $requirement)
- {
- if ($requirement->getType() === PostFilter::REQUIREMENT_TAG)
- {
- $tagName = $requirement->getValue()->getValue();
- $tag = $this->tagDao->findByName($tagName);
- if (!$tag)
- throw new \DomainException('Invalid tag: "' . $tagName . '"');
+ protected function decorateQueryFromRequirement($query, Requirement $requirement)
+ {
+ if ($requirement->getType() === PostFilter::REQUIREMENT_TAG)
+ {
+ $tagName = $requirement->getValue()->getValue();
+ $tag = $this->tagDao->findByName($tagName);
+ if (!$tag)
+ throw new \DomainException('Invalid tag: "' . $tagName . '"');
- $sql = 'EXISTS (
- SELECT 1 FROM postTags
- WHERE postTags.postId = posts.id
- AND postTags.tagId = ?)';
+ $sql = 'EXISTS (
+ SELECT 1 FROM postTags
+ WHERE postTags.postId = posts.id
+ AND postTags.tagId = ?)';
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
- $query->where($sql, $tag->getId());
- return;
- }
+ $query->where($sql, $tag->getId());
+ return;
+ }
- elseif ($requirement->getType() === PostFilter::REQUIREMENT_FAVORITE)
- {
- foreach ($requirement->getValue()->getValues() as $userName)
- {
- $sql = 'EXISTS (
- SELECT 1 FROM favorites f
- WHERE f.postId = posts.id
- AND f.userId = (SELECT id FROM users WHERE name = ?))';
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
- $query->where($sql, [$userName]);
- }
- return;
- }
+ elseif ($requirement->getType() === PostFilter::REQUIREMENT_FAVORITE)
+ {
+ foreach ($requirement->getValue()->getValues() as $userName)
+ {
+ $sql = 'EXISTS (
+ SELECT 1 FROM favorites f
+ WHERE f.postId = posts.id
+ AND f.userId = (SELECT id FROM users WHERE name = ?))';
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
+ $query->where($sql, [$userName]);
+ }
+ return;
+ }
- elseif ($requirement->getType() === PostFilter::REQUIREMENT_COMMENT_AUTHOR)
- {
- foreach ($requirement->getValue()->getValues() as $userName)
- {
- $sql = 'EXISTS (
- SELECT 1 FROM comments c
- WHERE c.postId = posts.id
- AND c.userId = (SELECT id FROM users WHERE name = ?))';
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
- $query->where($sql, [$userName]);
- }
- return;
- }
+ elseif ($requirement->getType() === PostFilter::REQUIREMENT_COMMENT_AUTHOR)
+ {
+ foreach ($requirement->getValue()->getValues() as $userName)
+ {
+ $sql = 'EXISTS (
+ SELECT 1 FROM comments c
+ WHERE c.postId = posts.id
+ AND c.userId = (SELECT id FROM users WHERE name = ?))';
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
+ $query->where($sql, [$userName]);
+ }
+ return;
+ }
- elseif ($requirement->getType() === PostFilter::REQUIREMENT_UPLOADER)
- {
- foreach ($requirement->getValue()->getValues() as $userName)
- {
- $alias = 'u' . uniqid();
- $query->innerJoin('users ' . $alias, $alias . '.id = posts.userId');
- $sql = $alias . '.name = ?';
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
- $query->where($sql, [$userName]);
- }
- return;
- }
+ elseif ($requirement->getType() === PostFilter::REQUIREMENT_UPLOADER)
+ {
+ foreach ($requirement->getValue()->getValues() as $userName)
+ {
+ $alias = 'u' . uniqid();
+ $query->innerJoin('users ' . $alias, $alias . '.id = posts.userId');
+ $sql = $alias . '.name = ?';
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
+ $query->where($sql, [$userName]);
+ }
+ return;
+ }
- elseif ($requirement->getType() === PostFilter::REQUIREMENT_USER_SCORE)
- {
- $values = $requirement->getValue()->getValues();
- $userName = $values[0];
- $score = $values[1];
- $sql = 'EXISTS (
- SELECT 1 FROM scores
- WHERE scores.postId = posts.id
- AND scores.userId = (SELECT id FROM users WHERE name = ?)
- AND scores.score = ?)';
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
- $query->where($sql, [$userName, $score]);
- return;
- }
+ elseif ($requirement->getType() === PostFilter::REQUIREMENT_USER_SCORE)
+ {
+ $values = $requirement->getValue()->getValues();
+ $userName = $values[0];
+ $score = $values[1];
+ $sql = 'EXISTS (
+ SELECT 1 FROM scores
+ WHERE scores.postId = posts.id
+ AND scores.userId = (SELECT id FROM users WHERE name = ?)
+ AND scores.score = ?)';
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
+ $query->where($sql, [$userName, $score]);
+ return;
+ }
- parent::decorateQueryFromRequirement($query, $requirement);
- }
+ parent::decorateQueryFromRequirement($query, $requirement);
+ }
- private function getTags(Post $post)
- {
- return $this->tagDao->findByPostId($post->getId());
- }
+ private function getTags(Post $post)
+ {
+ return $this->tagDao->findByPostId($post->getId());
+ }
- private function getUser(Post $post)
- {
- return $this->userDao->findById($post->getUserId());
- }
+ private function getUser(Post $post)
+ {
+ return $this->userDao->findById($post->getUserId());
+ }
- private function getRelatedPosts(Post $post)
- {
- $relatedPostIds = [];
+ private function getRelatedPosts(Post $post)
+ {
+ $relatedPostIds = [];
- foreach ($this->pdo->from('postRelations')->where('post1id', $post->getId()) as $arrayEntity)
- {
- $postId = intval($arrayEntity['post2id']);
- if ($postId !== $post->getId())
- $relatedPostIds[] = $postId;
- }
+ foreach ($this->pdo->from('postRelations')->where('post1id', $post->getId()) as $arrayEntity)
+ {
+ $postId = intval($arrayEntity['post2id']);
+ if ($postId !== $post->getId())
+ $relatedPostIds[] = $postId;
+ }
- foreach ($this->pdo->from('postRelations')->where('post2id', $post->getId()) as $arrayEntity)
- {
- $postId = intval($arrayEntity['post1id']);
- if ($postId !== $post->getId())
- $relatedPostIds[] = $postId;
- }
+ foreach ($this->pdo->from('postRelations')->where('post2id', $post->getId()) as $arrayEntity)
+ {
+ $postId = intval($arrayEntity['post1id']);
+ if ($postId !== $post->getId())
+ $relatedPostIds[] = $postId;
+ }
- return $this->findByIds($relatedPostIds);
- }
+ return $this->findByIds($relatedPostIds);
+ }
- private function syncContent(Post $post)
- {
- $targetPath = $post->getContentPath();
- $content = $post->getContent();
- if ($content)
- $this->fileDao->save($targetPath, $content);
- else
- $this->fileDao->delete($targetPath, $content);
- $this->thumbnailService->deleteUsedThumbnails($targetPath);
- }
+ private function syncContent(Post $post)
+ {
+ $targetPath = $post->getContentPath();
+ $content = $post->getContent();
+ if ($content)
+ $this->fileDao->save($targetPath, $content);
+ else
+ $this->fileDao->delete($targetPath, $content);
+ $this->thumbnailService->deleteUsedThumbnails($targetPath);
+ }
- private function syncThumbnailSourceContent(Post $post)
- {
- $targetPath = $post->getThumbnailSourceContentPath();
- $content = $post->getThumbnailSourceContent();
- if ($content)
- $this->fileDao->save($targetPath, $content);
- else
- $this->fileDao->delete($targetPath);
- $this->thumbnailService->deleteUsedThumbnails($targetPath);
- }
+ private function syncThumbnailSourceContent(Post $post)
+ {
+ $targetPath = $post->getThumbnailSourceContentPath();
+ $content = $post->getThumbnailSourceContent();
+ if ($content)
+ $this->fileDao->save($targetPath, $content);
+ else
+ $this->fileDao->delete($targetPath);
+ $this->thumbnailService->deleteUsedThumbnails($targetPath);
+ }
- private function syncTags(Post $post)
- {
- $tagIds = array_map(
- function ($tag)
- {
- if (!$tag->getId())
- throw new \RuntimeException('Unsaved entities found');
- return $tag->getId();
- },
- $post->getTags());
+ private function syncTags(Post $post)
+ {
+ $tagIds = array_map(
+ function ($tag)
+ {
+ if (!$tag->getId())
+ throw new \RuntimeException('Unsaved entities found');
+ return $tag->getId();
+ },
+ $post->getTags());
- $existingTagRelationIds = array_map(
- function ($arrayEntity)
- {
- return $arrayEntity['tagId'];
- },
- iterator_to_array($this->pdo->from('postTags')->where('postId', $post->getId())));
+ $existingTagRelationIds = array_map(
+ function ($arrayEntity)
+ {
+ return $arrayEntity['tagId'];
+ },
+ iterator_to_array($this->pdo->from('postTags')->where('postId', $post->getId())));
- $tagRelationsToInsert = array_diff($tagIds, $existingTagRelationIds);
- $tagRelationsToDelete = array_diff($existingTagRelationIds, $tagIds);
+ $tagRelationsToInsert = array_diff($tagIds, $existingTagRelationIds);
+ $tagRelationsToDelete = array_diff($existingTagRelationIds, $tagIds);
- foreach ($tagRelationsToInsert as $tagId)
- {
- $this->pdo->insertInto('postTags')->values(['postId' => $post->getId(), 'tagId' => $tagId])->execute();
- }
- foreach ($tagRelationsToDelete as $tagId)
- {
- $this->pdo->deleteFrom('postTags')->where('postId', $post->getId())->where('tagId', $tagId)->execute();
- }
- }
+ foreach ($tagRelationsToInsert as $tagId)
+ {
+ $this->pdo->insertInto('postTags')->values(['postId' => $post->getId(), 'tagId' => $tagId])->execute();
+ }
+ foreach ($tagRelationsToDelete as $tagId)
+ {
+ $this->pdo->deleteFrom('postTags')->where('postId', $post->getId())->where('tagId', $tagId)->execute();
+ }
+ }
- private function syncPostRelations(Post $post)
- {
- $relatedPostIds = array_filter(array_unique(array_map(
- function ($post)
- {
- if (!$post->getId())
- throw new \RuntimeException('Unsaved entities found');
- return $post->getId();
- },
- $post->getRelatedPosts())));
+ private function syncPostRelations(Post $post)
+ {
+ $relatedPostIds = array_filter(array_unique(array_map(
+ function ($post)
+ {
+ if (!$post->getId())
+ throw new \RuntimeException('Unsaved entities found');
+ return $post->getId();
+ },
+ $post->getRelatedPosts())));
- $this->pdo->deleteFrom('postRelations')->where('post1id', $post->getId())->execute();
- $this->pdo->deleteFrom('postRelations')->where('post2id', $post->getId())->execute();
- foreach ($relatedPostIds as $postId)
- {
- $this->pdo
- ->insertInto('postRelations')
- ->values([
- 'post1id' => $post->getId(),
- 'post2id' => $postId])
- ->execute();
- }
- }
+ $this->pdo->deleteFrom('postRelations')->where('post1id', $post->getId())->execute();
+ $this->pdo->deleteFrom('postRelations')->where('post2id', $post->getId())->execute();
+ foreach ($relatedPostIds as $postId)
+ {
+ $this->pdo
+ ->insertInto('postRelations')
+ ->values([
+ 'post1id' => $post->getId(),
+ 'post2id' => $postId])
+ ->execute();
+ }
+ }
}
diff --git a/src/Dao/PostNoteDao.php b/src/Dao/PostNoteDao.php
index 939fec90..8bfec398 100644
--- a/src/Dao/PostNoteDao.php
+++ b/src/Dao/PostNoteDao.php
@@ -8,32 +8,32 @@ use Szurubooru\Entities\PostNote;
class PostNoteDao extends AbstractDao implements ICrudDao
{
- private $postDao;
+ private $postDao;
- public function __construct(
- DatabaseConnection $databaseConnection,
- PostDao $postDao)
- {
- parent::__construct(
- $databaseConnection,
- 'postNotes',
- new PostNoteEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ PostDao $postDao)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'postNotes',
+ new PostNoteEntityConverter());
- $this->postDao = $postDao;
- }
+ $this->postDao = $postDao;
+ }
- public function findByPostId($postId)
- {
- return $this->findBy('postId', $postId);
- }
+ public function findByPostId($postId)
+ {
+ return $this->findBy('postId', $postId);
+ }
- protected function afterLoad(Entity $postNote)
- {
- $postNote->setLazyLoader(
- PostNote::LAZY_LOADER_POST,
- function (PostNote $postNote)
- {
- return $this->postDao->findById($postNote->getPostId());
- });
- }
+ protected function afterLoad(Entity $postNote)
+ {
+ $postNote->setLazyLoader(
+ PostNote::LAZY_LOADER_POST,
+ function (PostNote $postNote)
+ {
+ return $this->postDao->findById($postNote->getPostId());
+ });
+ }
}
diff --git a/src/Dao/PublicFileDao.php b/src/Dao/PublicFileDao.php
index 4987d7a0..570a0c4c 100644
--- a/src/Dao/PublicFileDao.php
+++ b/src/Dao/PublicFileDao.php
@@ -6,8 +6,8 @@ use Szurubooru\Dao\IFileDao;
class PublicFileDao extends FileDao implements IFileDao
{
- public function __construct(Config $config)
- {
- parent::__construct($config->getPublicDataDirectory());
- }
+ public function __construct(Config $config)
+ {
+ parent::__construct($config->getPublicDataDirectory());
+ }
}
diff --git a/src/Dao/ScoreDao.php b/src/Dao/ScoreDao.php
index c4b89bb3..da53570b 100644
--- a/src/Dao/ScoreDao.php
+++ b/src/Dao/ScoreDao.php
@@ -11,70 +11,70 @@ use Szurubooru\Services\TimeService;
class ScoreDao extends AbstractDao implements ICrudDao
{
- private $timeService;
+ private $timeService;
- public function __construct(
- DatabaseConnection $databaseConnection,
- TimeService $timeService)
- {
- parent::__construct(
- $databaseConnection,
- 'scores',
- new ScoreEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ TimeService $timeService)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'scores',
+ new ScoreEntityConverter());
- $this->timeService = $timeService;
- }
+ $this->timeService = $timeService;
+ }
- public function getScoreValue(Entity $entity)
- {
- $query = $this->getBaseQuery($entity);
- $query->select(null);
- $query->select('SUM(score) AS score');
- return iterator_to_array($query)[0]['score'];
- }
+ public function getScoreValue(Entity $entity)
+ {
+ $query = $this->getBaseQuery($entity);
+ $query->select(null);
+ $query->select('SUM(score) AS score');
+ return iterator_to_array($query)[0]['score'];
+ }
- public function getUserScore(User $user, Entity $entity)
- {
- $query = $this->getBaseQuery($entity);
- $query->where('userId', $user->getId());
+ public function getUserScore(User $user, Entity $entity)
+ {
+ $query = $this->getBaseQuery($entity);
+ $query->where('userId', $user->getId());
- $arrayEntities = iterator_to_array($query);
- $entities = $this->arrayToEntities($arrayEntities);
- return array_shift($entities);
- }
+ $arrayEntities = iterator_to_array($query);
+ $entities = $this->arrayToEntities($arrayEntities);
+ return array_shift($entities);
+ }
- public function setUserScore(User $user, Entity $entity, $scoreValue)
- {
- $score = $this->getUserScore($user, $entity);
- if (!$score)
- {
- $score = new Score();
- $score->setTime($this->timeService->getCurrentTime());
- $score->setUserId($user->getId());
+ public function setUserScore(User $user, Entity $entity, $scoreValue)
+ {
+ $score = $this->getUserScore($user, $entity);
+ if (!$score)
+ {
+ $score = new Score();
+ $score->setTime($this->timeService->getCurrentTime());
+ $score->setUserId($user->getId());
- if ($entity instanceof Post)
- $score->setPostId($entity->getId());
- elseif ($entity instanceof Comment)
- $score->setCommentId($entity->getId());
- else
- throw new \InvalidArgumentException();
- }
- $score->setScore($scoreValue);
- $this->save($score);
- return $score;
- }
+ if ($entity instanceof Post)
+ $score->setPostId($entity->getId());
+ elseif ($entity instanceof Comment)
+ $score->setCommentId($entity->getId());
+ else
+ throw new \InvalidArgumentException();
+ }
+ $score->setScore($scoreValue);
+ $this->save($score);
+ return $score;
+ }
- private function getBaseQuery($entity)
- {
- $query = $this->pdo->from($this->tableName);
+ private function getBaseQuery($entity)
+ {
+ $query = $this->pdo->from($this->tableName);
- if ($entity instanceof Post)
- $query->where('postId', $entity->getId());
- elseif ($entity instanceof Comment)
- $query->where('commentId', $entity->getId());
- else
- throw new \InvalidArgumentException();
+ if ($entity instanceof Post)
+ $query->where('postId', $entity->getId());
+ elseif ($entity instanceof Comment)
+ $query->where('commentId', $entity->getId());
+ else
+ throw new \InvalidArgumentException();
- return $query;
- }
+ return $query;
+ }
}
diff --git a/src/Dao/SnapshotDao.php b/src/Dao/SnapshotDao.php
index 7f41293a..290d2578 100644
--- a/src/Dao/SnapshotDao.php
+++ b/src/Dao/SnapshotDao.php
@@ -8,47 +8,47 @@ use Szurubooru\Entities\Snapshot;
class SnapshotDao extends AbstractDao
{
- private $userDao;
+ private $userDao;
- public function __construct(
- DatabaseConnection $databaseConnection,
- UserDao $userDao)
- {
- parent::__construct(
- $databaseConnection,
- 'snapshots',
- new SnapshotEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ UserDao $userDao)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'snapshots',
+ new SnapshotEntityConverter());
- $this->userDao = $userDao;
- }
+ $this->userDao = $userDao;
+ }
- public function findEarlierSnapshots(Snapshot $snapshot)
- {
- $query = $this->pdo
- ->from($this->tableName)
- ->where('type', $snapshot->getType())
- ->where('primaryKey', $snapshot->getPrimaryKey())
- ->orderBy('time DESC');
+ public function findEarlierSnapshots(Snapshot $snapshot)
+ {
+ $query = $this->pdo
+ ->from($this->tableName)
+ ->where('type', $snapshot->getType())
+ ->where('primaryKey', $snapshot->getPrimaryKey())
+ ->orderBy('time DESC');
- if ($snapshot->getId())
- $query->where('id < ?', $snapshot->getId());
+ if ($snapshot->getId())
+ $query->where('id < ?', $snapshot->getId());
- return $this->arrayToEntities(iterator_to_array($query));
- }
+ return $this->arrayToEntities(iterator_to_array($query));
+ }
- public function afterLoad(Entity $snapshot)
- {
- $snapshot->setLazyLoader(
- Snapshot::LAZY_LOADER_USER,
- function (Snapshot $snapshot)
- {
- return $this->getUser($snapshot);
- });
- }
+ public function afterLoad(Entity $snapshot)
+ {
+ $snapshot->setLazyLoader(
+ Snapshot::LAZY_LOADER_USER,
+ function (Snapshot $snapshot)
+ {
+ return $this->getUser($snapshot);
+ });
+ }
- private function getUser(Snapshot $snapshot)
- {
- $userId = $snapshot->getUserId();
- return $this->userDao->findById($userId);
- }
+ private function getUser(Snapshot $snapshot)
+ {
+ $userId = $snapshot->getUserId();
+ return $this->userDao->findById($userId);
+ }
}
diff --git a/src/Dao/TagDao.php b/src/Dao/TagDao.php
index 9d723aaa..5c0f77d5 100644
--- a/src/Dao/TagDao.php
+++ b/src/Dao/TagDao.php
@@ -10,213 +10,213 @@ use Szurubooru\Search\Requirements\Requirement;
class TagDao extends AbstractDao implements ICrudDao
{
- const TAG_RELATION_IMPLICATION = 1;
- const TAG_RELATION_SUGGESTION = 2;
+ const TAG_RELATION_IMPLICATION = 1;
+ const TAG_RELATION_SUGGESTION = 2;
- public function __construct(DatabaseConnection $databaseConnection)
- {
- parent::__construct(
- $databaseConnection,
- 'tags',
- new TagEntityConverter());
- }
+ public function __construct(DatabaseConnection $databaseConnection)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'tags',
+ new TagEntityConverter());
+ }
- public function findByName($tagName)
- {
- return $this->findOneBy('name', $tagName);
- }
+ public function findByName($tagName)
+ {
+ return $this->findOneBy('name', $tagName);
+ }
- public function findByNames($tagNames)
- {
- return $this->findBy('name', $tagNames);
- }
+ public function findByNames($tagNames)
+ {
+ return $this->findBy('name', $tagNames);
+ }
- public function findByPostId($postId)
- {
- return $this->findByPostIds([$postId]);
- }
+ public function findByPostId($postId)
+ {
+ return $this->findByPostIds([$postId]);
+ }
- public function findByPostIds($postIds)
- {
- $query = $this->pdo->from($this->tableName)
- ->innerJoin('postTags', 'postTags.tagId = tags.id')
- ->where('postTags.postId', $postIds);
- $arrayEntities = iterator_to_array($query);
- return $this->arrayToEntities($arrayEntities);
- }
+ public function findByPostIds($postIds)
+ {
+ $query = $this->pdo->from($this->tableName)
+ ->innerJoin('postTags', 'postTags.tagId = tags.id')
+ ->where('postTags.postId', $postIds);
+ $arrayEntities = iterator_to_array($query);
+ return $this->arrayToEntities($arrayEntities);
+ }
- public function findSiblings($tagName)
- {
- $tag = $this->findByName($tagName);
- if (!$tag)
- return [];
- $tagId = $tag->getId();
- $query = $this->pdo->from($this->tableName)
- ->select('COUNT(pt2.postId) AS postCount')
- ->innerJoin('postTags pt1', 'pt1.tagId = tags.id')
- ->innerJoin('postTags pt2', 'pt2.postId = pt1.postId')
- ->where('pt2.tagId', $tagId)
- ->groupBy('tags.id')
- ->orderBy('postCount DESC, name ASC');
+ public function findSiblings($tagName)
+ {
+ $tag = $this->findByName($tagName);
+ if (!$tag)
+ return [];
+ $tagId = $tag->getId();
+ $query = $this->pdo->from($this->tableName)
+ ->select('COUNT(pt2.postId) AS postCount')
+ ->innerJoin('postTags pt1', 'pt1.tagId = tags.id')
+ ->innerJoin('postTags pt2', 'pt2.postId = pt1.postId')
+ ->where('pt2.tagId', $tagId)
+ ->groupBy('tags.id')
+ ->orderBy('postCount DESC, name ASC');
- $arrayEntities = array_filter(
- iterator_to_array($query),
- function($arrayEntity) use ($tagName)
- {
- return strcasecmp($arrayEntity['name'], $tagName) !== 0;
- });
+ $arrayEntities = array_filter(
+ iterator_to_array($query),
+ function($arrayEntity) use ($tagName)
+ {
+ return strcasecmp($arrayEntity['name'], $tagName) !== 0;
+ });
- return $this->arrayToEntities($arrayEntities);
- }
+ return $this->arrayToEntities($arrayEntities);
+ }
- public function export()
- {
- $exported = [];
- foreach ($this->pdo->from($this->tableName) as $arrayEntity)
- {
- $exported[$arrayEntity['id']] = [
- 'name' => $arrayEntity['name'],
- 'usages' => intval($arrayEntity['usages']),
- 'banned' => boolval($arrayEntity['banned'])
- ];
- }
+ public function export()
+ {
+ $exported = [];
+ foreach ($this->pdo->from($this->tableName) as $arrayEntity)
+ {
+ $exported[$arrayEntity['id']] = [
+ 'name' => $arrayEntity['name'],
+ 'usages' => intval($arrayEntity['usages']),
+ 'banned' => boolval($arrayEntity['banned'])
+ ];
+ }
- //upgrades on old databases
- try
- {
- $relations = iterator_to_array($this->pdo->from('tagRelations'));
- }
- catch (\Exception $e)
- {
- $relations = [];
- }
+ //upgrades on old databases
+ try
+ {
+ $relations = iterator_to_array($this->pdo->from('tagRelations'));
+ }
+ catch (\Exception $e)
+ {
+ $relations = [];
+ }
- foreach ($relations as $arrayEntity)
- {
- $key1 = $arrayEntity['tag1id'];
- $key2 = $arrayEntity['tag2id'];
- $type = intval($arrayEntity['type']);
- if ($type === self::TAG_RELATION_IMPLICATION)
- $target = 'implications';
- elseif ($type === self::TAG_RELATION_SUGGESTION)
- $target = 'suggestions';
- else
- continue;
+ foreach ($relations as $arrayEntity)
+ {
+ $key1 = $arrayEntity['tag1id'];
+ $key2 = $arrayEntity['tag2id'];
+ $type = intval($arrayEntity['type']);
+ if ($type === self::TAG_RELATION_IMPLICATION)
+ $target = 'implications';
+ elseif ($type === self::TAG_RELATION_SUGGESTION)
+ $target = 'suggestions';
+ else
+ continue;
- if (!isset($exported[$key1]) || !isset($exported[$key2]))
- continue;
+ if (!isset($exported[$key1]) || !isset($exported[$key2]))
+ continue;
- if (!isset($exported[$key1][$target]))
- $exported[$key1][$target] = [];
+ if (!isset($exported[$key1][$target]))
+ $exported[$key1][$target] = [];
- $exported[$key1][$target][] = $exported[$key2]['name'];
- }
+ $exported[$key1][$target][] = $exported[$key2]['name'];
+ }
- return array_values($exported);
- }
+ return array_values($exported);
+ }
- protected function afterLoad(Entity $tag)
- {
- $tag->setLazyLoader(
- Tag::LAZY_LOADER_IMPLIED_TAGS,
- function (Tag $tag)
- {
- return $this->findImpliedTags($tag);
- });
+ protected function afterLoad(Entity $tag)
+ {
+ $tag->setLazyLoader(
+ Tag::LAZY_LOADER_IMPLIED_TAGS,
+ function (Tag $tag)
+ {
+ return $this->findImpliedTags($tag);
+ });
- $tag->setLazyLoader(
- Tag::LAZY_LOADER_SUGGESTED_TAGS,
- function (Tag $tag)
- {
- return $this->findSuggested($tag);
- });
- }
+ $tag->setLazyLoader(
+ Tag::LAZY_LOADER_SUGGESTED_TAGS,
+ function (Tag $tag)
+ {
+ return $this->findSuggested($tag);
+ });
+ }
- protected function afterSave(Entity $tag)
- {
- $this->syncImpliedTags($tag);
- $this->syncSuggestedTags($tag);
- }
+ protected function afterSave(Entity $tag)
+ {
+ $this->syncImpliedTags($tag);
+ $this->syncSuggestedTags($tag);
+ }
- protected function decorateQueryFromRequirement($query, Requirement $requirement)
- {
- if ($requirement->getType() === TagFilter::REQUIREMENT_PARTIAL_TAG_NAME)
- {
- $sql = 'INSTR(LOWER(tags.name), LOWER(?)) > 0';
+ protected function decorateQueryFromRequirement($query, Requirement $requirement)
+ {
+ if ($requirement->getType() === TagFilter::REQUIREMENT_PARTIAL_TAG_NAME)
+ {
+ $sql = 'INSTR(LOWER(tags.name), LOWER(?)) > 0';
- if ($requirement->isNegated())
- $sql = 'NOT ' . $sql;
+ if ($requirement->isNegated())
+ $sql = 'NOT ' . $sql;
- $query->where($sql, $requirement->getValue()->getValue());
- return;
- }
+ $query->where($sql, $requirement->getValue()->getValue());
+ return;
+ }
- elseif ($requirement->getType() === TagFilter::REQUIREMENT_CATEGORY)
- {
- $sql = 'IFNULL(category, \'default\')';
- $requirement->setType($sql);
- return parent::decorateQueryFromRequirement($query, $requirement);
- }
+ elseif ($requirement->getType() === TagFilter::REQUIREMENT_CATEGORY)
+ {
+ $sql = 'IFNULL(category, \'default\')';
+ $requirement->setType($sql);
+ return parent::decorateQueryFromRequirement($query, $requirement);
+ }
- parent::decorateQueryFromRequirement($query, $requirement);
- }
+ parent::decorateQueryFromRequirement($query, $requirement);
+ }
- private function findImpliedTags(Tag $tag)
- {
- return $this->findRelatedTagsByType($tag, self::TAG_RELATION_IMPLICATION);
- }
+ private function findImpliedTags(Tag $tag)
+ {
+ return $this->findRelatedTagsByType($tag, self::TAG_RELATION_IMPLICATION);
+ }
- private function findSuggested(Tag $tag)
- {
- return $this->findRelatedTagsByType($tag, self::TAG_RELATION_SUGGESTION);
- }
+ private function findSuggested(Tag $tag)
+ {
+ return $this->findRelatedTagsByType($tag, self::TAG_RELATION_SUGGESTION);
+ }
- private function syncImpliedTags($tag)
- {
- $this->syncRelatedTagsByType($tag, $tag->getImpliedTags(), self::TAG_RELATION_IMPLICATION);
- }
+ private function syncImpliedTags($tag)
+ {
+ $this->syncRelatedTagsByType($tag, $tag->getImpliedTags(), self::TAG_RELATION_IMPLICATION);
+ }
- private function syncSuggestedTags($tag)
- {
- $this->syncRelatedTagsByType($tag, $tag->getSuggestedTags(), self::TAG_RELATION_SUGGESTION);
- }
+ private function syncSuggestedTags($tag)
+ {
+ $this->syncRelatedTagsByType($tag, $tag->getSuggestedTags(), self::TAG_RELATION_SUGGESTION);
+ }
- private function syncRelatedTagsByType(Tag $tag, array $relatedTags, $type)
- {
- $relatedTagIds = array_filter(array_unique(array_map(
- function ($tag)
- {
- if (!$tag->getId())
- throw new \RuntimeException('Unsaved entities found');
- return $tag->getId();
- },
- $relatedTags)));
+ private function syncRelatedTagsByType(Tag $tag, array $relatedTags, $type)
+ {
+ $relatedTagIds = array_filter(array_unique(array_map(
+ function ($tag)
+ {
+ if (!$tag->getId())
+ throw new \RuntimeException('Unsaved entities found');
+ return $tag->getId();
+ },
+ $relatedTags)));
- $this->pdo->deleteFrom('tagRelations')
- ->where('tag1id', $tag->getId())
- ->where('type', $type)
- ->execute();
+ $this->pdo->deleteFrom('tagRelations')
+ ->where('tag1id', $tag->getId())
+ ->where('type', $type)
+ ->execute();
- foreach ($relatedTagIds as $tagId)
- {
- $this->pdo
- ->insertInto('tagRelations')
- ->values([
- 'tag1id' => $tag->getId(),
- 'tag2id' => $tagId,
- 'type' => $type])
- ->execute();
- }
- }
+ foreach ($relatedTagIds as $tagId)
+ {
+ $this->pdo
+ ->insertInto('tagRelations')
+ ->values([
+ 'tag1id' => $tag->getId(),
+ 'tag2id' => $tagId,
+ 'type' => $type])
+ ->execute();
+ }
+ }
- private function findRelatedTagsByType(Tag $tag, $type)
- {
- $tagId = $tag->getId();
- $query = $this->pdo->from($this->tableName)
- ->innerJoin('tagRelations tr', 'tags.id = tr.tag2id')
- ->where('tr.type', $type)
- ->where('tr.tag1id', $tagId);
- $arrayEntities = iterator_to_array($query);
- return $this->arrayToEntities($arrayEntities);
- }
+ private function findRelatedTagsByType(Tag $tag, $type)
+ {
+ $tagId = $tag->getId();
+ $query = $this->pdo->from($this->tableName)
+ ->innerJoin('tagRelations tr', 'tags.id = tr.tag2id')
+ ->where('tr.type', $type)
+ ->where('tr.tag1id', $tagId);
+ $arrayEntities = iterator_to_array($query);
+ return $this->arrayToEntities($arrayEntities);
+ }
}
diff --git a/src/Dao/TokenDao.php b/src/Dao/TokenDao.php
index 07130d8c..40525bf2 100644
--- a/src/Dao/TokenDao.php
+++ b/src/Dao/TokenDao.php
@@ -5,39 +5,39 @@ use Szurubooru\DatabaseConnection;
class TokenDao extends AbstractDao
{
- public function __construct(DatabaseConnection $databaseConnection)
- {
- parent::__construct(
- $databaseConnection,
- 'tokens',
- new TokenEntityConverter());
- }
+ public function __construct(DatabaseConnection $databaseConnection)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'tokens',
+ new TokenEntityConverter());
+ }
- public function findByName($tokenName)
- {
- return $this->findOneBy('name', $tokenName);
- }
+ public function findByName($tokenName)
+ {
+ return $this->findOneBy('name', $tokenName);
+ }
- public function findByAdditionalDataAndPurpose($additionalData, $purpose)
- {
- $query = $this->pdo->from($this->tableName)
- ->where('additionalData', $additionalData)
- ->where('purpose', $purpose);
- $arrayEntities = iterator_to_array($query);
- $entities = $this->arrayToEntities($arrayEntities);
- if (!$entities || !count($entities))
- return null;
- $entity = array_shift($entities);
- return $entity;
- }
+ public function findByAdditionalDataAndPurpose($additionalData, $purpose)
+ {
+ $query = $this->pdo->from($this->tableName)
+ ->where('additionalData', $additionalData)
+ ->where('purpose', $purpose);
+ $arrayEntities = iterator_to_array($query);
+ $entities = $this->arrayToEntities($arrayEntities);
+ if (!$entities || !count($entities))
+ return null;
+ $entity = array_shift($entities);
+ return $entity;
+ }
- public function deleteByName($tokenName)
- {
- return $this->deleteBy('name', $tokenName);
- }
+ public function deleteByName($tokenName)
+ {
+ return $this->deleteBy('name', $tokenName);
+ }
- public function deleteByAdditionalData($additionalData)
- {
- return $this->deleteBy('additionalData', $additionalData);
- }
+ public function deleteByAdditionalData($additionalData)
+ {
+ return $this->deleteBy('additionalData', $additionalData);
+ }
}
diff --git a/src/Dao/TransactionManager.php b/src/Dao/TransactionManager.php
index 1701f967..82799d32 100644
--- a/src/Dao/TransactionManager.php
+++ b/src/Dao/TransactionManager.php
@@ -4,40 +4,40 @@ use Szurubooru\DatabaseConnection;
class TransactionManager
{
- private $databaseConnection;
+ private $databaseConnection;
- public function __construct(DatabaseConnection $databaseConnection)
- {
- $this->databaseConnection = $databaseConnection;
- }
+ public function __construct(DatabaseConnection $databaseConnection)
+ {
+ $this->databaseConnection = $databaseConnection;
+ }
- public function commit($callback)
- {
- return $this->doInTransaction($callback, 'commit');
- }
+ public function commit($callback)
+ {
+ return $this->doInTransaction($callback, 'commit');
+ }
- public function rollback($callback)
- {
- return $this->doInTransaction($callback, 'rollBack');
- }
+ public function rollback($callback)
+ {
+ return $this->doInTransaction($callback, 'rollBack');
+ }
- public function doInTransaction($callback, $operation)
- {
- $pdo = $this->databaseConnection->getPDO();
- if ($pdo->inTransaction())
- return $callback();
+ public function doInTransaction($callback, $operation)
+ {
+ $pdo = $this->databaseConnection->getPDO();
+ if ($pdo->inTransaction())
+ return $callback();
- $pdo->beginTransaction();
- try
- {
- $ret = $callback();
- $pdo->$operation();
- return $ret;
- }
- catch (\Exception $e)
- {
- $pdo->rollBack();
- throw $e;
- }
- }
+ $pdo->beginTransaction();
+ try
+ {
+ $ret = $callback();
+ $pdo->$operation();
+ return $ret;
+ }
+ catch (\Exception $e)
+ {
+ $pdo->rollBack();
+ throw $e;
+ }
+ }
}
diff --git a/src/Dao/UserDao.php b/src/Dao/UserDao.php
index e5bd78b3..7313c386 100644
--- a/src/Dao/UserDao.php
+++ b/src/Dao/UserDao.php
@@ -9,78 +9,78 @@ use Szurubooru\Services\ThumbnailService;
class UserDao extends AbstractDao implements ICrudDao
{
- const ORDER_NAME = 'name';
- const ORDER_REGISTRATION_TIME = 'registrationTime';
+ const ORDER_NAME = 'name';
+ const ORDER_REGISTRATION_TIME = 'registrationTime';
- private $fileDao;
- private $thumbnailService;
+ private $fileDao;
+ private $thumbnailService;
- public function __construct(
- DatabaseConnection $databaseConnection,
- PublicFileDao $fileDao,
- ThumbnailService $thumbnailService)
- {
- parent::__construct(
- $databaseConnection,
- 'users',
- new UserEntityConverter());
+ public function __construct(
+ DatabaseConnection $databaseConnection,
+ PublicFileDao $fileDao,
+ ThumbnailService $thumbnailService)
+ {
+ parent::__construct(
+ $databaseConnection,
+ 'users',
+ new UserEntityConverter());
- $this->fileDao = $fileDao;
- $this->thumbnailService = $thumbnailService;
- }
+ $this->fileDao = $fileDao;
+ $this->thumbnailService = $thumbnailService;
+ }
- public function findByName($userName)
- {
- return $this->findOneBy('name', $userName);
- }
+ public function findByName($userName)
+ {
+ return $this->findOneBy('name', $userName);
+ }
- public function findByEmail($userEmail, $allowUnconfirmed = false)
- {
- $result = $this->findOneBy('email', $userEmail);
- if (!$result && $allowUnconfirmed)
- {
- $result = $this->findOneBy('emailUnconfirmed', $userEmail);
- }
- return $result;
- }
+ public function findByEmail($userEmail, $allowUnconfirmed = false)
+ {
+ $result = $this->findOneBy('email', $userEmail);
+ if (!$result && $allowUnconfirmed)
+ {
+ $result = $this->findOneBy('emailUnconfirmed', $userEmail);
+ }
+ return $result;
+ }
- public function hasAnyUsers()
- {
- return $this->hasAnyRecords();
- }
+ public function hasAnyUsers()
+ {
+ return $this->hasAnyRecords();
+ }
- public function deleteByName($userName)
- {
- $this->deleteBy('name', $userName);
- $this->pdo->deleteFrom('tokens')->where('additionalData', $userName);
- }
+ public function deleteByName($userName)
+ {
+ $this->deleteBy('name', $userName);
+ $this->pdo->deleteFrom('tokens')->where('additionalData', $userName);
+ }
- protected function afterLoad(Entity $user)
- {
- $user->setLazyLoader(
- User::LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT,
- function(User $user)
- {
- $avatarSource = $user->getCustomAvatarSourceContentPath();
- return $this->fileDao->load($avatarSource);
- });
- }
+ protected function afterLoad(Entity $user)
+ {
+ $user->setLazyLoader(
+ User::LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT,
+ function(User $user)
+ {
+ $avatarSource = $user->getCustomAvatarSourceContentPath();
+ return $this->fileDao->load($avatarSource);
+ });
+ }
- protected function afterSave(Entity $user)
- {
- $targetPath = $user->getCustomAvatarSourceContentPath();
- $content = $user->getCustomAvatarSourceContent();
- if ($content)
- $this->fileDao->save($targetPath, $content);
- else
- $this->fileDao->delete($targetPath);
- $this->thumbnailService->deleteUsedThumbnails($targetPath);
- }
+ protected function afterSave(Entity $user)
+ {
+ $targetPath = $user->getCustomAvatarSourceContentPath();
+ $content = $user->getCustomAvatarSourceContent();
+ if ($content)
+ $this->fileDao->save($targetPath, $content);
+ else
+ $this->fileDao->delete($targetPath);
+ $this->thumbnailService->deleteUsedThumbnails($targetPath);
+ }
- protected function afterDelete(Entity $user)
- {
- $avatarSource = $user->getCustomAvatarSourceContentPath();
- $this->fileDao->delete($avatarSource);
- $this->thumbnailService->deleteUsedThumbnails($avatarSource);
- }
+ protected function afterDelete(Entity $user)
+ {
+ $avatarSource = $user->getCustomAvatarSourceContentPath();
+ $this->fileDao->delete($avatarSource);
+ $this->thumbnailService->deleteUsedThumbnails($avatarSource);
+ }
}
diff --git a/src/DatabaseConnection.php b/src/DatabaseConnection.php
index 2f84e57b..d45514fb 100644
--- a/src/DatabaseConnection.php
+++ b/src/DatabaseConnection.php
@@ -5,45 +5,45 @@ use Szurubooru\PDOEx\PDOEx;
class DatabaseConnection
{
- private $pdo;
- private $config;
+ private $pdo;
+ private $config;
- public function __construct(Config $config)
- {
- $this->config = $config;
- }
+ public function __construct(Config $config)
+ {
+ $this->config = $config;
+ }
- public function getPDO()
- {
- if (!$this->pdo)
- {
- $this->createPDO();
- }
- return $this->pdo;
- }
+ public function getPDO()
+ {
+ if (!$this->pdo)
+ {
+ $this->createPDO();
+ }
+ return $this->pdo;
+ }
- public function getDriver()
- {
- return $this->getPDO()->getAttribute(\PDO::ATTR_DRIVER_NAME);
- }
+ public function getDriver()
+ {
+ return $this->getPDO()->getAttribute(\PDO::ATTR_DRIVER_NAME);
+ }
- public function close()
- {
- $this->pdo = null;
- }
+ public function close()
+ {
+ $this->pdo = null;
+ }
- private function createPDO()
- {
- $cwd = getcwd();
- if ($this->config->getDataDirectory())
- chdir($this->config->getDataDirectory());
+ private function createPDO()
+ {
+ $cwd = getcwd();
+ if ($this->config->getDataDirectory())
+ chdir($this->config->getDataDirectory());
- $this->pdo = new PDOEx(
- $this->config->database->dsn,
- $this->config->database->user,
- $this->config->database->password);
+ $this->pdo = new PDOEx(
+ $this->config->database->dsn,
+ $this->config->database->user,
+ $this->config->database->password);
- $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
- chdir($cwd);
- }
+ $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
+ chdir($cwd);
+ }
}
diff --git a/src/Dispatcher.php b/src/Dispatcher.php
index fb70a1ef..1b374d8e 100644
--- a/src/Dispatcher.php
+++ b/src/Dispatcher.php
@@ -10,78 +10,78 @@ use Szurubooru\Services\TokenService;
final class Dispatcher
{
- private $router;
- private $config;
- private $databaseConnection;
- private $authService;
- private $tokenService;
+ private $router;
+ private $config;
+ private $databaseConnection;
+ private $authService;
+ private $tokenService;
- public function __construct(
- Router $router,
- Config $config,
- DatabaseConnection $databaseConnection,
- HttpHelper $httpHelper,
- AuthService $authService,
- TokenService $tokenService,
- RouteRepository $routeRepository)
- {
- $this->router = $router;
- $this->config = $config;
- $this->databaseConnection = $databaseConnection;
- $this->httpHelper = $httpHelper;
- $this->authService = $authService;
- $this->tokenService = $tokenService;
+ public function __construct(
+ Router $router,
+ Config $config,
+ DatabaseConnection $databaseConnection,
+ HttpHelper $httpHelper,
+ AuthService $authService,
+ TokenService $tokenService,
+ RouteRepository $routeRepository)
+ {
+ $this->router = $router;
+ $this->config = $config;
+ $this->databaseConnection = $databaseConnection;
+ $this->httpHelper = $httpHelper;
+ $this->authService = $authService;
+ $this->tokenService = $tokenService;
- //if script fails prematurely, mark it as fail from advance
- $this->httpHelper->setResponseCode(500);
+ //if script fails prematurely, mark it as fail from advance
+ $this->httpHelper->setResponseCode(500);
- $routeRepository->injectRoutes($router);
- }
+ $routeRepository->injectRoutes($router);
+ }
- public function run($requestMethod, $requestUri)
- {
- try
- {
- $code = 200;
- $this->authorizeFromRequestHeader();
- $json = (array) $this->router->handle($requestMethod, $requestUri);
- }
- catch (\Exception $e)
- {
- $code = 400;
- $trace = $e->getTrace();
- foreach ($trace as &$item)
- unset($item['args']);
- $json = [
- 'error' => $e->getMessage(),
- 'trace' => $trace,
- ];
- }
- $end = microtime(true);
- $json['__time'] = $end - Bootstrap::getStartTime();
- if ($this->config->misc->dumpSqlIntoQueries)
- {
- $json['__queries'] = $this->databaseConnection->getPDO()->getQueryCount();
- $json['__statements'] = $this->databaseConnection->getPDO()->getStatements();
- }
+ public function run($requestMethod, $requestUri)
+ {
+ try
+ {
+ $code = 200;
+ $this->authorizeFromRequestHeader();
+ $json = (array) $this->router->handle($requestMethod, $requestUri);
+ }
+ catch (\Exception $e)
+ {
+ $code = 400;
+ $trace = $e->getTrace();
+ foreach ($trace as &$item)
+ unset($item['args']);
+ $json = [
+ 'error' => $e->getMessage(),
+ 'trace' => $trace,
+ ];
+ }
+ $end = microtime(true);
+ $json['__time'] = $end - Bootstrap::getStartTime();
+ if ($this->config->misc->dumpSqlIntoQueries)
+ {
+ $json['__queries'] = $this->databaseConnection->getPDO()->getQueryCount();
+ $json['__statements'] = $this->databaseConnection->getPDO()->getStatements();
+ }
- if (!$this->httpHelper->isRedirecting())
- {
- $this->httpHelper->setResponseCode($code);
- $this->httpHelper->setHeader('Content-Type', 'application/json');
- $this->httpHelper->outputJSON($json);
- }
+ if (!$this->httpHelper->isRedirecting())
+ {
+ $this->httpHelper->setResponseCode($code);
+ $this->httpHelper->setHeader('Content-Type', 'application/json');
+ $this->httpHelper->outputJSON($json);
+ }
- return $json;
- }
+ return $json;
+ }
- private function authorizeFromRequestHeader()
- {
- $loginTokenName = $this->httpHelper->getRequestHeader('X-Authorization-Token');
- if ($loginTokenName)
- {
- $token = $this->tokenService->getByName($loginTokenName);
- $this->authService->loginFromToken($token);
- }
- }
+ private function authorizeFromRequestHeader()
+ {
+ $loginTokenName = $this->httpHelper->getRequestHeader('X-Authorization-Token');
+ if ($loginTokenName)
+ {
+ $token = $this->tokenService->getByName($loginTokenName);
+ $this->authService->loginFromToken($token);
+ }
+ }
}
diff --git a/src/Entities/Comment.php b/src/Entities/Comment.php
index 153026c9..ed75ff9a 100644
--- a/src/Entities/Comment.php
+++ b/src/Entities/Comment.php
@@ -5,91 +5,91 @@ use Szurubooru\Entities\User;
final class Comment extends Entity
{
- private $postId;
- private $userId;
- private $creationTime;
- private $lastEditTime;
- private $text;
+ private $postId;
+ private $userId;
+ private $creationTime;
+ private $lastEditTime;
+ private $text;
- const LAZY_LOADER_USER = 'user';
- const LAZY_LOADER_POST = 'post';
+ const LAZY_LOADER_USER = 'user';
+ const LAZY_LOADER_POST = 'post';
- const META_SCORE = 'score';
+ const META_SCORE = 'score';
- public function getUserId()
- {
- return $this->userId;
- }
+ public function getUserId()
+ {
+ return $this->userId;
+ }
- public function setUserId($userId)
- {
- $this->userId = $userId;
- }
+ public function setUserId($userId)
+ {
+ $this->userId = $userId;
+ }
- public function getPostId()
- {
- return $this->postId;
- }
+ public function getPostId()
+ {
+ return $this->postId;
+ }
- public function setPostId($postId)
- {
- $this->postId = $postId;
- }
+ public function setPostId($postId)
+ {
+ $this->postId = $postId;
+ }
- public function getCreationTime()
- {
- return $this->creationTime;
- }
+ public function getCreationTime()
+ {
+ return $this->creationTime;
+ }
- public function setCreationTime($creationTime)
- {
- $this->creationTime = $creationTime;
- }
+ public function setCreationTime($creationTime)
+ {
+ $this->creationTime = $creationTime;
+ }
- public function getLastEditTime()
- {
- return $this->lastEditTime;
- }
+ public function getLastEditTime()
+ {
+ return $this->lastEditTime;
+ }
- public function setLastEditTime($lastEditTime)
- {
- $this->lastEditTime = $lastEditTime;
- }
+ public function setLastEditTime($lastEditTime)
+ {
+ $this->lastEditTime = $lastEditTime;
+ }
- public function getText()
- {
- return $this->text;
- }
+ public function getText()
+ {
+ return $this->text;
+ }
- public function setText($text)
- {
- $this->text = $text;
- }
+ public function setText($text)
+ {
+ $this->text = $text;
+ }
- public function getUser()
- {
- return $this->lazyLoad(self::LAZY_LOADER_USER, null);
- }
+ public function getUser()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_USER, null);
+ }
- public function setUser(User $user = null)
- {
- $this->lazySave(self::LAZY_LOADER_USER, $user);
- $this->userId = $user ? $user->getId() : null;
- }
+ public function setUser(User $user = null)
+ {
+ $this->lazySave(self::LAZY_LOADER_USER, $user);
+ $this->userId = $user ? $user->getId() : null;
+ }
- public function getPost()
- {
- return $this->lazyLoad(self::LAZY_LOADER_POST, null);
- }
+ public function getPost()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_POST, null);
+ }
- public function setPost(Post $post)
- {
- $this->lazySave(self::LAZY_LOADER_POST, $post);
- $this->postId = $post->getId();
- }
+ public function setPost(Post $post)
+ {
+ $this->lazySave(self::LAZY_LOADER_POST, $post);
+ $this->postId = $post->getId();
+ }
- public function getScore()
- {
- return $this->getMeta(self::META_SCORE, 0);
- }
+ public function getScore()
+ {
+ return $this->getMeta(self::META_SCORE, 0);
+ }
}
diff --git a/src/Entities/Entity.php b/src/Entities/Entity.php
index 5d6116f9..44836504 100644
--- a/src/Entities/Entity.php
+++ b/src/Entities/Entity.php
@@ -3,74 +3,74 @@ namespace Szurubooru\Entities;
abstract class Entity
{
- protected $id = null;
- private $lazyLoaders = [];
- private $lazyContainers = [];
- private $meta;
+ protected $id = null;
+ private $lazyLoaders = [];
+ private $lazyContainers = [];
+ private $meta;
- public function __construct($id = null)
- {
- $this->id = $id === null ? null : intval($id);
- }
+ public function __construct($id = null)
+ {
+ $this->id = $id === null ? null : intval($id);
+ }
- public function getId()
- {
- return $this->id;
- }
+ public function getId()
+ {
+ return $this->id;
+ }
- public function setId($id)
- {
- $this->id = $id;
- }
+ public function setId($id)
+ {
+ $this->id = $id;
+ }
- public function getMeta($metaName, $default = null)
- {
- if (!isset($this->meta[$metaName]))
- return $default;
- return $this->meta[$metaName];
- }
+ public function getMeta($metaName, $default = null)
+ {
+ if (!isset($this->meta[$metaName]))
+ return $default;
+ return $this->meta[$metaName];
+ }
- public function setMeta($metaName, $value)
- {
- $this->meta[$metaName] = $value;
- }
+ public function setMeta($metaName, $value)
+ {
+ $this->meta[$metaName] = $value;
+ }
- public function resetMeta()
- {
- $this->meta = [];
- }
+ public function resetMeta()
+ {
+ $this->meta = [];
+ }
- public function resetLazyLoaders()
- {
- $this->lazyLoaders = [];
- $this->lazyContainers = [];
- }
+ public function resetLazyLoaders()
+ {
+ $this->lazyLoaders = [];
+ $this->lazyContainers = [];
+ }
- public function setLazyLoader($lazyContainerName, $getter)
- {
- $this->lazyLoaders[$lazyContainerName] = $getter;
- }
+ public function setLazyLoader($lazyContainerName, $getter)
+ {
+ $this->lazyLoaders[$lazyContainerName] = $getter;
+ }
- protected function lazyLoad($lazyContainerName, $defaultValue)
- {
- if (!isset($this->lazyContainers[$lazyContainerName]))
- {
- if (!isset($this->lazyLoaders[$lazyContainerName]))
- {
- return $defaultValue;
- }
- $result = $this->lazyLoaders[$lazyContainerName]($this);
- $this->lazySave($lazyContainerName, $result);
- }
- else
- {
- $result = $this->lazyContainers[$lazyContainerName];
- }
- return $result;
- }
+ protected function lazyLoad($lazyContainerName, $defaultValue)
+ {
+ if (!isset($this->lazyContainers[$lazyContainerName]))
+ {
+ if (!isset($this->lazyLoaders[$lazyContainerName]))
+ {
+ return $defaultValue;
+ }
+ $result = $this->lazyLoaders[$lazyContainerName]($this);
+ $this->lazySave($lazyContainerName, $result);
+ }
+ else
+ {
+ $result = $this->lazyContainers[$lazyContainerName];
+ }
+ return $result;
+ }
- protected function lazySave($lazyContainerName, $value)
- {
- $this->lazyContainers[$lazyContainerName] = $value;
- }
+ protected function lazySave($lazyContainerName, $value)
+ {
+ $this->lazyContainers[$lazyContainerName] = $value;
+ }
}
diff --git a/src/Entities/Favorite.php b/src/Entities/Favorite.php
index 8eb05734..9db14411 100644
--- a/src/Entities/Favorite.php
+++ b/src/Entities/Favorite.php
@@ -5,62 +5,62 @@ use Szurubooru\Entities\User;
final class Favorite extends Entity
{
- private $postId;
- private $userId;
- private $time;
+ private $postId;
+ private $userId;
+ private $time;
- const LAZY_LOADER_USER = 'user';
- const LAZY_LOADER_POST = 'post';
+ const LAZY_LOADER_USER = 'user';
+ const LAZY_LOADER_POST = 'post';
- public function getUserId()
- {
- return $this->userId;
- }
+ public function getUserId()
+ {
+ return $this->userId;
+ }
- public function setUserId($userId)
- {
- $this->userId = $userId;
- }
+ public function setUserId($userId)
+ {
+ $this->userId = $userId;
+ }
- public function getPostId()
- {
- return $this->postId;
- }
+ public function getPostId()
+ {
+ return $this->postId;
+ }
- public function setPostId($postId)
- {
- $this->postId = $postId;
- }
+ public function setPostId($postId)
+ {
+ $this->postId = $postId;
+ }
- public function getTime()
- {
- return $this->time;
- }
+ public function getTime()
+ {
+ return $this->time;
+ }
- public function setTime($time)
- {
- $this->time = $time;
- }
+ public function setTime($time)
+ {
+ $this->time = $time;
+ }
- public function getUser()
- {
- return $this->lazyLoad(self::LAZY_LOADER_USER, null);
- }
+ public function getUser()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_USER, null);
+ }
- public function setUser(User $user)
- {
- $this->lazySave(self::LAZY_LOADER_USER, $user);
- $this->userId = $user->getId();
- }
+ public function setUser(User $user)
+ {
+ $this->lazySave(self::LAZY_LOADER_USER, $user);
+ $this->userId = $user->getId();
+ }
- public function getPost()
- {
- return $this->lazyLoad(self::LAZY_LOADER_POST, null);
- }
+ public function getPost()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_POST, null);
+ }
- public function setPost(Post $post)
- {
- $this->lazySave(self::LAZY_LOADER_POST, $post);
- $this->postId = $post->getId();
- }
+ public function setPost(Post $post)
+ {
+ $this->lazySave(self::LAZY_LOADER_POST, $post);
+ $this->postId = $post->getId();
+ }
}
diff --git a/src/Entities/GlobalParam.php b/src/Entities/GlobalParam.php
index 3ad4eacd..0def0657 100644
--- a/src/Entities/GlobalParam.php
+++ b/src/Entities/GlobalParam.php
@@ -3,31 +3,31 @@ namespace Szurubooru\Entities;
final class GlobalParam extends Entity
{
- const KEY_FEATURED_POST_USER = 'featuredPostUser';
- const KEY_FEATURED_POST = 'featuredPost';
- const KEY_POST_SIZE = 'postSize';
- const KEY_POST_COUNT = 'postCount';
+ const KEY_FEATURED_POST_USER = 'featuredPostUser';
+ const KEY_FEATURED_POST = 'featuredPost';
+ const KEY_POST_SIZE = 'postSize';
+ const KEY_POST_COUNT = 'postCount';
- private $key;
- private $value;
+ private $key;
+ private $value;
- public function getKey()
- {
- return $this->key;
- }
+ public function getKey()
+ {
+ return $this->key;
+ }
- public function setKey($key)
- {
- $this->key = $key;
- }
+ public function setKey($key)
+ {
+ $this->key = $key;
+ }
- public function getValue()
- {
- return $this->value;
- }
+ public function getValue()
+ {
+ return $this->value;
+ }
- public function setValue($value)
- {
- $this->value = $value;
- }
+ public function setValue($value)
+ {
+ $this->value = $value;
+ }
}
diff --git a/src/Entities/Post.php b/src/Entities/Post.php
index b54d2bd1..a8d0cad5 100644
--- a/src/Entities/Post.php
+++ b/src/Entities/Post.php
@@ -4,290 +4,290 @@ use Szurubooru\Entities\User;
final class Post extends Entity
{
- const POST_SAFETY_SAFE = 1;
- const POST_SAFETY_SKETCHY = 2;
- const POST_SAFETY_UNSAFE = 3;
+ const POST_SAFETY_SAFE = 1;
+ const POST_SAFETY_SKETCHY = 2;
+ const POST_SAFETY_UNSAFE = 3;
- const POST_TYPE_IMAGE = 1;
- const POST_TYPE_FLASH = 2;
- const POST_TYPE_VIDEO = 3;
- const POST_TYPE_YOUTUBE = 4;
- const POST_TYPE_ANIMATED_IMAGE = 5;
+ const POST_TYPE_IMAGE = 1;
+ const POST_TYPE_FLASH = 2;
+ const POST_TYPE_VIDEO = 3;
+ const POST_TYPE_YOUTUBE = 4;
+ const POST_TYPE_ANIMATED_IMAGE = 5;
- const FLAG_LOOP = 1;
+ const FLAG_LOOP = 1;
- const LAZY_LOADER_USER = 'user';
- const LAZY_LOADER_TAGS = 'tags';
- const LAZY_LOADER_CONTENT = 'content';
- const LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT = 'thumbnailSourceContent';
- const LAZY_LOADER_RELATED_POSTS = 'relatedPosts';
+ const LAZY_LOADER_USER = 'user';
+ const LAZY_LOADER_TAGS = 'tags';
+ const LAZY_LOADER_CONTENT = 'content';
+ const LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT = 'thumbnailSourceContent';
+ const LAZY_LOADER_RELATED_POSTS = 'relatedPosts';
- const META_TAG_COUNT = 'tagCount';
- const META_FAV_COUNT = 'favCount';
- const META_COMMENT_COUNT = 'commentCount';
- const META_SCORE = 'score';
+ const META_TAG_COUNT = 'tagCount';
+ const META_FAV_COUNT = 'favCount';
+ const META_COMMENT_COUNT = 'commentCount';
+ const META_SCORE = 'score';
- private $name;
- private $userId;
- private $uploadTime;
- private $lastEditTime;
- private $safety;
- private $contentType;
- private $contentChecksum;
- private $contentMimeType;
- private $source;
- private $imageWidth;
- private $imageHeight;
- private $originalFileSize;
- private $originalFileName;
- private $featureCount = 0;
- private $lastFeatureTime;
- private $flags = 0;
+ private $name;
+ private $userId;
+ private $uploadTime;
+ private $lastEditTime;
+ private $safety;
+ private $contentType;
+ private $contentChecksum;
+ private $contentMimeType;
+ private $source;
+ private $imageWidth;
+ private $imageHeight;
+ private $originalFileSize;
+ private $originalFileName;
+ private $featureCount = 0;
+ private $lastFeatureTime;
+ private $flags = 0;
- public function getIdMarkdown()
- {
- return '@' . $this->id;
- }
+ public function getIdMarkdown()
+ {
+ return '@' . $this->id;
+ }
- public function getName()
- {
- return $this->name;
- }
+ public function getName()
+ {
+ return $this->name;
+ }
- public function setName($name)
- {
- $this->name = $name;
- }
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
- public function getUserId()
- {
- return $this->userId;
- }
+ public function getUserId()
+ {
+ return $this->userId;
+ }
- public function setUserId($userId)
- {
- $this->userId = $userId;
- }
+ public function setUserId($userId)
+ {
+ $this->userId = $userId;
+ }
- public function getSafety()
- {
- return $this->safety;
- }
+ public function getSafety()
+ {
+ return $this->safety;
+ }
- public function setSafety($safety)
- {
- $this->safety = $safety;
- }
+ public function setSafety($safety)
+ {
+ $this->safety = $safety;
+ }
- public function getUploadTime()
- {
- return $this->uploadTime;
- }
+ public function getUploadTime()
+ {
+ return $this->uploadTime;
+ }
- public function setUploadTime($uploadTime)
- {
- $this->uploadTime = $uploadTime;
- }
+ public function setUploadTime($uploadTime)
+ {
+ $this->uploadTime = $uploadTime;
+ }
- public function getLastEditTime()
- {
- return $this->lastEditTime;
- }
+ public function getLastEditTime()
+ {
+ return $this->lastEditTime;
+ }
- public function setLastEditTime($lastEditTime)
- {
- $this->lastEditTime = $lastEditTime;
- }
+ public function setLastEditTime($lastEditTime)
+ {
+ $this->lastEditTime = $lastEditTime;
+ }
- public function getContentType()
- {
- return $this->contentType;
- }
+ public function getContentType()
+ {
+ return $this->contentType;
+ }
- public function setContentType($contentType)
- {
- $this->contentType = $contentType;
- }
+ public function setContentType($contentType)
+ {
+ $this->contentType = $contentType;
+ }
- public function getContentChecksum()
- {
- return $this->contentChecksum;
- }
+ public function getContentChecksum()
+ {
+ return $this->contentChecksum;
+ }
- public function setContentChecksum($contentChecksum)
- {
- $this->contentChecksum = $contentChecksum;
- }
+ public function setContentChecksum($contentChecksum)
+ {
+ $this->contentChecksum = $contentChecksum;
+ }
- public function getContentMimeType()
- {
- return $this->contentMimeType;
- }
+ public function getContentMimeType()
+ {
+ return $this->contentMimeType;
+ }
- public function setContentMimeType($contentMimeType)
- {
- $this->contentMimeType = $contentMimeType;
- }
+ public function setContentMimeType($contentMimeType)
+ {
+ $this->contentMimeType = $contentMimeType;
+ }
- public function getSource()
- {
- return $this->source;
- }
+ public function getSource()
+ {
+ return $this->source;
+ }
- public function setSource($source)
- {
- $this->source = $source;
- }
+ public function setSource($source)
+ {
+ $this->source = $source;
+ }
- public function getImageWidth()
- {
- return $this->imageWidth;
- }
+ public function getImageWidth()
+ {
+ return $this->imageWidth;
+ }
- public function setImageWidth($imageWidth)
- {
- $this->imageWidth = $imageWidth;
- }
+ public function setImageWidth($imageWidth)
+ {
+ $this->imageWidth = $imageWidth;
+ }
- public function getImageHeight()
- {
- return $this->imageHeight;
- }
+ public function getImageHeight()
+ {
+ return $this->imageHeight;
+ }
- public function setImageHeight($imageHeight)
- {
- $this->imageHeight = $imageHeight;
- }
+ public function setImageHeight($imageHeight)
+ {
+ $this->imageHeight = $imageHeight;
+ }
- public function getOriginalFileSize()
- {
- return $this->originalFileSize;
- }
+ public function getOriginalFileSize()
+ {
+ return $this->originalFileSize;
+ }
- public function setOriginalFileSize($originalFileSize)
- {
- $this->originalFileSize = $originalFileSize;
- }
+ public function setOriginalFileSize($originalFileSize)
+ {
+ $this->originalFileSize = $originalFileSize;
+ }
- public function getOriginalFileName()
- {
- return $this->originalFileName;
- }
+ public function getOriginalFileName()
+ {
+ return $this->originalFileName;
+ }
- public function setOriginalFileName($originalFileName)
- {
- $this->originalFileName = $originalFileName;
- }
+ public function setOriginalFileName($originalFileName)
+ {
+ $this->originalFileName = $originalFileName;
+ }
- public function getFeatureCount()
- {
- return $this->featureCount;
- }
+ public function getFeatureCount()
+ {
+ return $this->featureCount;
+ }
- public function setFeatureCount($featureCount)
- {
- $this->featureCount = $featureCount;
- }
+ public function setFeatureCount($featureCount)
+ {
+ $this->featureCount = $featureCount;
+ }
- public function getLastFeatureTime()
- {
- return $this->lastFeatureTime;
- }
+ public function getLastFeatureTime()
+ {
+ return $this->lastFeatureTime;
+ }
- public function setLastFeatureTime($lastFeatureTime)
- {
- $this->lastFeatureTime = $lastFeatureTime;
- }
+ public function setLastFeatureTime($lastFeatureTime)
+ {
+ $this->lastFeatureTime = $lastFeatureTime;
+ }
- public function getFlags()
- {
- return $this->flags;
- }
+ public function getFlags()
+ {
+ return $this->flags;
+ }
- public function setFlags($flags)
- {
- $this->flags = $flags;
- }
+ public function setFlags($flags)
+ {
+ $this->flags = $flags;
+ }
- public function getTags()
- {
- return $this->lazyLoad(self::LAZY_LOADER_TAGS, []);
- }
+ public function getTags()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_TAGS, []);
+ }
- public function setTags(array $tags)
- {
- $this->lazySave(self::LAZY_LOADER_TAGS, $tags);
- $this->setMeta(self::META_TAG_COUNT, count($tags));
- }
+ public function setTags(array $tags)
+ {
+ $this->lazySave(self::LAZY_LOADER_TAGS, $tags);
+ $this->setMeta(self::META_TAG_COUNT, count($tags));
+ }
- public function getRelatedPosts()
- {
- return $this->lazyLoad(self::LAZY_LOADER_RELATED_POSTS, []);
- }
+ public function getRelatedPosts()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_RELATED_POSTS, []);
+ }
- public function setRelatedPosts(array $relatedPosts)
- {
- $this->lazySave(self::LAZY_LOADER_RELATED_POSTS, $relatedPosts);
- }
+ public function setRelatedPosts(array $relatedPosts)
+ {
+ $this->lazySave(self::LAZY_LOADER_RELATED_POSTS, $relatedPosts);
+ }
- public function getUser()
- {
- return $this->lazyLoad(self::LAZY_LOADER_USER, null);
- }
+ public function getUser()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_USER, null);
+ }
- public function setUser(User $user = null)
- {
- $this->lazySave(self::LAZY_LOADER_USER, $user);
- $this->userId = $user ? $user->getId() : null;
- }
+ public function setUser(User $user = null)
+ {
+ $this->lazySave(self::LAZY_LOADER_USER, $user);
+ $this->userId = $user ? $user->getId() : null;
+ }
- public function getContent()
- {
- return $this->lazyLoad(self::LAZY_LOADER_CONTENT, null);
- }
+ public function getContent()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_CONTENT, null);
+ }
- public function setContent($content)
- {
- $this->lazySave(self::LAZY_LOADER_CONTENT, $content);
- }
+ public function setContent($content)
+ {
+ $this->lazySave(self::LAZY_LOADER_CONTENT, $content);
+ }
- public function getThumbnailSourceContent()
- {
- return $this->lazyLoad(self::LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT, null);
- }
+ public function getThumbnailSourceContent()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT, null);
+ }
- public function setThumbnailSourceContent($content)
- {
- $this->lazySave(self::LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT, $content);
- }
+ public function setThumbnailSourceContent($content)
+ {
+ $this->lazySave(self::LAZY_LOADER_THUMBNAIL_SOURCE_CONTENT, $content);
+ }
- public function getContentPath()
- {
- return 'posts' . DIRECTORY_SEPARATOR . $this->getName();
- }
+ public function getContentPath()
+ {
+ return 'posts' . DIRECTORY_SEPARATOR . $this->getName();
+ }
- public function getThumbnailSourceContentPath()
- {
- return 'posts' . DIRECTORY_SEPARATOR . $this->getName() . '-custom-thumb';
- }
+ public function getThumbnailSourceContentPath()
+ {
+ return 'posts' . DIRECTORY_SEPARATOR . $this->getName() . '-custom-thumb';
+ }
- public function getTagCount()
- {
- return $this->getMeta(self::META_TAG_COUNT, 0);
- }
+ public function getTagCount()
+ {
+ return $this->getMeta(self::META_TAG_COUNT, 0);
+ }
- public function getFavoriteCount()
- {
- return $this->getMeta(self::META_FAV_COUNT, 0);
- }
+ public function getFavoriteCount()
+ {
+ return $this->getMeta(self::META_FAV_COUNT, 0);
+ }
- public function getCommentCount()
- {
- return $this->getMeta(self::META_COMMENT_COUNT, 0);
- }
+ public function getCommentCount()
+ {
+ return $this->getMeta(self::META_COMMENT_COUNT, 0);
+ }
- public function getScore()
- {
- return $this->getMeta(self::META_SCORE, 0);
- }
+ public function getScore()
+ {
+ return $this->getMeta(self::META_SCORE, 0);
+ }
}
diff --git a/src/Entities/PostNote.php b/src/Entities/PostNote.php
index 2fa85bc6..7bc3436c 100644
--- a/src/Entities/PostNote.php
+++ b/src/Entities/PostNote.php
@@ -3,83 +3,83 @@ namespace Szurubooru\Entities;
final class PostNote extends Entity
{
- private $postId;
- private $left;
- private $top;
- private $width;
- private $height;
- private $text;
+ private $postId;
+ private $left;
+ private $top;
+ private $width;
+ private $height;
+ private $text;
- const LAZY_LOADER_POST = 'post';
+ const LAZY_LOADER_POST = 'post';
- public function getPostId()
- {
- return $this->postId;
- }
+ public function getPostId()
+ {
+ return $this->postId;
+ }
- public function setPostId($postId)
- {
- $this->postId = $postId;
- }
+ public function setPostId($postId)
+ {
+ $this->postId = $postId;
+ }
- public function getLeft()
- {
- return $this->left;
- }
+ public function getLeft()
+ {
+ return $this->left;
+ }
- public function setLeft($left)
- {
- $this->left = $left;
- }
+ public function setLeft($left)
+ {
+ $this->left = $left;
+ }
- public function getTop()
- {
- return $this->top;
- }
+ public function getTop()
+ {
+ return $this->top;
+ }
- public function setTop($top)
- {
- $this->top = $top;
- }
+ public function setTop($top)
+ {
+ $this->top = $top;
+ }
- public function getWidth()
- {
- return $this->width;
- }
+ public function getWidth()
+ {
+ return $this->width;
+ }
- public function setWidth($width)
- {
- $this->width = $width;
- }
+ public function setWidth($width)
+ {
+ $this->width = $width;
+ }
- public function getHeight()
- {
- return $this->height;
- }
+ public function getHeight()
+ {
+ return $this->height;
+ }
- public function setHeight($height)
- {
- $this->height = $height;
- }
+ public function setHeight($height)
+ {
+ $this->height = $height;
+ }
- public function getText()
- {
- return $this->text;
- }
+ public function getText()
+ {
+ return $this->text;
+ }
- public function setText($text)
- {
- $this->text = $text;
- }
+ public function setText($text)
+ {
+ $this->text = $text;
+ }
- public function getPost()
- {
- return $this->lazyLoad(self::LAZY_LOADER_POST, null);
- }
+ public function getPost()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_POST, null);
+ }
- public function setPost(Post $post)
- {
- $this->lazySave(self::LAZY_LOADER_POST, $post);
- $this->postId = $post->getId();
- }
+ public function setPost(Post $post)
+ {
+ $this->lazySave(self::LAZY_LOADER_POST, $post);
+ $this->postId = $post->getId();
+ }
}
diff --git a/src/Entities/Score.php b/src/Entities/Score.php
index 29a64ed6..28197eaa 100644
--- a/src/Entities/Score.php
+++ b/src/Entities/Score.php
@@ -3,59 +3,59 @@ namespace Szurubooru\Entities;
final class Score extends Entity
{
- private $postId;
- private $commentId;
- private $score;
- private $time;
- private $userId;
+ private $postId;
+ private $commentId;
+ private $score;
+ private $time;
+ private $userId;
- public function getUserId()
- {
- return $this->userId;
- }
+ public function getUserId()
+ {
+ return $this->userId;
+ }
- public function setUserId($userId)
- {
- $this->userId = $userId;
- }
+ public function setUserId($userId)
+ {
+ $this->userId = $userId;
+ }
- public function getPostId()
- {
- return $this->postId;
- }
+ public function getPostId()
+ {
+ return $this->postId;
+ }
- public function setPostId($postId)
- {
- $this->postId = $postId;
- }
+ public function setPostId($postId)
+ {
+ $this->postId = $postId;
+ }
- public function getCommentId()
- {
- return $this->commentId;
- }
+ public function getCommentId()
+ {
+ return $this->commentId;
+ }
- public function setCommentId($commentId)
- {
- $this->commentId = $commentId;
- }
+ public function setCommentId($commentId)
+ {
+ $this->commentId = $commentId;
+ }
- public function getTime()
- {
- return $this->time;
- }
+ public function getTime()
+ {
+ return $this->time;
+ }
- public function setTime($time)
- {
- $this->time = $time;
- }
+ public function setTime($time)
+ {
+ $this->time = $time;
+ }
- public function getScore()
- {
- return $this->score;
- }
+ public function getScore()
+ {
+ return $this->score;
+ }
- public function setScore($score)
- {
- $this->score = $score;
- }
+ public function setScore($score)
+ {
+ $this->score = $score;
+ }
}
diff --git a/src/Entities/Snapshot.php b/src/Entities/Snapshot.php
index 548ae857..d22a5bd8 100644
--- a/src/Entities/Snapshot.php
+++ b/src/Entities/Snapshot.php
@@ -4,101 +4,101 @@ use Szurubooru\Entities\User;
final class Snapshot extends Entity
{
- const TYPE_POST = 0;
- const TYPE_TAG = 1;
+ const TYPE_POST = 0;
+ const TYPE_TAG = 1;
- const OPERATION_CREATION = 0;
- const OPERATION_CHANGE = 1;
- const OPERATION_DELETE = 2;
+ const OPERATION_CREATION = 0;
+ const OPERATION_CHANGE = 1;
+ const OPERATION_DELETE = 2;
- const LAZY_LOADER_USER = 'user';
+ const LAZY_LOADER_USER = 'user';
- private $time;
- private $type;
- private $primaryKey;
- private $operation;
- private $userId;
- private $data;
- private $dataDifference;
+ private $time;
+ private $type;
+ private $primaryKey;
+ private $operation;
+ private $userId;
+ private $data;
+ private $dataDifference;
- public function getTime()
- {
- return $this->time;
- }
+ public function getTime()
+ {
+ return $this->time;
+ }
- public function setTime($time)
- {
- $this->time = $time;
- }
+ public function setTime($time)
+ {
+ $this->time = $time;
+ }
- public function getType()
- {
- return $this->type;
- }
+ public function getType()
+ {
+ return $this->type;
+ }
- public function setType($type)
- {
- $this->type = $type;
- }
+ public function setType($type)
+ {
+ $this->type = $type;
+ }
- public function getPrimaryKey()
- {
- return $this->primaryKey;
- }
+ public function getPrimaryKey()
+ {
+ return $this->primaryKey;
+ }
- public function setPrimaryKey($primaryKey)
- {
- $this->primaryKey = $primaryKey;
- }
+ public function setPrimaryKey($primaryKey)
+ {
+ $this->primaryKey = $primaryKey;
+ }
- public function getOperation()
- {
- return $this->operation;
- }
+ public function getOperation()
+ {
+ return $this->operation;
+ }
- public function setOperation($operation)
- {
- $this->operation = $operation;
- }
+ public function setOperation($operation)
+ {
+ $this->operation = $operation;
+ }
- public function getUserId()
- {
- return $this->userId;
- }
+ public function getUserId()
+ {
+ return $this->userId;
+ }
- public function setUserId($userId)
- {
- $this->userId = $userId;
- }
+ public function setUserId($userId)
+ {
+ $this->userId = $userId;
+ }
- public function getData()
- {
- return $this->data;
- }
+ public function getData()
+ {
+ return $this->data;
+ }
- public function setData($data)
- {
- $this->data = $data;
- }
+ public function setData($data)
+ {
+ $this->data = $data;
+ }
- public function getDataDifference()
- {
- return $this->dataDifference;
- }
+ public function getDataDifference()
+ {
+ return $this->dataDifference;
+ }
- public function setDataDifference($dataDifference)
- {
- $this->dataDifference = $dataDifference;
- }
+ public function setDataDifference($dataDifference)
+ {
+ $this->dataDifference = $dataDifference;
+ }
- public function getUser()
- {
- return $this->lazyLoad(self::LAZY_LOADER_USER, null);
- }
+ public function getUser()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_USER, null);
+ }
- public function setUser(User $user = null)
- {
- $this->lazySave(self::LAZY_LOADER_USER, $user);
- $this->userId = $user ? $user->getId() : null;
- }
+ public function setUser(User $user = null)
+ {
+ $this->lazySave(self::LAZY_LOADER_USER, $user);
+ $this->userId = $user ? $user->getId() : null;
+ }
}
diff --git a/src/Entities/Tag.php b/src/Entities/Tag.php
index d186fc40..c3e98ee9 100644
--- a/src/Entities/Tag.php
+++ b/src/Entities/Tag.php
@@ -3,78 +3,78 @@ namespace Szurubooru\Entities;
final class Tag extends Entity
{
- private $name;
- private $creationTime;
- private $banned = false;
- private $category = 'default';
+ private $name;
+ private $creationTime;
+ private $banned = false;
+ private $category = 'default';
- const LAZY_LOADER_IMPLIED_TAGS = 'implications';
- const LAZY_LOADER_SUGGESTED_TAGS = 'suggestions';
+ const LAZY_LOADER_IMPLIED_TAGS = 'implications';
+ const LAZY_LOADER_SUGGESTED_TAGS = 'suggestions';
- const META_USAGES = 'usages';
+ const META_USAGES = 'usages';
- public function getName()
- {
- return $this->name;
- }
+ public function getName()
+ {
+ return $this->name;
+ }
- public function setName($name)
- {
- $this->name = $name;
- }
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
- public function getCreationTime()
- {
- return $this->creationTime;
- }
+ public function getCreationTime()
+ {
+ return $this->creationTime;
+ }
- public function setCreationTime($creationTime)
- {
- $this->creationTime = $creationTime;
- }
+ public function setCreationTime($creationTime)
+ {
+ $this->creationTime = $creationTime;
+ }
- public function isBanned()
- {
- return $this->banned;
- }
+ public function isBanned()
+ {
+ return $this->banned;
+ }
- public function setBanned($banned)
- {
- $this->banned = boolval($banned);
- }
+ public function setBanned($banned)
+ {
+ $this->banned = boolval($banned);
+ }
- public function getCategory()
- {
- return $this->category;
- }
+ public function getCategory()
+ {
+ return $this->category;
+ }
- public function setCategory($category)
- {
- $this->category = $category;
- }
+ public function setCategory($category)
+ {
+ $this->category = $category;
+ }
- public function getUsages()
- {
- return $this->getMeta(self::META_USAGES);
- }
+ public function getUsages()
+ {
+ return $this->getMeta(self::META_USAGES);
+ }
- public function getImpliedTags()
- {
- return $this->lazyLoad(self::LAZY_LOADER_IMPLIED_TAGS, []);
- }
+ public function getImpliedTags()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_IMPLIED_TAGS, []);
+ }
- public function setImpliedTags(array $impliedTags)
- {
- $this->lazySave(self::LAZY_LOADER_IMPLIED_TAGS, $impliedTags);
- }
+ public function setImpliedTags(array $impliedTags)
+ {
+ $this->lazySave(self::LAZY_LOADER_IMPLIED_TAGS, $impliedTags);
+ }
- public function getSuggestedTags()
- {
- return $this->lazyLoad(self::LAZY_LOADER_SUGGESTED_TAGS, []);
- }
+ public function getSuggestedTags()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_SUGGESTED_TAGS, []);
+ }
- public function setSuggestedTags(array $suggestedTags)
- {
- $this->lazySave(self::LAZY_LOADER_SUGGESTED_TAGS, $suggestedTags);
- }
+ public function setSuggestedTags(array $suggestedTags)
+ {
+ $this->lazySave(self::LAZY_LOADER_SUGGESTED_TAGS, $suggestedTags);
+ }
}
diff --git a/src/Entities/Token.php b/src/Entities/Token.php
index 4358f930..4146b072 100644
--- a/src/Entities/Token.php
+++ b/src/Entities/Token.php
@@ -3,41 +3,41 @@ namespace Szurubooru\Entities;
final class Token extends Entity
{
- const PURPOSE_LOGIN = 1;
- const PURPOSE_ACTIVATE = 2;
- const PURPOSE_PASSWORD_RESET = 3;
+ const PURPOSE_LOGIN = 1;
+ const PURPOSE_ACTIVATE = 2;
+ const PURPOSE_PASSWORD_RESET = 3;
- private $name;
- private $purpose;
- private $additionalData;
+ private $name;
+ private $purpose;
+ private $additionalData;
- public function getName()
- {
- return $this->name;
- }
+ public function getName()
+ {
+ return $this->name;
+ }
- public function setName($name)
- {
- $this->name = $name;
- }
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
- public function getPurpose()
- {
- return $this->purpose;
- }
+ public function getPurpose()
+ {
+ return $this->purpose;
+ }
- public function setPurpose($purpose)
- {
- $this->purpose = intval($purpose);
- }
+ public function setPurpose($purpose)
+ {
+ $this->purpose = intval($purpose);
+ }
- public function getAdditionalData()
- {
- return $this->additionalData;
- }
+ public function getAdditionalData()
+ {
+ return $this->additionalData;
+ }
- public function setAdditionalData($additionalData)
- {
- $this->additionalData = $additionalData;
- }
+ public function setAdditionalData($additionalData)
+ {
+ $this->additionalData = $additionalData;
+ }
}
diff --git a/src/Entities/User.php b/src/Entities/User.php
index e0f6fab6..4074677d 100644
--- a/src/Entities/User.php
+++ b/src/Entities/User.php
@@ -3,165 +3,165 @@ namespace Szurubooru\Entities;
final class User extends Entity
{
- const ACCESS_RANK_NOBODY = 0;
- const ACCESS_RANK_ANONYMOUS = 1;
- const ACCESS_RANK_RESTRICTED_USER = 2;
- const ACCESS_RANK_REGULAR_USER = 3;
- const ACCESS_RANK_POWER_USER = 4;
- const ACCESS_RANK_MODERATOR = 5;
- const ACCESS_RANK_ADMINISTRATOR = 6;
+ const ACCESS_RANK_NOBODY = 0;
+ const ACCESS_RANK_ANONYMOUS = 1;
+ const ACCESS_RANK_RESTRICTED_USER = 2;
+ const ACCESS_RANK_REGULAR_USER = 3;
+ const ACCESS_RANK_POWER_USER = 4;
+ const ACCESS_RANK_MODERATOR = 5;
+ const ACCESS_RANK_ADMINISTRATOR = 6;
- const AVATAR_STYLE_GRAVATAR = 1;
- const AVATAR_STYLE_MANUAL = 2;
- const AVATAR_STYLE_BLANK = 3;
+ const AVATAR_STYLE_GRAVATAR = 1;
+ const AVATAR_STYLE_MANUAL = 2;
+ const AVATAR_STYLE_BLANK = 3;
- const LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT = 'customAvatarContent';
+ const LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT = 'customAvatarContent';
- private $name;
- private $email;
- private $emailUnconfirmed;
- private $passwordHash;
- private $passwordSalt;
- private $accessRank;
- private $registrationTime;
- private $lastLoginTime;
- private $avatarStyle;
- private $browsingSettings;
- private $accountConfirmed = false;
- private $banned = false;
+ private $name;
+ private $email;
+ private $emailUnconfirmed;
+ private $passwordHash;
+ private $passwordSalt;
+ private $accessRank;
+ private $registrationTime;
+ private $lastLoginTime;
+ private $avatarStyle;
+ private $browsingSettings;
+ private $accountConfirmed = false;
+ private $banned = false;
- public function getName()
- {
- return $this->name;
- }
+ public function getName()
+ {
+ return $this->name;
+ }
- public function setName($name)
- {
- $this->name = $name;
- }
+ public function setName($name)
+ {
+ $this->name = $name;
+ }
- public function getEmail()
- {
- return $this->email;
- }
+ public function getEmail()
+ {
+ return $this->email;
+ }
- public function setEmail($email)
- {
- $this->email = $email;
- }
+ public function setEmail($email)
+ {
+ $this->email = $email;
+ }
- public function getEmailUnconfirmed()
- {
- return $this->emailUnconfirmed;
- }
+ public function getEmailUnconfirmed()
+ {
+ return $this->emailUnconfirmed;
+ }
- public function setEmailUnconfirmed($emailUnconfirmed)
- {
- $this->emailUnconfirmed = $emailUnconfirmed;
- }
+ public function setEmailUnconfirmed($emailUnconfirmed)
+ {
+ $this->emailUnconfirmed = $emailUnconfirmed;
+ }
- public function isBanned()
- {
- return $this->banned;
- }
+ public function isBanned()
+ {
+ return $this->banned;
+ }
- public function setBanned($banned)
- {
- $this->banned = boolval($banned);
- }
+ public function setBanned($banned)
+ {
+ $this->banned = boolval($banned);
+ }
- public function isAccountConfirmed()
- {
- return $this->accountConfirmed;
- }
+ public function isAccountConfirmed()
+ {
+ return $this->accountConfirmed;
+ }
- public function setAccountConfirmed($accountConfirmed)
- {
- $this->accountConfirmed = boolval($accountConfirmed);
- }
+ public function setAccountConfirmed($accountConfirmed)
+ {
+ $this->accountConfirmed = boolval($accountConfirmed);
+ }
- public function getPasswordHash()
- {
- return $this->passwordHash;
- }
+ public function getPasswordHash()
+ {
+ return $this->passwordHash;
+ }
- public function setPasswordHash($passwordHash)
- {
- $this->passwordHash = $passwordHash;
- }
+ public function setPasswordHash($passwordHash)
+ {
+ $this->passwordHash = $passwordHash;
+ }
- public function getPasswordSalt()
- {
- return $this->passwordSalt;
- }
+ public function getPasswordSalt()
+ {
+ return $this->passwordSalt;
+ }
- public function setPasswordSalt($passwordSalt)
- {
- $this->passwordSalt = $passwordSalt;
- }
+ public function setPasswordSalt($passwordSalt)
+ {
+ $this->passwordSalt = $passwordSalt;
+ }
- public function getAccessRank()
- {
- return $this->accessRank;
- }
+ public function getAccessRank()
+ {
+ return $this->accessRank;
+ }
- public function setAccessRank($accessRank)
- {
- $this->accessRank = $accessRank;
- }
+ public function setAccessRank($accessRank)
+ {
+ $this->accessRank = $accessRank;
+ }
- public function getRegistrationTime()
- {
- return $this->registrationTime;
- }
+ public function getRegistrationTime()
+ {
+ return $this->registrationTime;
+ }
- public function setRegistrationTime($registrationTime)
- {
- $this->registrationTime = $registrationTime;
- }
+ public function setRegistrationTime($registrationTime)
+ {
+ $this->registrationTime = $registrationTime;
+ }
- public function getLastLoginTime()
- {
- return $this->lastLoginTime;
- }
+ public function getLastLoginTime()
+ {
+ return $this->lastLoginTime;
+ }
- public function setLastLoginTime($lastLoginTime)
- {
- $this->lastLoginTime = $lastLoginTime;
- }
+ public function setLastLoginTime($lastLoginTime)
+ {
+ $this->lastLoginTime = $lastLoginTime;
+ }
- public function getAvatarStyle()
- {
- return $this->avatarStyle;
- }
+ public function getAvatarStyle()
+ {
+ return $this->avatarStyle;
+ }
- public function setAvatarStyle($avatarStyle)
- {
- $this->avatarStyle = $avatarStyle;
- }
+ public function setAvatarStyle($avatarStyle)
+ {
+ $this->avatarStyle = $avatarStyle;
+ }
- public function getBrowsingSettings()
- {
- return $this->browsingSettings;
- }
+ public function getBrowsingSettings()
+ {
+ return $this->browsingSettings;
+ }
- public function setBrowsingSettings($browsingSettings)
- {
- $this->browsingSettings = $browsingSettings;
- }
+ public function setBrowsingSettings($browsingSettings)
+ {
+ $this->browsingSettings = $browsingSettings;
+ }
- public function getCustomAvatarSourceContent()
- {
- return $this->lazyLoad(self::LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT, null);
- }
+ public function getCustomAvatarSourceContent()
+ {
+ return $this->lazyLoad(self::LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT, null);
+ }
- public function setCustomAvatarSourceContent($content)
- {
- $this->lazySave(self::LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT, $content);
- }
+ public function setCustomAvatarSourceContent($content)
+ {
+ $this->lazySave(self::LAZY_LOADER_CUSTOM_AVATAR_SOURCE_CONTENT, $content);
+ }
- public function getCustomAvatarSourceContentPath()
- {
- return 'avatars' . DIRECTORY_SEPARATOR . $this->getId();
- }
+ public function getCustomAvatarSourceContentPath()
+ {
+ return 'avatars' . DIRECTORY_SEPARATOR . $this->getId();
+ }
}
diff --git a/src/FormData/LoginFormData.php b/src/FormData/LoginFormData.php
index 2fb3977d..99b3ca2d 100644
--- a/src/FormData/LoginFormData.php
+++ b/src/FormData/LoginFormData.php
@@ -5,19 +5,19 @@ use Szurubooru\Validator;
class LoginFormData implements IValidatable
{
- public $userNameOrEmail;
- public $password;
+ public $userNameOrEmail;
+ public $password;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->userNameOrEmail = trim($inputReader->userNameOrEmail);
- $this->password = $inputReader->password;
- }
- }
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->userNameOrEmail = trim($inputReader->userNameOrEmail);
+ $this->password = $inputReader->password;
+ }
+ }
- public function validate(Validator $validator)
- {
- }
+ public function validate(Validator $validator)
+ {
+ }
}
diff --git a/src/FormData/PostEditFormData.php b/src/FormData/PostEditFormData.php
index f7a2691e..c4a68738 100644
--- a/src/FormData/PostEditFormData.php
+++ b/src/FormData/PostEditFormData.php
@@ -6,46 +6,46 @@ use Szurubooru\Validator;
class PostEditFormData implements IValidatable
{
- public $content;
- public $thumbnail;
- public $safety;
- public $source;
- public $tags;
- public $relations;
- public $flags;
+ public $content;
+ public $thumbnail;
+ public $safety;
+ public $source;
+ public $tags;
+ public $relations;
+ public $flags;
- public $seenEditTime;
+ public $seenEditTime;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->content = $inputReader->readFile('content');
- $this->thumbnail = $inputReader->readFile('thumbnail');
- if ($inputReader->safety)
- $this->safety = EnumHelper::postSafetyFromString($inputReader->safety);
- if ($inputReader->source !== null)
- $this->source = $inputReader->source;
- $this->tags = preg_split('/[\s+]/', $inputReader->tags);
- if ($inputReader->relations !== null)
- $this->relations = array_filter(preg_split('/[\s+]/', $inputReader->relations));
- $this->seenEditTime = $inputReader->seenEditTime;
- $this->flags = new \StdClass;
- $this->flags->loop = !empty($inputReader->loop);
- }
- }
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->content = $inputReader->readFile('content');
+ $this->thumbnail = $inputReader->readFile('thumbnail');
+ if ($inputReader->safety)
+ $this->safety = EnumHelper::postSafetyFromString($inputReader->safety);
+ if ($inputReader->source !== null)
+ $this->source = $inputReader->source;
+ $this->tags = preg_split('/[\s+]/', $inputReader->tags);
+ if ($inputReader->relations !== null)
+ $this->relations = array_filter(preg_split('/[\s+]/', $inputReader->relations));
+ $this->seenEditTime = $inputReader->seenEditTime;
+ $this->flags = new \StdClass;
+ $this->flags->loop = !empty($inputReader->loop);
+ }
+ }
- public function validate(Validator $validator)
- {
- $validator->validatePostTags($this->tags);
+ public function validate(Validator $validator)
+ {
+ $validator->validatePostTags($this->tags);
- if ($this->source !== null)
- $validator->validatePostSource($this->source);
+ if ($this->source !== null)
+ $validator->validatePostSource($this->source);
- if ($this->relations)
- {
- foreach ($this->relations as $relatedPostId)
- $validator->validateNumber($relatedPostId);
- }
- }
+ if ($this->relations)
+ {
+ foreach ($this->relations as $relatedPostId)
+ $validator->validateNumber($relatedPostId);
+ }
+ }
}
diff --git a/src/FormData/PostNoteFormData.php b/src/FormData/PostNoteFormData.php
index b84e51bf..8166141c 100644
--- a/src/FormData/PostNoteFormData.php
+++ b/src/FormData/PostNoteFormData.php
@@ -5,26 +5,26 @@ use Szurubooru\Validator;
class PostNoteFormData implements IValidatable
{
- public $left;
- public $top;
- public $width;
- public $height;
- public $text;
+ public $left;
+ public $top;
+ public $width;
+ public $height;
+ public $text;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->left = floatval($inputReader->left);
- $this->top = floatval($inputReader->top);
- $this->width = floatval($inputReader->width);
- $this->height = floatval($inputReader->height);
- $this->text = trim($inputReader->text);
- }
- }
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->left = floatval($inputReader->left);
+ $this->top = floatval($inputReader->top);
+ $this->width = floatval($inputReader->width);
+ $this->height = floatval($inputReader->height);
+ $this->text = trim($inputReader->text);
+ }
+ }
- public function validate(Validator $validator)
- {
- $validator->validateMinLength($this->text, 3, 'Post note content');
- }
+ public function validate(Validator $validator)
+ {
+ $validator->validateMinLength($this->text, 3, 'Post note content');
+ }
}
diff --git a/src/FormData/RegistrationFormData.php b/src/FormData/RegistrationFormData.php
index 96bd3b7c..0014b687 100644
--- a/src/FormData/RegistrationFormData.php
+++ b/src/FormData/RegistrationFormData.php
@@ -5,24 +5,24 @@ use Szurubooru\Validator;
class RegistrationFormData implements IValidatable
{
- public $userName;
- public $password;
- public $email;
+ public $userName;
+ public $password;
+ public $email;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->userName = trim($inputReader->userName);
- $this->password = $inputReader->password;
- $this->email = trim($inputReader->email);
- }
- }
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->userName = trim($inputReader->userName);
+ $this->password = $inputReader->password;
+ $this->email = trim($inputReader->email);
+ }
+ }
- public function validate(Validator $validator)
- {
- $validator->validateUserName($this->userName);
- $validator->validatePassword($this->password);
- $validator->validateEmail($this->email);
- }
+ public function validate(Validator $validator)
+ {
+ $validator->validateUserName($this->userName);
+ $validator->validatePassword($this->password);
+ $validator->validateEmail($this->email);
+ }
}
diff --git a/src/FormData/TagEditFormData.php b/src/FormData/TagEditFormData.php
index 3ae43caf..0c960dbb 100644
--- a/src/FormData/TagEditFormData.php
+++ b/src/FormData/TagEditFormData.php
@@ -5,40 +5,40 @@ use Szurubooru\Validator;
class TagEditFormData implements IValidatable
{
- public $name;
- public $banned;
- public $category;
- public $implications;
- public $suggestions;
+ public $name;
+ public $banned;
+ public $category;
+ public $implications;
+ public $suggestions;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->name = trim($inputReader->name);
- $this->category = strtolower(trim($inputReader->category));
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->name = trim($inputReader->name);
+ $this->category = strtolower(trim($inputReader->category));
- if ($inputReader->banned !== null)
- $this->banned = boolval($inputReader->banned);
+ if ($inputReader->banned !== null)
+ $this->banned = boolval($inputReader->banned);
- $this->implications = array_filter(array_unique(preg_split('/[\s+]/', $inputReader->implications)));
- $this->suggestions = array_filter(array_unique(preg_split('/[\s+]/', $inputReader->suggestions)));
- }
- }
+ $this->implications = array_filter(array_unique(preg_split('/[\s+]/', $inputReader->implications)));
+ $this->suggestions = array_filter(array_unique(preg_split('/[\s+]/', $inputReader->suggestions)));
+ }
+ }
- public function validate(Validator $validator)
- {
- if ($this->category !== null)
- $validator->validateLength($this->category, 1, 25, 'Tag category');
+ public function validate(Validator $validator)
+ {
+ if ($this->category !== null)
+ $validator->validateLength($this->category, 1, 25, 'Tag category');
- if ($this->name !== null)
- $validator->validatePostTags([$this->name]);
+ if ($this->name !== null)
+ $validator->validatePostTags([$this->name]);
- if (!empty($this->implications))
- $validator->validatePostTags($this->implications);
+ if (!empty($this->implications))
+ $validator->validatePostTags($this->implications);
- if (!empty($this->suggestions))
- $validator->validatePostTags($this->suggestions);
- }
+ if (!empty($this->suggestions))
+ $validator->validatePostTags($this->suggestions);
+ }
}
diff --git a/src/FormData/UploadFormData.php b/src/FormData/UploadFormData.php
index 4b9f4987..ab018cae 100644
--- a/src/FormData/UploadFormData.php
+++ b/src/FormData/UploadFormData.php
@@ -6,37 +6,37 @@ use Szurubooru\Validator;
class UploadFormData implements IValidatable
{
- public $contentFileName;
- public $content;
- public $url;
- public $anonymous;
- public $safety;
- public $source;
- public $tags;
+ public $contentFileName;
+ public $content;
+ public $url;
+ public $anonymous;
+ public $safety;
+ public $source;
+ public $tags;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->contentFileName = $inputReader->contentFileName;
- $this->content = $inputReader->readFile('content');
- $this->url = $inputReader->url;
- $this->anonymous = $inputReader->anonymous;
- $this->safety = EnumHelper::postSafetyFromString($inputReader->safety);
- $this->source = $inputReader->source;
- $this->tags = preg_split('/[\s+]/', $inputReader->tags);
- }
- }
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->contentFileName = $inputReader->contentFileName;
+ $this->content = $inputReader->readFile('content');
+ $this->url = $inputReader->url;
+ $this->anonymous = $inputReader->anonymous;
+ $this->safety = EnumHelper::postSafetyFromString($inputReader->safety);
+ $this->source = $inputReader->source;
+ $this->tags = preg_split('/[\s+]/', $inputReader->tags);
+ }
+ }
- public function validate(Validator $validator)
- {
- if ($this->content === null && $this->url === null)
- throw new \DomainException('Neither data or URL provided.');
+ public function validate(Validator $validator)
+ {
+ if ($this->content === null && $this->url === null)
+ throw new \DomainException('Neither data or URL provided.');
- $validator->validatePostTags($this->tags);
+ $validator->validatePostTags($this->tags);
- if ($this->source !== null)
- $validator->validatePostSource($this->source);
- }
+ if ($this->source !== null)
+ $validator->validatePostSource($this->source);
+ }
}
diff --git a/src/FormData/UserEditFormData.php b/src/FormData/UserEditFormData.php
index 45549b67..10b09351 100644
--- a/src/FormData/UserEditFormData.php
+++ b/src/FormData/UserEditFormData.php
@@ -7,60 +7,60 @@ use Szurubooru\Validator;
class UserEditFormData implements IValidatable
{
- public $userName;
- public $email;
- public $password;
- public $accessRank;
- public $avatarStyle;
- public $avatarContent;
- public $browsingSettings;
- public $banned;
+ public $userName;
+ public $email;
+ public $password;
+ public $accessRank;
+ public $avatarStyle;
+ public $avatarContent;
+ public $browsingSettings;
+ public $banned;
- public function __construct($inputReader = null)
- {
- if ($inputReader !== null)
- {
- $this->userName = $inputReader->userName;
- $this->email = $inputReader->email;
- $this->password = $inputReader->password;
- if ($inputReader->accessRank !== null)
- $this->accessRank = EnumHelper::accessRankFromString($inputReader->accessRank);
- if ($inputReader->avatarStyle !== null)
- $this->avatarStyle = EnumHelper::avatarStyleFromString($inputReader->avatarStyle);
- $this->avatarContent = $inputReader->readFile('avatarContent');
- $this->browsingSettings = json_decode($inputReader->browsingSettings);
- if ($inputReader->banned !== null)
- $this->banned = boolval($inputReader->banned);
- }
- }
+ public function __construct($inputReader = null)
+ {
+ if ($inputReader !== null)
+ {
+ $this->userName = $inputReader->userName;
+ $this->email = $inputReader->email;
+ $this->password = $inputReader->password;
+ if ($inputReader->accessRank !== null)
+ $this->accessRank = EnumHelper::accessRankFromString($inputReader->accessRank);
+ if ($inputReader->avatarStyle !== null)
+ $this->avatarStyle = EnumHelper::avatarStyleFromString($inputReader->avatarStyle);
+ $this->avatarContent = $inputReader->readFile('avatarContent');
+ $this->browsingSettings = json_decode($inputReader->browsingSettings);
+ if ($inputReader->banned !== null)
+ $this->banned = boolval($inputReader->banned);
+ }
+ }
- public function validate(Validator $validator)
- {
- if ($this->userName !== null)
- $validator->validateUserName($this->userName);
+ public function validate(Validator $validator)
+ {
+ if ($this->userName !== null)
+ $validator->validateUserName($this->userName);
- if ($this->password !== null)
- $validator->validatePassword($this->password);
+ if ($this->password !== null)
+ $validator->validatePassword($this->password);
- if ($this->email !== null)
- $validator->validateEmail($this->email);
+ if ($this->email !== null)
+ $validator->validateEmail($this->email);
- if (strlen($this->avatarContent) > 1024 * 512)
- throw new \DomainException('Avatar content must have at most 512 kilobytes.');
+ if (strlen($this->avatarContent) > 1024 * 512)
+ throw new \DomainException('Avatar content must have at most 512 kilobytes.');
- if ($this->avatarContent)
- {
- $avatarContentMimeType = MimeHelper::getMimeTypeFromBuffer($this->avatarContent);
- if (!MimeHelper::isImage($avatarContentMimeType))
- throw new \DomainException('Avatar must be an image (detected: ' . $avatarContentMimeType . ').');
- }
+ if ($this->avatarContent)
+ {
+ $avatarContentMimeType = MimeHelper::getMimeTypeFromBuffer($this->avatarContent);
+ if (!MimeHelper::isImage($avatarContentMimeType))
+ throw new \DomainException('Avatar must be an image (detected: ' . $avatarContentMimeType . ').');
+ }
- if ($this->browsingSettings !== null)
- {
- if (!is_object($this->browsingSettings))
- throw new \InvalidArgumentException('Browsing settings must be valid JSON.');
- else if (strlen(json_encode($this->browsingSettings)) > 300)
- throw new \InvalidArgumentException('Stringified browsing settings can have at most 300 characters.');
- }
- }
+ if ($this->browsingSettings !== null)
+ {
+ if (!is_object($this->browsingSettings))
+ throw new \InvalidArgumentException('Browsing settings must be valid JSON.');
+ else if (strlen(json_encode($this->browsingSettings)) > 300)
+ throw new \InvalidArgumentException('Stringified browsing settings can have at most 300 characters.');
+ }
+ }
}
diff --git a/src/Helpers/EnumHelper.php b/src/Helpers/EnumHelper.php
index 9d599a4e..2e4aa26d 100644
--- a/src/Helpers/EnumHelper.php
+++ b/src/Helpers/EnumHelper.php
@@ -6,111 +6,111 @@ use Szurubooru\Entities\User;
class EnumHelper
{
- private static $accessRankMap =
- [
- 'anonymous' => User::ACCESS_RANK_ANONYMOUS,
- 'restrictedUser' => User::ACCESS_RANK_RESTRICTED_USER,
- 'regularUser' => User::ACCESS_RANK_REGULAR_USER,
- 'powerUser' => User::ACCESS_RANK_POWER_USER,
- 'moderator' => User::ACCESS_RANK_MODERATOR,
- 'administrator' => User::ACCESS_RANK_ADMINISTRATOR,
- ];
+ private static $accessRankMap =
+ [
+ 'anonymous' => User::ACCESS_RANK_ANONYMOUS,
+ 'restrictedUser' => User::ACCESS_RANK_RESTRICTED_USER,
+ 'regularUser' => User::ACCESS_RANK_REGULAR_USER,
+ 'powerUser' => User::ACCESS_RANK_POWER_USER,
+ 'moderator' => User::ACCESS_RANK_MODERATOR,
+ 'administrator' => User::ACCESS_RANK_ADMINISTRATOR,
+ ];
- private static $avatarStyleMap =
- [
- 'gravatar' => User::AVATAR_STYLE_GRAVATAR,
- 'manual' => User::AVATAR_STYLE_MANUAL,
- 'none' => User::AVATAR_STYLE_BLANK,
- 'blank' => User::AVATAR_STYLE_BLANK,
- ];
+ private static $avatarStyleMap =
+ [
+ 'gravatar' => User::AVATAR_STYLE_GRAVATAR,
+ 'manual' => User::AVATAR_STYLE_MANUAL,
+ 'none' => User::AVATAR_STYLE_BLANK,
+ 'blank' => User::AVATAR_STYLE_BLANK,
+ ];
- private static $postSafetyMap =
- [
- 'safe' => Post::POST_SAFETY_SAFE,
- 'sketchy' => Post::POST_SAFETY_SKETCHY,
- 'unsafe' => Post::POST_SAFETY_UNSAFE,
- ];
+ private static $postSafetyMap =
+ [
+ 'safe' => Post::POST_SAFETY_SAFE,
+ 'sketchy' => Post::POST_SAFETY_SKETCHY,
+ 'unsafe' => Post::POST_SAFETY_UNSAFE,
+ ];
- private static $postTypeMap =
- [
- 'image' => Post::POST_TYPE_IMAGE,
- 'video' => Post::POST_TYPE_VIDEO,
- 'flash' => Post::POST_TYPE_FLASH,
- 'youtube' => Post::POST_TYPE_YOUTUBE,
- 'animation' => Post::POST_TYPE_ANIMATED_IMAGE,
- ];
+ private static $postTypeMap =
+ [
+ 'image' => Post::POST_TYPE_IMAGE,
+ 'video' => Post::POST_TYPE_VIDEO,
+ 'flash' => Post::POST_TYPE_FLASH,
+ 'youtube' => Post::POST_TYPE_YOUTUBE,
+ 'animation' => Post::POST_TYPE_ANIMATED_IMAGE,
+ ];
- private static $snapshotTypeMap =
- [
- 'post' => Snapshot::TYPE_POST,
- ];
+ private static $snapshotTypeMap =
+ [
+ 'post' => Snapshot::TYPE_POST,
+ ];
- public static function accessRankToString($accessRank)
- {
- return self::enumToString(self::$accessRankMap, $accessRank);
- }
+ public static function accessRankToString($accessRank)
+ {
+ return self::enumToString(self::$accessRankMap, $accessRank);
+ }
- public static function accessRankFromString($accessRankString)
- {
- return self::stringToEnum(self::$accessRankMap, $accessRankString);
- }
+ public static function accessRankFromString($accessRankString)
+ {
+ return self::stringToEnum(self::$accessRankMap, $accessRankString);
+ }
- public static function avatarStyleToString($avatarStyle)
- {
- return self::enumToString(self::$avatarStyleMap, $avatarStyle);
- }
+ public static function avatarStyleToString($avatarStyle)
+ {
+ return self::enumToString(self::$avatarStyleMap, $avatarStyle);
+ }
- public static function avatarStyleFromString($avatarStyleString)
- {
- return self::stringToEnum(self::$avatarStyleMap, $avatarStyleString);
- }
+ public static function avatarStyleFromString($avatarStyleString)
+ {
+ return self::stringToEnum(self::$avatarStyleMap, $avatarStyleString);
+ }
- public static function postSafetyToString($postSafety)
- {
- return self::enumToString(self::$postSafetyMap, $postSafety);
- }
+ public static function postSafetyToString($postSafety)
+ {
+ return self::enumToString(self::$postSafetyMap, $postSafety);
+ }
- public static function postSafetyFromString($postSafetyString)
- {
- return self::stringToEnum(self::$postSafetyMap, $postSafetyString);
- }
+ public static function postSafetyFromString($postSafetyString)
+ {
+ return self::stringToEnum(self::$postSafetyMap, $postSafetyString);
+ }
- public static function postTypeToString($postType)
- {
- return self::enumToString(self::$postTypeMap, $postType);
- }
+ public static function postTypeToString($postType)
+ {
+ return self::enumToString(self::$postTypeMap, $postType);
+ }
- public static function postTypeFromString($postTypeString)
- {
- return self::stringToEnum(self::$postTypeMap, $postTypeString);
- }
+ public static function postTypeFromString($postTypeString)
+ {
+ return self::stringToEnum(self::$postTypeMap, $postTypeString);
+ }
- public static function snapshotTypeFromString($snapshotTypeString)
- {
- return self::stringToEnum(self::$snapshotTypeMap, $snapshotTypeString);
- }
+ public static function snapshotTypeFromString($snapshotTypeString)
+ {
+ return self::stringToEnum(self::$snapshotTypeMap, $snapshotTypeString);
+ }
- private static function enumToString($enumMap, $enumValue)
- {
- $reverseMap = array_flip($enumMap);
- if (!isset($reverseMap[$enumValue]))
- throw new \RuntimeException('Invalid value!');
+ private static function enumToString($enumMap, $enumValue)
+ {
+ $reverseMap = array_flip($enumMap);
+ if (!isset($reverseMap[$enumValue]))
+ throw new \RuntimeException('Invalid value!');
- return $reverseMap[$enumValue];
- }
+ return $reverseMap[$enumValue];
+ }
- private static function stringToEnum($enumMap, $enumString)
- {
- $key = trim(strtolower($enumString));
- $lowerEnumMap = array_change_key_case($enumMap, \CASE_LOWER);
- if (!isset($lowerEnumMap[$key]))
- {
- throw new \DomainException(sprintf(
- 'Unrecognized value: %s.' . PHP_EOL . 'Possible values: %s',
- $enumString,
- join(', ', array_keys($lowerEnumMap))));
- }
+ private static function stringToEnum($enumMap, $enumString)
+ {
+ $key = trim(strtolower($enumString));
+ $lowerEnumMap = array_change_key_case($enumMap, \CASE_LOWER);
+ if (!isset($lowerEnumMap[$key]))
+ {
+ throw new \DomainException(sprintf(
+ 'Unrecognized value: %s.' . PHP_EOL . 'Possible values: %s',
+ $enumString,
+ join(', ', array_keys($lowerEnumMap))));
+ }
- return $lowerEnumMap[$key];
- }
+ return $lowerEnumMap[$key];
+ }
}
diff --git a/src/Helpers/HttpHelper.php b/src/Helpers/HttpHelper.php
index eeeeb36a..45641087 100644
--- a/src/Helpers/HttpHelper.php
+++ b/src/Helpers/HttpHelper.php
@@ -3,89 +3,89 @@ namespace Szurubooru\Helpers;
class HttpHelper
{
- private $redirected = false;
+ private $redirected = false;
- public function setResponseCode($code)
- {
- http_response_code($code);
- }
+ public function setResponseCode($code)
+ {
+ http_response_code($code);
+ }
- public function setHeader($key, $value)
- {
- header($key . ': ' . $value);
- }
+ public function setHeader($key, $value)
+ {
+ header($key . ': ' . $value);
+ }
- public function outputJSON($data)
- {
- $encodedJson = json_encode((array) $data);
- $lastError = json_last_error();
- if ($lastError !== JSON_ERROR_NONE)
- $this->output('Fatal error while encoding JSON: ' . $lastError . PHP_EOL . PHP_EOL . print_r($data, true));
- else
- $this->output($encodedJson);
- }
+ public function outputJSON($data)
+ {
+ $encodedJson = json_encode((array) $data);
+ $lastError = json_last_error();
+ if ($lastError !== JSON_ERROR_NONE)
+ $this->output('Fatal error while encoding JSON: ' . $lastError . PHP_EOL . PHP_EOL . print_r($data, true));
+ else
+ $this->output($encodedJson);
+ }
- public function output($data)
- {
- echo $data;
- }
+ public function output($data)
+ {
+ echo $data;
+ }
- public function getRequestHeaders()
- {
- if (function_exists('getallheaders'))
- {
- return getallheaders();
- }
- $result = [];
- foreach ($_SERVER as $key => $value)
- {
- if (substr($key, 0, 5) == "HTTP_")
- {
- $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
- $result[$key] = $value;
- }
- else
- {
- $result[$key] = $value;
- }
- }
- return $result;
- }
+ public function getRequestHeaders()
+ {
+ if (function_exists('getallheaders'))
+ {
+ return getallheaders();
+ }
+ $result = [];
+ foreach ($_SERVER as $key => $value)
+ {
+ if (substr($key, 0, 5) == "HTTP_")
+ {
+ $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
+ $result[$key] = $value;
+ }
+ else
+ {
+ $result[$key] = $value;
+ }
+ }
+ return $result;
+ }
- public function getRequestHeader($key)
- {
- $headers = $this->getRequestHeaders();
- return isset($headers[$key]) ? $headers[$key] : null;
- }
+ public function getRequestHeader($key)
+ {
+ $headers = $this->getRequestHeaders();
+ return isset($headers[$key]) ? $headers[$key] : null;
+ }
- public function getRequestMethod()
- {
- return $_SERVER['REQUEST_METHOD'];
- }
+ public function getRequestMethod()
+ {
+ return $_SERVER['REQUEST_METHOD'];
+ }
- public function getRequestUri()
- {
- $requestUri = $_SERVER['REQUEST_URI'];
- $requestUri = preg_replace('/\?.*$/', '', $requestUri);
- return $requestUri;
- }
+ public function getRequestUri()
+ {
+ $requestUri = $_SERVER['REQUEST_URI'];
+ $requestUri = preg_replace('/\?.*$/', '', $requestUri);
+ return $requestUri;
+ }
- public function redirect($destination)
- {
- $this->setResponseCode(307);
- $this->setHeader('Location', $destination);
- $this->redirected = true;
- }
+ public function redirect($destination)
+ {
+ $this->setResponseCode(307);
+ $this->setHeader('Location', $destination);
+ $this->redirected = true;
+ }
- public function nonCachedRedirect($destination)
- {
- $this->setResponseCode(303);
- $this->setHeader('Location', $destination);
- $this->redirected = true;
- }
+ public function nonCachedRedirect($destination)
+ {
+ $this->setResponseCode(303);
+ $this->setHeader('Location', $destination);
+ $this->redirected = true;
+ }
- public function isRedirecting()
- {
- return $this->redirected;
- }
+ public function isRedirecting()
+ {
+ return $this->redirected;
+ }
}
diff --git a/src/Helpers/InputReader.php b/src/Helpers/InputReader.php
index 874b3a58..5f4353d6 100644
--- a/src/Helpers/InputReader.php
+++ b/src/Helpers/InputReader.php
@@ -3,36 +3,36 @@ namespace Szurubooru\Helpers;
final class InputReader extends \ArrayObject
{
- public function __construct()
- {
- parent::setFlags(parent::ARRAY_AS_PROPS | parent::STD_PROP_LIST);
+ public function __construct()
+ {
+ parent::setFlags(parent::ARRAY_AS_PROPS | parent::STD_PROP_LIST);
- $_PUT = [];
- if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT')
- parse_str(file_get_contents('php://input'), $_PUT);
+ $_PUT = [];
+ if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PUT')
+ parse_str(file_get_contents('php://input'), $_PUT);
- foreach ([$_GET, $_POST, $_PUT] as $source)
- {
- foreach ($source as $key => $value)
- $this->offsetSet($key, $value);
- }
- }
+ foreach ([$_GET, $_POST, $_PUT] as $source)
+ {
+ foreach ($source as $key => $value)
+ $this->offsetSet($key, $value);
+ }
+ }
- public function offsetGet($index)
- {
- if (!parent::offsetExists($index))
- return null;
- return parent::offsetGet($index);
- }
+ public function offsetGet($index)
+ {
+ if (!parent::offsetExists($index))
+ return null;
+ return parent::offsetGet($index);
+ }
- public function readFile($fileName)
- {
- if (!isset($_FILES[$fileName]))
- return null;
+ public function readFile($fileName)
+ {
+ if (!isset($_FILES[$fileName]))
+ return null;
- if (!$_FILES[$fileName]['tmp_name'])
- throw new \Exception('File is probably too big.');
+ if (!$_FILES[$fileName]['tmp_name'])
+ throw new \Exception('File is probably too big.');
- return file_get_contents($_FILES[$fileName]['tmp_name']);
- }
+ return file_get_contents($_FILES[$fileName]['tmp_name']);
+ }
}
diff --git a/src/Helpers/MimeHelper.php b/src/Helpers/MimeHelper.php
index a771aa15..ea05631a 100644
--- a/src/Helpers/MimeHelper.php
+++ b/src/Helpers/MimeHelper.php
@@ -3,99 +3,99 @@ namespace Szurubooru\Helpers;
class MimeHelper
{
- public static function getMimeTypeFromFile($path)
- {
- $fh = fopen($path, 'rb');
- if (!$fh)
- throw new \Exception('Cannot open ' . $path . ' for reading');
- $bytes = fread($fh, 16);
- fclose($fh);
- return self::getMimeTypeFrom16Bytes($bytes);
- }
+ public static function getMimeTypeFromFile($path)
+ {
+ $fh = fopen($path, 'rb');
+ if (!$fh)
+ throw new \Exception('Cannot open ' . $path . ' for reading');
+ $bytes = fread($fh, 16);
+ fclose($fh);
+ return self::getMimeTypeFrom16Bytes($bytes);
+ }
- public static function getMimeTypeFromBuffer($buffer)
- {
- return self::getMimeTypeFrom16Bytes(substr($buffer, 0, 16));
- }
+ public static function getMimeTypeFromBuffer($buffer)
+ {
+ return self::getMimeTypeFrom16Bytes(substr($buffer, 0, 16));
+ }
- public static function isBufferAnimatedGif($buffer)
- {
- return strtolower(self::getMimeTypeFromBuffer($buffer)) === 'image/gif'
- and preg_match_all('#\x21\xf9\x04.{4}\x00[\x2c\x21]#s', $buffer) > 1;
- }
+ public static function isBufferAnimatedGif($buffer)
+ {
+ return strtolower(self::getMimeTypeFromBuffer($buffer)) === 'image/gif'
+ and preg_match_all('#\x21\xf9\x04.{4}\x00[\x2c\x21]#s', $buffer) > 1;
+ }
- public static function isFlash($mime)
- {
- return strtolower($mime) === 'application/x-shockwave-flash';
- }
+ public static function isFlash($mime)
+ {
+ return strtolower($mime) === 'application/x-shockwave-flash';
+ }
- public static function isVideo($mime)
- {
- return strtolower($mime) === 'application/ogg' || preg_match('/video\//i', $mime);
- }
+ public static function isVideo($mime)
+ {
+ return strtolower($mime) === 'application/ogg' || preg_match('/video\//i', $mime);
+ }
- public static function isImage($mime)
- {
- return in_array(strtolower($mime), ['image/jpeg', 'image/png', 'image/gif']);
- }
+ public static function isImage($mime)
+ {
+ return in_array(strtolower($mime), ['image/jpeg', 'image/png', 'image/gif']);
+ }
- public static function getExtension($mime)
- {
- $map =
- [
- 'application/x-shockwave-flash' => 'SWF',
- 'image/jpeg' => 'JPG',
- 'image/png' => 'PNG',
- 'image/gif' => 'GIF',
- 'video/webm' => 'WEBM',
- 'video/mp4' => 'MP4',
- 'video/mpeg' => 'MPEG MPG MPE',
- 'video/x-flv' => 'FLV',
- 'video/x-matroska' => 'MKV',
- 'video/3gpp' => '3GP',
- 'video/quicktime' => 'QT MOV',
- 'text/plain' => 'TXT',
- ];
- $key = strtolower(trim($mime));
- return isset($map[$key]) ? $map[$key] : null;
- }
+ public static function getExtension($mime)
+ {
+ $map =
+ [
+ 'application/x-shockwave-flash' => 'SWF',
+ 'image/jpeg' => 'JPG',
+ 'image/png' => 'PNG',
+ 'image/gif' => 'GIF',
+ 'video/webm' => 'WEBM',
+ 'video/mp4' => 'MP4',
+ 'video/mpeg' => 'MPEG MPG MPE',
+ 'video/x-flv' => 'FLV',
+ 'video/x-matroska' => 'MKV',
+ 'video/3gpp' => '3GP',
+ 'video/quicktime' => 'QT MOV',
+ 'text/plain' => 'TXT',
+ ];
+ $key = strtolower(trim($mime));
+ return isset($map[$key]) ? $map[$key] : null;
+ }
- private static function getMimeTypeFrom16Bytes($bytes)
- {
- if ($bytes === false)
- return false;
+ private static function getMimeTypeFrom16Bytes($bytes)
+ {
+ if ($bytes === false)
+ return false;
- if (strncmp($bytes, 'CWS', 3) === 0 || strncmp($bytes, 'FWS', 3) === 0 || strncmp($bytes, 'ZWS', 3) === 0)
- return 'application/x-shockwave-flash';
+ if (strncmp($bytes, 'CWS', 3) === 0 || strncmp($bytes, 'FWS', 3) === 0 || strncmp($bytes, 'ZWS', 3) === 0)
+ return 'application/x-shockwave-flash';
- if (strncmp($bytes, "\xff\xd8\xff", 3) === 0)
- return 'image/jpeg';
+ if (strncmp($bytes, "\xff\xd8\xff", 3) === 0)
+ return 'image/jpeg';
- if (strncmp($bytes, "\x89PNG\x0d\x0a", 6) === 0)
- return 'image/png';
+ if (strncmp($bytes, "\x89PNG\x0d\x0a", 6) === 0)
+ return 'image/png';
- if (strncmp($bytes, 'GIF87a', 6) === 0 || strncmp($bytes, 'GIF89a', 6) === 0)
- return 'image/gif';
+ if (strncmp($bytes, 'GIF87a', 6) === 0 || strncmp($bytes, 'GIF89a', 6) === 0)
+ return 'image/gif';
- if (strncmp($bytes, "\x1a\x45\xdf\xa3", 4) === 0)
- return 'video/webm';
+ if (strncmp($bytes, "\x1a\x45\xdf\xa3", 4) === 0)
+ return 'video/webm';
- if (strncmp(substr($bytes, 4), 'ftypisom', 8) === 0 || strncmp(substr($bytes, 4), 'ftypmp42', 8) === 0)
- return 'video/mp4';
+ if (strncmp(substr($bytes, 4), 'ftypisom', 8) === 0 || strncmp(substr($bytes, 4), 'ftypmp42', 8) === 0)
+ return 'video/mp4';
- if (strncmp($bytes, "\x46\x4c\x56\x01", 4) === 0)
- return 'video/x-flv';
+ if (strncmp($bytes, "\x46\x4c\x56\x01", 4) === 0)
+ return 'video/x-flv';
- if (strncmp($bytes, "\x1a\x45\xdf\xa3\x93\x42\x82\x88\x6d\x61\x74\x72\x6f\x73\x6b\x61", 16) === 0)
- return 'video/x-matroska';
+ if (strncmp($bytes, "\x1a\x45\xdf\xa3\x93\x42\x82\x88\x6d\x61\x74\x72\x6f\x73\x6b\x61", 16) === 0)
+ return 'video/x-matroska';
- if (strncmp($bytes, "\x00\x00\x00\x14\x66\x74\x79\x70\x33\x67\x70", 12) === 0 or
- strncmp($bytes, "\x00\x00\x00\x20\x66\x74\x79\x70\x33\x67\x70", 12) === 0)
- return 'video/3gpp';
+ if (strncmp($bytes, "\x00\x00\x00\x14\x66\x74\x79\x70\x33\x67\x70", 12) === 0 or
+ strncmp($bytes, "\x00\x00\x00\x20\x66\x74\x79\x70\x33\x67\x70", 12) === 0)
+ return 'video/3gpp';
- if (strncmp(substr($bytes, 4), 'ftypqt ', 8) === 0)
- return 'video/quicktime';
+ if (strncmp(substr($bytes, 4), 'ftypqt ', 8) === 0)
+ return 'video/quicktime';
- return 'application/octet-stream';
- }
+ return 'application/octet-stream';
+ }
}
diff --git a/src/Helpers/ProgramExecutor.php b/src/Helpers/ProgramExecutor.php
index 87aa0ffa..09ffb802 100644
--- a/src/Helpers/ProgramExecutor.php
+++ b/src/Helpers/ProgramExecutor.php
@@ -3,24 +3,24 @@ namespace Szurubooru\Helpers;
class ProgramExecutor
{
- public static function run($programName, $arguments)
- {
- $quotedArguments = array_map('escapeshellarg', $arguments);
+ public static function run($programName, $arguments)
+ {
+ $quotedArguments = array_map('escapeshellarg', $arguments);
- $cmd = sprintf('%s %s 2>&1', $programName, implode(' ', $quotedArguments));
- return exec($cmd);
- }
+ $cmd = sprintf('%s %s 2>&1', $programName, implode(' ', $quotedArguments));
+ return exec($cmd);
+ }
- public static function isProgramAvailable($programName)
- {
- if (PHP_OS === 'WINNT')
- {
- exec('where "' . $programName . '" 2>&1 >nul', $trash, $exitCode);
- }
- else
- {
- exec('command -v "' . $programName . '" >/dev/null 2>&1', $trash, $exitCode);
- }
- return $exitCode === 0;
- }
+ public static function isProgramAvailable($programName)
+ {
+ if (PHP_OS === 'WINNT')
+ {
+ exec('where "' . $programName . '" 2>&1 >nul', $trash, $exitCode);
+ }
+ else
+ {
+ exec('command -v "' . $programName . '" >/dev/null 2>&1', $trash, $exitCode);
+ }
+ return $exitCode === 0;
+ }
}
diff --git a/src/Helpers/TypeHelper.php b/src/Helpers/TypeHelper.php
index ea1354f9..e9c95256 100644
--- a/src/Helpers/TypeHelper.php
+++ b/src/Helpers/TypeHelper.php
@@ -3,18 +3,18 @@ namespace Szurubooru\Helpers;
class TypeHelper
{
- public static function toBool($value)
- {
- if ($value === 0)
- return false;
- if ($value === 'false')
- return false;
- if ($value === false)
- return false;
- if (is_array($value) && count($value) === 1)
- return false;
- if ($value === null)
- return false;
- return true;
- }
+ public static function toBool($value)
+ {
+ if ($value === 0)
+ return false;
+ if ($value === 'false')
+ return false;
+ if ($value === false)
+ return false;
+ if (is_array($value) && count($value) === 1)
+ return false;
+ if ($value === null)
+ return false;
+ return true;
+ }
}
diff --git a/src/IValidatable.php b/src/IValidatable.php
index be2913cf..31b51f8d 100644
--- a/src/IValidatable.php
+++ b/src/IValidatable.php
@@ -4,5 +4,5 @@ use Szurubooru\Validator;
interface IValidatable
{
- public function validate(Validator $validator);
+ public function validate(Validator $validator);
}
diff --git a/src/Injector.php b/src/Injector.php
index a03921d5..9ba6562a 100644
--- a/src/Injector.php
+++ b/src/Injector.php
@@ -5,36 +5,36 @@ use Doctrine\Common\Cache\ArrayCache;
final class Injector
{
- private static $container;
- private static $definitionCache;
+ private static $container;
+ private static $definitionCache;
- public static function init()
- {
- $definitionsPath = __DIR__
- . DIRECTORY_SEPARATOR . '..'
- . DIRECTORY_SEPARATOR . 'src'
- . DIRECTORY_SEPARATOR . 'di.php';
+ public static function init()
+ {
+ $definitionsPath = __DIR__
+ . DIRECTORY_SEPARATOR . '..'
+ . DIRECTORY_SEPARATOR . 'src'
+ . DIRECTORY_SEPARATOR . 'di.php';
- self::$definitionCache = new ArrayCache();
- $builder = new ContainerBuilder();
- $builder->setDefinitionCache(self::$definitionCache);
- $builder->addDefinitions($definitionsPath);
- $builder->useAutowiring(true);
- $builder->useAnnotations(false);
- self::$container = $builder->build();
- }
+ self::$definitionCache = new ArrayCache();
+ $builder = new ContainerBuilder();
+ $builder->setDefinitionCache(self::$definitionCache);
+ $builder->addDefinitions($definitionsPath);
+ $builder->useAutowiring(true);
+ $builder->useAnnotations(false);
+ self::$container = $builder->build();
+ }
- public static function get($className)
- {
- return self::$container->get($className);
- }
+ public static function get($className)
+ {
+ return self::$container->get($className);
+ }
- public static function set($className, $object)
- {
- self::$container->set($className, $object);
- self::$definitionCache->delete($className);
- self::$definitionCache->flushAll();
- }
+ public static function set($className, $object)
+ {
+ self::$container->set($className, $object);
+ self::$definitionCache->delete($className);
+ self::$definitionCache->flushAll();
+ }
}
Injector::init();
diff --git a/src/NotSupportedException.php b/src/NotSupportedException.php
index 06af8987..1eadec16 100644
--- a/src/NotSupportedException.php
+++ b/src/NotSupportedException.php
@@ -3,8 +3,8 @@ namespace Szurubooru;
class NotSupportedException extends \BadMethodCallException
{
- public function __construct($message = null)
- {
- parent::__construct($message === null ? 'Not supported' : $message);
- }
+ public function __construct($message = null)
+ {
+ parent::__construct($message === null ? 'Not supported' : $message);
+ }
}
diff --git a/src/PDOEx/BaseQuery.php b/src/PDOEx/BaseQuery.php
index e046fa61..81242775 100644
--- a/src/PDOEx/BaseQuery.php
+++ b/src/PDOEx/BaseQuery.php
@@ -3,172 +3,172 @@ namespace Szurubooru\PDOEx;
abstract class BaseQuery implements \IteratorAggregate
{
- const CLAUSE_BASE = 'base';
- const CLAUSE_WHERE = 'where';
- const CLAUSE_JOIN = 'join';
- const CLAUSE_ORDER = 'order';
- const CLAUSE_GROUP = 'group';
- const CLAUSE_LIMIT = 'limit';
+ const CLAUSE_BASE = 'base';
+ const CLAUSE_WHERE = 'where';
+ const CLAUSE_JOIN = 'join';
+ const CLAUSE_ORDER = 'order';
+ const CLAUSE_GROUP = 'group';
+ const CLAUSE_LIMIT = 'limit';
- protected $table;
- protected $pdoex;
+ protected $table;
+ protected $pdoex;
- protected $clauses;
- protected $parameters;
+ protected $clauses;
+ protected $parameters;
- public function __construct(PDOEx $pdoex, $table)
- {
- $this->pdoex = $pdoex;
- $this->table = $table;
- $this->clauses = [];
- $this->parameters = [];
- $this->init();
- }
+ public function __construct(PDOEx $pdoex, $table)
+ {
+ $this->pdoex = $pdoex;
+ $this->table = $table;
+ $this->clauses = [];
+ $this->parameters = [];
+ $this->init();
+ }
- public function getIterator()
- {
- return $this->execute();
- }
+ public function getIterator()
+ {
+ return $this->execute();
+ }
- public function getQuery()
- {
- return $this->buildQuery();
- }
+ public function getQuery()
+ {
+ return $this->buildQuery();
+ }
- public function execute()
- {
- $query = $this->buildQuery();
- $parameters = $this->getParameters();
+ public function execute()
+ {
+ $query = $this->buildQuery();
+ $parameters = $this->getParameters();
- try
- {
- $result = $this->pdoex->prepare($query);
- if (!$result || !$result->execute($parameters))
- $this->throwQueryException($query, $parameters, 'unknown reason');
- }
- catch (\PDOException $e)
- {
- $this->throwQueryException($query, $parameters, $e->getMessage());
- }
- return $result;
- }
+ try
+ {
+ $result = $this->pdoex->prepare($query);
+ if (!$result || !$result->execute($parameters))
+ $this->throwQueryException($query, $parameters, 'unknown reason');
+ }
+ catch (\PDOException $e)
+ {
+ $this->throwQueryException($query, $parameters, $e->getMessage());
+ }
+ return $result;
+ }
- public function innerJoin($table, $condition)
- {
- if (!isset($this->clauses[self::CLAUSE_JOIN]))
- $this->clauses[self::CLAUSE_JOIN] = [];
+ public function innerJoin($table, $condition)
+ {
+ if (!isset($this->clauses[self::CLAUSE_JOIN]))
+ $this->clauses[self::CLAUSE_JOIN] = [];
- $this->clauses[self::CLAUSE_JOIN][] = 'INNER JOIN ' . $table . ' ON ' . $condition;
- return $this;
- }
+ $this->clauses[self::CLAUSE_JOIN][] = 'INNER JOIN ' . $table . ' ON ' . $condition;
+ return $this;
+ }
- public function where($key, $value = null)
- {
- if ($key === null)
- {
- $this->clauses[self::CLAUSE_WHERE] = [];
- return;
- }
+ public function where($key, $value = null)
+ {
+ if ($key === null)
+ {
+ $this->clauses[self::CLAUSE_WHERE] = [];
+ return;
+ }
- if (!isset($this->clauses[self::CLAUSE_WHERE]))
- $this->clauses[self::CLAUSE_WHERE] = [];
+ if (!isset($this->clauses[self::CLAUSE_WHERE]))
+ $this->clauses[self::CLAUSE_WHERE] = [];
- $sql = empty($this->clauses[self::CLAUSE_WHERE]) ? 'WHERE' : 'AND';
+ $sql = empty($this->clauses[self::CLAUSE_WHERE]) ? 'WHERE' : 'AND';
- if (strpos($key, '?') !== false)
- {
- if (!is_array($value))
- $value = [$value];
- assert(substr_count($key, '?') === count($value), 'Binding ' . print_r($value, true) . ' to ' . $key);
- $index = 0;
- $sql .= ' ' . preg_replace_callback(
- '/\?/',
- function($match) use (&$index, $value)
- {
- $ret = $this->bind($value[$index]);
- $index ++;
- return $ret;
- },
- $key);
- $this->clauses[self::CLAUSE_WHERE][] = $sql;
- return $this;
- }
+ if (strpos($key, '?') !== false)
+ {
+ if (!is_array($value))
+ $value = [$value];
+ assert(substr_count($key, '?') === count($value), 'Binding ' . print_r($value, true) . ' to ' . $key);
+ $index = 0;
+ $sql .= ' ' . preg_replace_callback(
+ '/\?/',
+ function($match) use (&$index, $value)
+ {
+ $ret = $this->bind($value[$index]);
+ $index ++;
+ return $ret;
+ },
+ $key);
+ $this->clauses[self::CLAUSE_WHERE][] = $sql;
+ return $this;
+ }
- if (!is_array($value))
- {
- if ($value === null)
- $sql .= ' ' . $key . ' IS NULL';
- else
- $sql .= ' ' . $key . ' = ' . $this->bind($value);
- $this->clauses[self::CLAUSE_WHERE][] = $sql;
- return $this;
- }
+ if (!is_array($value))
+ {
+ if ($value === null)
+ $sql .= ' ' . $key . ' IS NULL';
+ else
+ $sql .= ' ' . $key . ' = ' . $this->bind($value);
+ $this->clauses[self::CLAUSE_WHERE][] = $sql;
+ return $this;
+ }
- if (empty($value))
- {
- $sql .= ' 0';
- $this->clauses[self::CLAUSE_WHERE][] = $sql;
- return $this;
- }
+ if (empty($value))
+ {
+ $sql .= ' 0';
+ $this->clauses[self::CLAUSE_WHERE][] = $sql;
+ return $this;
+ }
- $sql .= ' ' . $key . ' IN (';
- foreach ($value as $id => $val)
- {
- $sql .= $this->bind($val) . ', ';
- }
- $sql = substr($sql, 0, -2);
- $sql .= ')';
- $this->clauses[self::CLAUSE_WHERE][] = $sql;
- return $this;
- }
+ $sql .= ' ' . $key . ' IN (';
+ foreach ($value as $id => $val)
+ {
+ $sql .= $this->bind($val) . ', ';
+ }
+ $sql = substr($sql, 0, -2);
+ $sql .= ')';
+ $this->clauses[self::CLAUSE_WHERE][] = $sql;
+ return $this;
+ }
- protected function getParameters()
- {
- return $this->parameters;
- }
+ protected function getParameters()
+ {
+ return $this->parameters;
+ }
- protected function buildQuery()
- {
- $priorities = array_flip([
- self::CLAUSE_BASE,
- self::CLAUSE_JOIN,
- self::CLAUSE_WHERE,
- self::CLAUSE_GROUP,
- self::CLAUSE_ORDER,
- self::CLAUSE_LIMIT]);
- uksort(
- $this->clauses,
- function($clauseNameA, $clauseNameB) use ($priorities)
- {
- return $priorities[$clauseNameA] - $priorities[$clauseNameB];
- });
+ protected function buildQuery()
+ {
+ $priorities = array_flip([
+ self::CLAUSE_BASE,
+ self::CLAUSE_JOIN,
+ self::CLAUSE_WHERE,
+ self::CLAUSE_GROUP,
+ self::CLAUSE_ORDER,
+ self::CLAUSE_LIMIT]);
+ uksort(
+ $this->clauses,
+ function($clauseNameA, $clauseNameB) use ($priorities)
+ {
+ return $priorities[$clauseNameA] - $priorities[$clauseNameB];
+ });
- $query = '';
- foreach ($this->clauses as $statements)
- {
- if (!is_array($statements))
- $statements = [$statements];
- foreach ($statements as $statement)
- $query .= ' ' . $statement;
- }
- return trim($query);
- }
+ $query = '';
+ foreach ($this->clauses as $statements)
+ {
+ if (!is_array($statements))
+ $statements = [$statements];
+ foreach ($statements as $statement)
+ $query .= ' ' . $statement;
+ }
+ return trim($query);
+ }
- protected abstract function init();
+ protected abstract function init();
- protected function bind($value)
- {
- $id = ':' . uniqid();
- $this->parameters[$id] = $value;
- return $id;
- }
+ protected function bind($value)
+ {
+ $id = ':' . uniqid();
+ $this->parameters[$id] = $value;
+ return $id;
+ }
- private function throwQueryException($query, $parameters, $message)
- {
- throw new \Exception(sprintf(
- 'Problem executing query "%s" with parameters %s: %s',
- $query,
- print_r($parameters, true),
- $message));
- }
+ private function throwQueryException($query, $parameters, $message)
+ {
+ throw new \Exception(sprintf(
+ 'Problem executing query "%s" with parameters %s: %s',
+ $query,
+ print_r($parameters, true),
+ $message));
+ }
}
diff --git a/src/PDOEx/DeleteQuery.php b/src/PDOEx/DeleteQuery.php
index eef55517..395989c5 100644
--- a/src/PDOEx/DeleteQuery.php
+++ b/src/PDOEx/DeleteQuery.php
@@ -3,8 +3,8 @@ namespace Szurubooru\PDOEx;
class DeleteQuery extends BaseQuery
{
- protected function init()
- {
- $this->clauses[self::CLAUSE_BASE] = 'DELETE FROM ' . $this->table;
- }
+ protected function init()
+ {
+ $this->clauses[self::CLAUSE_BASE] = 'DELETE FROM ' . $this->table;
+ }
}
diff --git a/src/PDOEx/InsertQuery.php b/src/PDOEx/InsertQuery.php
index a42fc27b..0b4e9f22 100644
--- a/src/PDOEx/InsertQuery.php
+++ b/src/PDOEx/InsertQuery.php
@@ -3,39 +3,39 @@ namespace Szurubooru\PDOEx;
class InsertQuery extends BaseQuery
{
- private $values = [];
+ private $values = [];
- public function values(array $values)
- {
- $this->values = $values;
- $this->refreshBaseQuery();
- return $this;
- }
+ public function values(array $values)
+ {
+ $this->values = $values;
+ $this->refreshBaseQuery();
+ return $this;
+ }
- public function where($key, $value = null)
- {
- throw new \BadMethodCallException('This makes no sense!');
- }
+ public function where($key, $value = null)
+ {
+ throw new \BadMethodCallException('This makes no sense!');
+ }
- public function innerJoin($table, $condition)
- {
- throw new \BadMethodCallException('This makes no sense!');
- }
+ public function innerJoin($table, $condition)
+ {
+ throw new \BadMethodCallException('This makes no sense!');
+ }
- protected function init()
- {
- $this->refreshBaseQuery();
- }
+ protected function init()
+ {
+ $this->refreshBaseQuery();
+ }
- private function refreshBaseQuery()
- {
- $sql = 'INSERT INTO ' . $this->table;
- $sql .= ' (' . implode(', ', array_keys($this->values)) . ')';
- $sql .= ' VALUES (';
- foreach ($this->values as $value)
- $sql .= $this->bind($value) . ', ';
- $sql = substr($sql, 0, -2);
- $sql .= ')';
- $this->clauses[self::CLAUSE_BASE] = $sql;
- }
+ private function refreshBaseQuery()
+ {
+ $sql = 'INSERT INTO ' . $this->table;
+ $sql .= ' (' . implode(', ', array_keys($this->values)) . ')';
+ $sql .= ' VALUES (';
+ foreach ($this->values as $value)
+ $sql .= $this->bind($value) . ', ';
+ $sql = substr($sql, 0, -2);
+ $sql .= ')';
+ $this->clauses[self::CLAUSE_BASE] = $sql;
+ }
}
diff --git a/src/PDOEx/PDOEx.php b/src/PDOEx/PDOEx.php
index 14862699..01c049da 100644
--- a/src/PDOEx/PDOEx.php
+++ b/src/PDOEx/PDOEx.php
@@ -3,43 +3,43 @@ namespace Szurubooru\PDOEx;
class PDOEx extends \PDO
{
- private $queryCount = 0;
- private $statements = [];
+ private $queryCount = 0;
+ private $statements = [];
- public function prepare($statement, $driverOptions = [])
- {
- ++ $this->queryCount;
- $this->statements[] = $statement;
- return parent::prepare($statement, $driverOptions);
- }
+ public function prepare($statement, $driverOptions = [])
+ {
+ ++ $this->queryCount;
+ $this->statements[] = $statement;
+ return parent::prepare($statement, $driverOptions);
+ }
- public function getQueryCount()
- {
- return $this->queryCount;
- }
+ public function getQueryCount()
+ {
+ return $this->queryCount;
+ }
- public function getStatements()
- {
- return $this->statements;
- }
+ public function getStatements()
+ {
+ return $this->statements;
+ }
- public function from($table)
- {
- return new SelectQuery($this, $table);
- }
+ public function from($table)
+ {
+ return new SelectQuery($this, $table);
+ }
- public function insertInto($table)
- {
- return new InsertQuery($this, $table);
- }
+ public function insertInto($table)
+ {
+ return new InsertQuery($this, $table);
+ }
- public function update($table)
- {
- return new UpdateQuery($this, $table);
- }
+ public function update($table)
+ {
+ return new UpdateQuery($this, $table);
+ }
- public function deleteFrom($table)
- {
- return new DeleteQuery($this, $table);
- }
+ public function deleteFrom($table)
+ {
+ return new DeleteQuery($this, $table);
+ }
}
diff --git a/src/PDOEx/SelectQuery.php b/src/PDOEx/SelectQuery.php
index e19e282e..f6afb4d4 100644
--- a/src/PDOEx/SelectQuery.php
+++ b/src/PDOEx/SelectQuery.php
@@ -3,93 +3,93 @@ namespace Szurubooru\PDOEx;
class SelectQuery extends BaseQuery implements \Countable
{
- private $selectTarget = '';
- private $orderTarget = '';
- private $offset = 0;
- private $limit = null;
+ private $selectTarget = '';
+ private $orderTarget = '';
+ private $offset = 0;
+ private $limit = null;
- public function limit($limit)
- {
- if ($limit === null || $limit === false)
- $this->limit = null;
- else
- $this->limit = intval($limit);
- $this->refreshLimitClause();
- return $this;
- }
+ public function limit($limit)
+ {
+ if ($limit === null || $limit === false)
+ $this->limit = null;
+ else
+ $this->limit = intval($limit);
+ $this->refreshLimitClause();
+ return $this;
+ }
- public function offset($offset)
- {
- $this->offset = intval($offset);
- $this->refreshLimitClause();
- return $this;
- }
+ public function offset($offset)
+ {
+ $this->offset = intval($offset);
+ $this->refreshLimitClause();
+ return $this;
+ }
- public function select($key)
- {
- if ($key === null)
- $this->selectTarget = '';
- else
- {
- if ($this->selectTarget)
- $this->selectTarget .= ', ';
- $this->selectTarget .= $key;
- }
- $this->refreshBaseClause();
- return $this;
- }
+ public function select($key)
+ {
+ if ($key === null)
+ $this->selectTarget = '';
+ else
+ {
+ if ($this->selectTarget)
+ $this->selectTarget .= ', ';
+ $this->selectTarget .= $key;
+ }
+ $this->refreshBaseClause();
+ return $this;
+ }
- public function orderBy($key, $dir = null)
- {
- if ($key === null)
- $this->orderTarget = '';
- else
- {
- if ($this->orderTarget)
- $this->orderTarget .= ', ';
- $this->orderTarget .= rtrim($key . ' ' . $dir);
- }
- $this->refreshOrderClause();
- return $this;
- }
+ public function orderBy($key, $dir = null)
+ {
+ if ($key === null)
+ $this->orderTarget = '';
+ else
+ {
+ if ($this->orderTarget)
+ $this->orderTarget .= ', ';
+ $this->orderTarget .= rtrim($key . ' ' . $dir);
+ }
+ $this->refreshOrderClause();
+ return $this;
+ }
- public function groupBy($key)
- {
- $this->clauses[self::CLAUSE_GROUP] = 'GROUP BY ' . $key;
- return $this;
- }
+ public function groupBy($key)
+ {
+ $this->clauses[self::CLAUSE_GROUP] = 'GROUP BY ' . $key;
+ return $this;
+ }
- public function count()
- {
- $query = clone($this);
- return iterator_to_array($query->select(null)->select('COUNT(1) AS c'))[0]['c'];
- }
+ public function count()
+ {
+ $query = clone($this);
+ return iterator_to_array($query->select(null)->select('COUNT(1) AS c'))[0]['c'];
+ }
- protected function init()
- {
- $this->selectTarget = $this->table . '.*';
- $this->refreshBaseClause();
- }
+ protected function init()
+ {
+ $this->selectTarget = $this->table . '.*';
+ $this->refreshBaseClause();
+ }
- private function refreshBaseClause()
- {
- $this->clauses[self::CLAUSE_BASE] = 'SELECT ' . $this->selectTarget . ' FROM ' . $this->table;
- }
+ private function refreshBaseClause()
+ {
+ $this->clauses[self::CLAUSE_BASE] = 'SELECT ' . $this->selectTarget . ' FROM ' . $this->table;
+ }
- private function refreshOrderClause()
- {
- $this->clauses[self::CLAUSE_ORDER] = 'ORDER BY ' . $this->orderTarget;
- }
+ private function refreshOrderClause()
+ {
+ $this->clauses[self::CLAUSE_ORDER] = 'ORDER BY ' . $this->orderTarget;
+ }
- private function refreshLimitClause()
- {
- $sql = '';
- if ($this->limit !== null)
- {
- $sql .= 'LIMIT ' . $this->limit;
- if ($this->offset !== null && $this->offset !== 0)
- $sql .= ' OFFSET ' . intval($this->offset);
- }
- $this->clauses[self::CLAUSE_LIMIT] = $sql;
- }
+ private function refreshLimitClause()
+ {
+ $sql = '';
+ if ($this->limit !== null)
+ {
+ $sql .= 'LIMIT ' . $this->limit;
+ if ($this->offset !== null && $this->offset !== 0)
+ $sql .= ' OFFSET ' . intval($this->offset);
+ }
+ $this->clauses[self::CLAUSE_LIMIT] = $sql;
+ }
}
diff --git a/src/PDOEx/UpdateQuery.php b/src/PDOEx/UpdateQuery.php
index eee43705..28fb05ae 100644
--- a/src/PDOEx/UpdateQuery.php
+++ b/src/PDOEx/UpdateQuery.php
@@ -3,32 +3,32 @@ namespace Szurubooru\PDOEx;
class UpdateQuery extends BaseQuery
{
- private $values = [];
+ private $values = [];
- public function set(array $values)
- {
- $this->values = $values;
- $this->refreshBaseQuery();
- return $this;
- }
+ public function set(array $values)
+ {
+ $this->values = $values;
+ $this->refreshBaseQuery();
+ return $this;
+ }
- public function innerJoin($table, $condition)
- {
- throw new \BadMethodCallException('This makes no sense!');
- }
+ public function innerJoin($table, $condition)
+ {
+ throw new \BadMethodCallException('This makes no sense!');
+ }
- protected function init()
- {
- $this->refreshBaseQuery();
- }
+ protected function init()
+ {
+ $this->refreshBaseQuery();
+ }
- private function refreshBaseQuery()
- {
- $sql = 'UPDATE ' . $this->table;
- $sql .= ' SET ';
- foreach ($this->values as $key => $value)
- $sql .= $key . ' = ' . $this->bind($value) . ', ';
- $sql = substr($sql, 0, -2);
- $this->clauses[self::CLAUSE_BASE] = $sql;
- }
+ private function refreshBaseQuery()
+ {
+ $sql = 'UPDATE ' . $this->table;
+ $sql .= ' SET ';
+ foreach ($this->values as $key => $value)
+ $sql .= $key . ' = ' . $this->bind($value) . ', ';
+ $sql = substr($sql, 0, -2);
+ $this->clauses[self::CLAUSE_BASE] = $sql;
+ }
}
diff --git a/src/Privilege.php b/src/Privilege.php
index 26765ba0..78de4ec0 100644
--- a/src/Privilege.php
+++ b/src/Privilege.php
@@ -3,58 +3,58 @@ namespace Szurubooru;
class Privilege
{
- const REGISTER = 'register';
- const LIST_USERS = 'listUsers';
- const VIEW_USERS = 'viewUsers';
- const VIEW_ALL_EMAIL_ADDRESSES = 'viewAllEmailAddresses';
- const VIEW_ALL_ACCESS_RANKS = 'viewAllAccessRanks';
- const CHANGE_ACCESS_RANK = 'changeAccessRank';
- const CHANGE_OWN_AVATAR_STYLE = 'changeOwnAvatarStyle';
- const CHANGE_OWN_EMAIL_ADDRESS = 'changeOwnEmailAddress';
- const CHANGE_OWN_NAME = 'changeOwnName';
- const CHANGE_OWN_PASSWORD = 'changeOwnPassword';
- const CHANGE_ALL_AVATAR_STYLES = 'changeAllAvatarStyles';
- const CHANGE_ALL_EMAIL_ADDRESSES = 'changeAllEmailAddresses';
- const CHANGE_ALL_NAMES = 'changeAllNames';
- const CHANGE_ALL_PASSWORDS = 'changeAllPasswords';
- const DELETE_OWN_ACCOUNT = 'deleteOwnAccount';
- const DELETE_ALL_ACCOUNTS = 'deleteAllAccounts';
- const BAN_USERS = 'banUsers';
+ const REGISTER = 'register';
+ const LIST_USERS = 'listUsers';
+ const VIEW_USERS = 'viewUsers';
+ const VIEW_ALL_EMAIL_ADDRESSES = 'viewAllEmailAddresses';
+ const VIEW_ALL_ACCESS_RANKS = 'viewAllAccessRanks';
+ const CHANGE_ACCESS_RANK = 'changeAccessRank';
+ const CHANGE_OWN_AVATAR_STYLE = 'changeOwnAvatarStyle';
+ const CHANGE_OWN_EMAIL_ADDRESS = 'changeOwnEmailAddress';
+ const CHANGE_OWN_NAME = 'changeOwnName';
+ const CHANGE_OWN_PASSWORD = 'changeOwnPassword';
+ const CHANGE_ALL_AVATAR_STYLES = 'changeAllAvatarStyles';
+ const CHANGE_ALL_EMAIL_ADDRESSES = 'changeAllEmailAddresses';
+ const CHANGE_ALL_NAMES = 'changeAllNames';
+ const CHANGE_ALL_PASSWORDS = 'changeAllPasswords';
+ const DELETE_OWN_ACCOUNT = 'deleteOwnAccount';
+ const DELETE_ALL_ACCOUNTS = 'deleteAllAccounts';
+ const BAN_USERS = 'banUsers';
- const LIST_POSTS = 'listPosts';
- const VIEW_POSTS = 'viewPosts';
- const UPLOAD_POSTS = 'uploadPosts';
- const UPLOAD_POSTS_ANONYMOUSLY = 'uploadPostsAnonymously';
- const DELETE_POSTS = 'deletePosts';
- const FEATURE_POSTS = 'featurePosts';
- const CHANGE_POST_SAFETY = 'changePostSafety';
- const CHANGE_POST_SOURCE = 'changePostSource';
- const CHANGE_POST_TAGS = 'changePostTags';
- const CHANGE_POST_CONTENT = 'changePostContent';
- const CHANGE_POST_THUMBNAIL = 'changePostThumbnail';
- const CHANGE_POST_RELATIONS = 'changePostRelations';
- const CHANGE_POST_FLAGS = 'changePostFlags';
+ const LIST_POSTS = 'listPosts';
+ const VIEW_POSTS = 'viewPosts';
+ const UPLOAD_POSTS = 'uploadPosts';
+ const UPLOAD_POSTS_ANONYMOUSLY = 'uploadPostsAnonymously';
+ const DELETE_POSTS = 'deletePosts';
+ const FEATURE_POSTS = 'featurePosts';
+ const CHANGE_POST_SAFETY = 'changePostSafety';
+ const CHANGE_POST_SOURCE = 'changePostSource';
+ const CHANGE_POST_TAGS = 'changePostTags';
+ const CHANGE_POST_CONTENT = 'changePostContent';
+ const CHANGE_POST_THUMBNAIL = 'changePostThumbnail';
+ const CHANGE_POST_RELATIONS = 'changePostRelations';
+ const CHANGE_POST_FLAGS = 'changePostFlags';
- const ADD_POST_NOTES = 'addPostNotes';
- const EDIT_POST_NOTES = 'editPostNotes';
- const DELETE_POST_NOTES = 'deletePostNotes';
+ const ADD_POST_NOTES = 'addPostNotes';
+ const EDIT_POST_NOTES = 'editPostNotes';
+ const DELETE_POST_NOTES = 'deletePostNotes';
- const LIST_TAGS = 'listTags';
- const MASS_TAG = 'massTag';
- const CHANGE_TAG_NAME = 'changeTagName';
- const CHANGE_TAG_CATEGORY = 'changeTagCategory';
- const CHANGE_TAG_IMPLICATIONS = 'changeTagImplications';
- const CHANGE_TAG_SUGGESTIONS = 'changeTagSuggestions';
- const BAN_TAGS = 'banTags';
- const DELETE_TAGS = 'deleteTags';
- const MERGE_TAGS = 'mergeTags';
+ const LIST_TAGS = 'listTags';
+ const MASS_TAG = 'massTag';
+ const CHANGE_TAG_NAME = 'changeTagName';
+ const CHANGE_TAG_CATEGORY = 'changeTagCategory';
+ const CHANGE_TAG_IMPLICATIONS = 'changeTagImplications';
+ const CHANGE_TAG_SUGGESTIONS = 'changeTagSuggestions';
+ const BAN_TAGS = 'banTags';
+ const DELETE_TAGS = 'deleteTags';
+ const MERGE_TAGS = 'mergeTags';
- const LIST_COMMENTS = 'listComments';
- const ADD_COMMENTS = 'addComments';
- const EDIT_OWN_COMMENTS = 'editOwnComments';
- const EDIT_ALL_COMMENTS = 'editAllComments';
- const DELETE_OWN_COMMENTS = 'deleteOwnComments';
- const DELETE_ALL_COMMENTS = 'deleteAllComments';
+ const LIST_COMMENTS = 'listComments';
+ const ADD_COMMENTS = 'addComments';
+ const EDIT_OWN_COMMENTS = 'editOwnComments';
+ const EDIT_ALL_COMMENTS = 'editAllComments';
+ const DELETE_OWN_COMMENTS = 'deleteOwnComments';
+ const DELETE_ALL_COMMENTS = 'deleteAllComments';
- const VIEW_HISTORY = 'viewHistory';
+ const VIEW_HISTORY = 'viewHistory';
}
diff --git a/src/RouteRepository.php b/src/RouteRepository.php
index dc754041..5e964eee 100644
--- a/src/RouteRepository.php
+++ b/src/RouteRepository.php
@@ -3,27 +3,27 @@ namespace Szurubooru;
class RouteRepository
{
- private $routes = [];
+ private $routes = [];
- public function __construct(array $routes)
- {
- $this->routes = $routes;
- }
+ public function __construct(array $routes)
+ {
+ $this->routes = $routes;
+ }
- public function getRoutes()
- {
- return $this->routes;
- }
+ public function getRoutes()
+ {
+ return $this->routes;
+ }
- public function injectRoutes(Router $router)
- {
- foreach ($this->routes as $route)
- {
- foreach ($route->getMethods() as $method)
- {
- $method = strtolower($method);
- $router->$method($route->getUrl(), [$route, 'work']);
- }
- }
- }
+ public function injectRoutes(Router $router)
+ {
+ foreach ($this->routes as $route)
+ {
+ foreach ($route->getMethods() as $method)
+ {
+ $method = strtolower($method);
+ $router->$method($route->getUrl(), [$route, 'work']);
+ }
+ }
+ }
}
diff --git a/src/Router.php b/src/Router.php
index 7fb5a620..b3b41b19 100644
--- a/src/Router.php
+++ b/src/Router.php
@@ -3,55 +3,55 @@ namespace Szurubooru;
class Router
{
- private $routes;
+ private $routes;
- public function get($url, callable $function)
- {
- $this->inject('GET', $url, $function);
- }
+ public function get($url, callable $function)
+ {
+ $this->inject('GET', $url, $function);
+ }
- public function post($url, callable $function)
- {
- $this->inject('POST', $url, $function);
- }
+ public function post($url, callable $function)
+ {
+ $this->inject('POST', $url, $function);
+ }
- public function put($url, callable $function)
- {
- $this->inject('PUT', $url, $function);
- }
+ public function put($url, callable $function)
+ {
+ $this->inject('PUT', $url, $function);
+ }
- public function delete($url, callable $function)
- {
- $this->inject('DELETE', $url, $function);
- }
+ public function delete($url, callable $function)
+ {
+ $this->inject('DELETE', $url, $function);
+ }
- public function handle($method, $request)
- {
- if (!isset($this->routes[$method]))
- throw new \DomainException('Unhandled request method: ' . $method);
+ public function handle($method, $request)
+ {
+ if (!isset($this->routes[$method]))
+ throw new \DomainException('Unhandled request method: ' . $method);
- $request = trim($request, '/');
- foreach ($this->routes[$method] as $url => $callback)
- {
- if (!preg_match(self::getRegex($url), $request, $matches))
- continue;
+ $request = trim($request, '/');
+ foreach ($this->routes[$method] as $url => $callback)
+ {
+ if (!preg_match(self::getRegex($url), $request, $matches))
+ continue;
- return $callback($matches);
- }
+ return $callback($matches);
+ }
- throw new \DomainException('Unhandled request address: ' . $request);
- }
+ throw new \DomainException('Unhandled request address: ' . $request);
+ }
- private function inject($method, $url, callable $function)
- {
- if (!isset($this->routes[$method]))
- $this->routes[$method] = [];
- $this->routes[$method][$url] = $function;
- }
+ private function inject($method, $url, callable $function)
+ {
+ if (!isset($this->routes[$method]))
+ $this->routes[$method] = [];
+ $this->routes[$method][$url] = $function;
+ }
- private static function getRegex($url)
- {
- $quotedQuery = preg_quote(trim($url, '/'), '/');
- return '/^' . preg_replace('/\\\?\:([a-zA-Z_-]*)/', '(?P<\1>[^\/]+)', $quotedQuery) . '$/i';
- }
+ private static function getRegex($url)
+ {
+ $quotedQuery = preg_quote(trim($url, '/'), '/');
+ return '/^' . preg_replace('/\\\?\:([a-zA-Z_-]*)/', '(?P<\1>[^\/]+)', $quotedQuery) . '$/i';
+ }
}
diff --git a/src/Routes/AbstractRoute.php b/src/Routes/AbstractRoute.php
index 33a87edc..a2ec0ebd 100644
--- a/src/Routes/AbstractRoute.php
+++ b/src/Routes/AbstractRoute.php
@@ -3,9 +3,9 @@ namespace Szurubooru\Routes;
abstract class AbstractRoute
{
- public abstract function getMethods();
+ public abstract function getMethods();
- public abstract function getUrl();
+ public abstract function getUrl();
- public abstract function work($args);
+ public abstract function work($args);
}
diff --git a/src/Routes/Comments/AbstractCommentRoute.php b/src/Routes/Comments/AbstractCommentRoute.php
index 2136fd3e..2ac28244 100644
--- a/src/Routes/Comments/AbstractCommentRoute.php
+++ b/src/Routes/Comments/AbstractCommentRoute.php
@@ -5,11 +5,11 @@ use Szurubooru\ViewProxies\CommentViewProxy;
abstract class AbstractCommentRoute extends AbstractRoute
{
- protected function getCommentsFetchConfig()
- {
- return
- [
- CommentViewProxy::FETCH_OWN_SCORE => true,
- ];
- }
+ protected function getCommentsFetchConfig()
+ {
+ return
+ [
+ CommentViewProxy::FETCH_OWN_SCORE => true,
+ ];
+ }
}
diff --git a/src/Routes/Comments/AddComment.php b/src/Routes/Comments/AddComment.php
index 8cf76a65..4d013ae3 100644
--- a/src/Routes/Comments/AddComment.php
+++ b/src/Routes/Comments/AddComment.php
@@ -10,45 +10,45 @@ use Szurubooru\ViewProxies\PostViewProxy;
class AddComment extends AbstractCommentRoute
{
- private $privilegeService;
- private $postService;
- private $commentService;
- private $commentViewProxy;
- private $postViewProxy;
- private $inputReader;
+ private $privilegeService;
+ private $postService;
+ private $commentService;
+ private $commentViewProxy;
+ private $postViewProxy;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- CommentService $commentService,
- CommentViewProxy $commentViewProxy,
- PostViewProxy $postViewProxy,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->commentService = $commentService;
- $this->commentViewProxy = $commentViewProxy;
- $this->postViewProxy = $postViewProxy;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ CommentService $commentService,
+ CommentViewProxy $commentViewProxy,
+ PostViewProxy $postViewProxy,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->commentService = $commentService;
+ $this->commentViewProxy = $commentViewProxy;
+ $this->postViewProxy = $postViewProxy;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['POST'];
- }
+ public function getMethods()
+ {
+ return ['POST'];
+ }
- public function getUrl()
- {
- return '/api/comments/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/comments/:postNameOrId';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::ADD_COMMENTS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::ADD_COMMENTS);
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $comment = $this->commentService->createComment($post, $this->inputReader->text);
- return $this->commentViewProxy->fromEntity($comment, $this->getCommentsFetchConfig());
- }
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $comment = $this->commentService->createComment($post, $this->inputReader->text);
+ return $this->commentViewProxy->fromEntity($comment, $this->getCommentsFetchConfig());
+ }
}
diff --git a/src/Routes/Comments/DeleteComment.php b/src/Routes/Comments/DeleteComment.php
index c17c3b1c..c6701a6f 100644
--- a/src/Routes/Comments/DeleteComment.php
+++ b/src/Routes/Comments/DeleteComment.php
@@ -10,48 +10,48 @@ use Szurubooru\ViewProxies\PostViewProxy;
class DeleteComment extends AbstractCommentRoute
{
- private $privilegeService;
- private $postService;
- private $commentService;
- private $commentViewProxy;
- private $postViewProxy;
- private $inputReader;
+ private $privilegeService;
+ private $postService;
+ private $commentService;
+ private $commentViewProxy;
+ private $postViewProxy;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- CommentService $commentService,
- CommentViewProxy $commentViewProxy,
- PostViewProxy $postViewProxy,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->commentService = $commentService;
- $this->commentViewProxy = $commentViewProxy;
- $this->postViewProxy = $postViewProxy;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ CommentService $commentService,
+ CommentViewProxy $commentViewProxy,
+ PostViewProxy $postViewProxy,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->commentService = $commentService;
+ $this->commentViewProxy = $commentViewProxy;
+ $this->postViewProxy = $postViewProxy;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['DELETE'];
- }
+ public function getMethods()
+ {
+ return ['DELETE'];
+ }
- public function getUrl()
- {
- return '/api/comments/:commentId';
- }
+ public function getUrl()
+ {
+ return '/api/comments/:commentId';
+ }
- public function work($args)
- {
- $comment = $this->commentService->getById($args['commentId']);
+ public function work($args)
+ {
+ $comment = $this->commentService->getById($args['commentId']);
- $this->privilegeService->assertPrivilege(
- $this->privilegeService->isLoggedIn($comment->getUser())
- ? Privilege::DELETE_OWN_COMMENTS
- : Privilege::DELETE_ALL_COMMENTS);
+ $this->privilegeService->assertPrivilege(
+ $this->privilegeService->isLoggedIn($comment->getUser())
+ ? Privilege::DELETE_OWN_COMMENTS
+ : Privilege::DELETE_ALL_COMMENTS);
- return $this->commentService->deleteComment($comment);
- }
+ return $this->commentService->deleteComment($comment);
+ }
}
diff --git a/src/Routes/Comments/EditComment.php b/src/Routes/Comments/EditComment.php
index 26072180..96ea52a1 100644
--- a/src/Routes/Comments/EditComment.php
+++ b/src/Routes/Comments/EditComment.php
@@ -10,49 +10,49 @@ use Szurubooru\ViewProxies\PostViewProxy;
class EditComment extends AbstractCommentRoute
{
- private $privilegeService;
- private $postService;
- private $commentService;
- private $commentViewProxy;
- private $postViewProxy;
- private $inputReader;
+ private $privilegeService;
+ private $postService;
+ private $commentService;
+ private $commentViewProxy;
+ private $postViewProxy;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- CommentService $commentService,
- CommentViewProxy $commentViewProxy,
- PostViewProxy $postViewProxy,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->commentService = $commentService;
- $this->commentViewProxy = $commentViewProxy;
- $this->postViewProxy = $postViewProxy;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ CommentService $commentService,
+ CommentViewProxy $commentViewProxy,
+ PostViewProxy $postViewProxy,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->commentService = $commentService;
+ $this->commentViewProxy = $commentViewProxy;
+ $this->postViewProxy = $postViewProxy;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['PUT'];
- }
+ public function getMethods()
+ {
+ return ['PUT'];
+ }
- public function getUrl()
- {
- return '/api/comments/:commentId';
- }
+ public function getUrl()
+ {
+ return '/api/comments/:commentId';
+ }
- public function work($args)
- {
- $comment = $this->commentService->getById($args['commentId']);
+ public function work($args)
+ {
+ $comment = $this->commentService->getById($args['commentId']);
- $this->privilegeService->assertPrivilege(
- ($comment->getUser() && $this->privilegeService->isLoggedIn($comment->getUser()))
- ? Privilege::EDIT_OWN_COMMENTS
- : Privilege::EDIT_ALL_COMMENTS);
+ $this->privilegeService->assertPrivilege(
+ ($comment->getUser() && $this->privilegeService->isLoggedIn($comment->getUser()))
+ ? Privilege::EDIT_OWN_COMMENTS
+ : Privilege::EDIT_ALL_COMMENTS);
- $comment = $this->commentService->updateComment($comment, $this->inputReader->text);
- return $this->commentViewProxy->fromEntity($comment, $this->getCommentsFetchConfig());
- }
+ $comment = $this->commentService->updateComment($comment, $this->inputReader->text);
+ return $this->commentViewProxy->fromEntity($comment, $this->getCommentsFetchConfig());
+ }
}
diff --git a/src/Routes/Comments/GetComments.php b/src/Routes/Comments/GetComments.php
index 55e86ee9..be3c4f40 100644
--- a/src/Routes/Comments/GetComments.php
+++ b/src/Routes/Comments/GetComments.php
@@ -13,75 +13,75 @@ use Szurubooru\ViewProxies\PostViewProxy;
class GetComments extends AbstractCommentRoute
{
- private $privilegeService;
- private $postService;
- private $commentService;
- private $commentViewProxy;
- private $postViewProxy;
- private $inputReader;
+ private $privilegeService;
+ private $postService;
+ private $commentService;
+ private $commentViewProxy;
+ private $postViewProxy;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- CommentService $commentService,
- CommentViewProxy $commentViewProxy,
- PostViewProxy $postViewProxy,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->commentService = $commentService;
- $this->commentViewProxy = $commentViewProxy;
- $this->postViewProxy = $postViewProxy;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ CommentService $commentService,
+ CommentViewProxy $commentViewProxy,
+ PostViewProxy $postViewProxy,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->commentService = $commentService;
+ $this->commentViewProxy = $commentViewProxy;
+ $this->postViewProxy = $postViewProxy;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/comments';
- }
+ public function getUrl()
+ {
+ return '/api/comments';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::LIST_COMMENTS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::LIST_COMMENTS);
- $filter = new PostFilter();
- $filter->setPageSize(10);
- $filter->setPageNumber($this->inputReader->page);
- $filter->setOrder([
- PostFilter::ORDER_LAST_COMMENT_TIME =>
- PostFilter::ORDER_DESC]);
+ $filter = new PostFilter();
+ $filter->setPageSize(10);
+ $filter->setPageNumber($this->inputReader->page);
+ $filter->setOrder([
+ PostFilter::ORDER_LAST_COMMENT_TIME =>
+ PostFilter::ORDER_DESC]);
- $this->postService->decorateFilterFromBrowsingSettings($filter);
+ $this->postService->decorateFilterFromBrowsingSettings($filter);
- $requirement = new Requirement();
- $requirement->setValue(new RequirementRangedValue());
- $requirement->getValue()->setMinValue(1);
- $requirement->setType(PostFilter::REQUIREMENT_COMMENT_COUNT);
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setValue(new RequirementRangedValue());
+ $requirement->getValue()->setMinValue(1);
+ $requirement->setType(PostFilter::REQUIREMENT_COMMENT_COUNT);
+ $filter->addRequirement($requirement);
- $result = $this->postService->getFiltered($filter);
- $posts = $result->getEntities();
+ $result = $this->postService->getFiltered($filter);
+ $posts = $result->getEntities();
- $data = [];
- foreach ($posts as $post)
- {
- $data[] = [
- 'post' => $this->postViewProxy->fromEntity($post),
- 'comments' => $this->commentViewProxy->fromArray(
- array_reverse($this->commentService->getByPost($post)),
- $this->getCommentsFetchConfig()),
- ];
- }
+ $data = [];
+ foreach ($posts as $post)
+ {
+ $data[] = [
+ 'post' => $this->postViewProxy->fromEntity($post),
+ 'comments' => $this->commentViewProxy->fromArray(
+ array_reverse($this->commentService->getByPost($post)),
+ $this->getCommentsFetchConfig()),
+ ];
+ }
- return [
- 'data' => $data,
- 'pageSize' => $result->getPageSize(),
- 'totalRecords' => $result->getTotalRecords()];
- }
+ return [
+ 'data' => $data,
+ 'pageSize' => $result->getPageSize(),
+ 'totalRecords' => $result->getTotalRecords()];
+ }
}
diff --git a/src/Routes/Comments/GetPostComments.php b/src/Routes/Comments/GetPostComments.php
index 7687d137..5052cdf2 100644
--- a/src/Routes/Comments/GetPostComments.php
+++ b/src/Routes/Comments/GetPostComments.php
@@ -13,56 +13,56 @@ use Szurubooru\ViewProxies\PostViewProxy;
class GetPostComments extends AbstractCommentRoute
{
- private $privilegeService;
- private $postService;
- private $commentService;
- private $commentViewProxy;
- private $postViewProxy;
- private $inputReader;
+ private $privilegeService;
+ private $postService;
+ private $commentService;
+ private $commentViewProxy;
+ private $postViewProxy;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- CommentService $commentService,
- CommentViewProxy $commentViewProxy,
- PostViewProxy $postViewProxy,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->commentService = $commentService;
- $this->commentViewProxy = $commentViewProxy;
- $this->postViewProxy = $postViewProxy;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ CommentService $commentService,
+ CommentViewProxy $commentViewProxy,
+ PostViewProxy $postViewProxy,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->commentService = $commentService;
+ $this->commentViewProxy = $commentViewProxy;
+ $this->postViewProxy = $postViewProxy;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/comments/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/comments/:postNameOrId';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::LIST_COMMENTS);
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::LIST_COMMENTS);
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $filter = new CommentFilter();
- $filter->setOrder([
- CommentFilter::ORDER_ID =>
- CommentFilter::ORDER_ASC]);
+ $filter = new CommentFilter();
+ $filter->setOrder([
+ CommentFilter::ORDER_ID =>
+ CommentFilter::ORDER_ASC]);
- $requirement = new Requirement();
- $requirement->setValue(new RequirementSingleValue($post->getId()));
- $requirement->setType(CommentFilter::REQUIREMENT_POST_ID);
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setValue(new RequirementSingleValue($post->getId()));
+ $requirement->setType(CommentFilter::REQUIREMENT_POST_ID);
+ $filter->addRequirement($requirement);
- $result = $this->commentService->getFiltered($filter);
- $entities = $this->commentViewProxy->fromArray($result->getEntities(), $this->getCommentsFetchConfig());
- return ['data' => $entities];
- }
+ $result = $this->commentService->getFiltered($filter);
+ $entities = $this->commentViewProxy->fromArray($result->getEntities(), $this->getCommentsFetchConfig());
+ return ['data' => $entities];
+ }
}
diff --git a/src/Routes/Favorites/AddToFavorites.php b/src/Routes/Favorites/AddToFavorites.php
index a1527f53..a6c8ef0c 100644
--- a/src/Routes/Favorites/AddToFavorites.php
+++ b/src/Routes/Favorites/AddToFavorites.php
@@ -9,44 +9,44 @@ use Szurubooru\ViewProxies\UserViewProxy;
class AddToFavorites extends AbstractRoute
{
- private $privilegeService;
- private $authService;
- private $postService;
- private $favoritesService;
- private $userViewProxy;
+ private $privilegeService;
+ private $authService;
+ private $postService;
+ private $favoritesService;
+ private $userViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- PostService $postService,
- FavoritesService $favoritesService,
- UserViewProxy $userViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->authService = $authService;
- $this->postService = $postService;
- $this->favoritesService = $favoritesService;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ PostService $postService,
+ FavoritesService $favoritesService,
+ UserViewProxy $userViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->authService = $authService;
+ $this->postService = $postService;
+ $this->favoritesService = $favoritesService;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId/favorites';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId/favorites';
+ }
- public function work($args)
- {
- $this->privilegeService->assertLoggedIn();
- $user = $this->authService->getLoggedInUser();
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $this->favoritesService->addFavorite($user, $post);
+ public function work($args)
+ {
+ $this->privilegeService->assertLoggedIn();
+ $user = $this->authService->getLoggedInUser();
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $this->favoritesService->addFavorite($user, $post);
- $users = $this->favoritesService->getFavoriteUsers($post);
- return ['data' => $this->userViewProxy->fromArray($users)];
- }
+ $users = $this->favoritesService->getFavoriteUsers($post);
+ return ['data' => $this->userViewProxy->fromArray($users)];
+ }
}
diff --git a/src/Routes/Favorites/GetFavoriteUsers.php b/src/Routes/Favorites/GetFavoriteUsers.php
index 5eacd75e..9064b4f3 100644
--- a/src/Routes/Favorites/GetFavoriteUsers.php
+++ b/src/Routes/Favorites/GetFavoriteUsers.php
@@ -9,40 +9,40 @@ use Szurubooru\ViewProxies\UserViewProxy;
class GetFavoriteUsers extends AbstractRoute
{
- private $privilegeService;
- private $authService;
- private $postService;
- private $favoritesService;
- private $userViewProxy;
+ private $privilegeService;
+ private $authService;
+ private $postService;
+ private $favoritesService;
+ private $userViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- PostService $postService,
- FavoritesService $favoritesService,
- UserViewProxy $userViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->authService = $authService;
- $this->postService = $postService;
- $this->favoritesService = $favoritesService;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ PostService $postService,
+ FavoritesService $favoritesService,
+ UserViewProxy $userViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->authService = $authService;
+ $this->postService = $postService;
+ $this->favoritesService = $favoritesService;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId/favorites';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId/favorites';
+ }
- public function work($args)
- {
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $users = $this->favoritesService->getFavoriteUsers($post);
- return ['data' => $this->userViewProxy->fromArray($users)];
- }
+ public function work($args)
+ {
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $users = $this->favoritesService->getFavoriteUsers($post);
+ return ['data' => $this->userViewProxy->fromArray($users)];
+ }
}
diff --git a/src/Routes/Favorites/RemoveFromFavorites.php b/src/Routes/Favorites/RemoveFromFavorites.php
index 7754edca..2cd84a6e 100644
--- a/src/Routes/Favorites/RemoveFromFavorites.php
+++ b/src/Routes/Favorites/RemoveFromFavorites.php
@@ -9,44 +9,44 @@ use Szurubooru\ViewProxies\UserViewProxy;
class RemoveFromFavorites extends AbstractRoute
{
- private $privilegeService;
- private $authService;
- private $postService;
- private $favoritesService;
- private $userViewProxy;
+ private $privilegeService;
+ private $authService;
+ private $postService;
+ private $favoritesService;
+ private $userViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- PostService $postService,
- FavoritesService $favoritesService,
- UserViewProxy $userViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->authService = $authService;
- $this->postService = $postService;
- $this->favoritesService = $favoritesService;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ PostService $postService,
+ FavoritesService $favoritesService,
+ UserViewProxy $userViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->authService = $authService;
+ $this->postService = $postService;
+ $this->favoritesService = $favoritesService;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['DELETE'];
- }
+ public function getMethods()
+ {
+ return ['DELETE'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId/favorites';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId/favorites';
+ }
- public function work($args)
- {
- $this->privilegeService->assertLoggedIn();
- $user = $this->authService->getLoggedInUser();
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $this->favoritesService->deleteFavorite($user, $post);
+ public function work($args)
+ {
+ $this->privilegeService->assertLoggedIn();
+ $user = $this->authService->getLoggedInUser();
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $this->favoritesService->deleteFavorite($user, $post);
- $users = $this->favoritesService->getFavoriteUsers($post);
- return ['data' => $this->userViewProxy->fromArray($users)];
- }
+ $users = $this->favoritesService->getFavoriteUsers($post);
+ return ['data' => $this->userViewProxy->fromArray($users)];
+ }
}
diff --git a/src/Routes/GetGlobals.php b/src/Routes/GetGlobals.php
index 6afe84c4..c5edbaba 100644
--- a/src/Routes/GetGlobals.php
+++ b/src/Routes/GetGlobals.php
@@ -4,31 +4,31 @@ use Szurubooru\Dao\GlobalParamDao;
class GetGlobals extends AbstractRoute
{
- private $globalParamDao;
+ private $globalParamDao;
- public function __construct(GlobalParamDao $globalParamDao)
- {
- $this->globalParamDao = $globalParamDao;
- }
+ public function __construct(GlobalParamDao $globalParamDao)
+ {
+ $this->globalParamDao = $globalParamDao;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/globals';
- }
+ public function getUrl()
+ {
+ return '/api/globals';
+ }
- public function work($args)
- {
- $globals = $this->globalParamDao->findAll();
- $result = [];
- foreach ($globals as $global)
- {
- $result[$global->getKey()] = $global->getValue();
- }
- return $result;
- }
+ public function work($args)
+ {
+ $globals = $this->globalParamDao->findAll();
+ $result = [];
+ foreach ($globals as $global)
+ {
+ $result[$global->getKey()] = $global->getValue();
+ }
+ return $result;
+ }
}
diff --git a/src/Routes/GetHistory.php b/src/Routes/GetHistory.php
index 3604b49b..684ea246 100644
--- a/src/Routes/GetHistory.php
+++ b/src/Routes/GetHistory.php
@@ -10,47 +10,47 @@ use Szurubooru\ViewProxies\SnapshotViewProxy;
class GetHistory extends AbstractRoute
{
- private $historyService;
- private $privilegeService;
- private $snapshotSearchParser;
- private $inputReader;
- private $snapshotViewProxy;
+ private $historyService;
+ private $privilegeService;
+ private $snapshotSearchParser;
+ private $inputReader;
+ private $snapshotViewProxy;
- public function __construct(
- HistoryService $historyService,
- PrivilegeService $privilegeService,
- SnapshotSearchParser $snapshotSearchParser,
- InputReader $inputReader,
- SnapshotViewProxy $snapshotViewProxy)
- {
- $this->historyService = $historyService;
- $this->privilegeService = $privilegeService;
- $this->snapshotSearchParser = $snapshotSearchParser;
- $this->inputReader = $inputReader;
- $this->snapshotViewProxy = $snapshotViewProxy;
- }
+ public function __construct(
+ HistoryService $historyService,
+ PrivilegeService $privilegeService,
+ SnapshotSearchParser $snapshotSearchParser,
+ InputReader $inputReader,
+ SnapshotViewProxy $snapshotViewProxy)
+ {
+ $this->historyService = $historyService;
+ $this->privilegeService = $privilegeService;
+ $this->snapshotSearchParser = $snapshotSearchParser;
+ $this->inputReader = $inputReader;
+ $this->snapshotViewProxy = $snapshotViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/history';
- }
+ public function getUrl()
+ {
+ return '/api/history';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::VIEW_HISTORY);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::VIEW_HISTORY);
- $filter = $this->snapshotSearchParser->createFilterFromInputReader($this->inputReader);
- $filter->setPageSize(50);
- $result = $this->historyService->getFiltered($filter);
- $entities = $this->snapshotViewProxy->fromArray($result->getEntities());
- return [
- 'data' => $entities,
- 'pageSize' => $result->getPageSize(),
- 'totalRecords' => $result->getTotalRecords()];
- }
+ $filter = $this->snapshotSearchParser->createFilterFromInputReader($this->inputReader);
+ $filter->setPageSize(50);
+ $result = $this->historyService->getFiltered($filter);
+ $entities = $this->snapshotViewProxy->fromArray($result->getEntities());
+ return [
+ 'data' => $entities,
+ 'pageSize' => $result->getPageSize(),
+ 'totalRecords' => $result->getTotalRecords()];
+ }
}
diff --git a/src/Routes/Login.php b/src/Routes/Login.php
index 5fac1b85..61923883 100644
--- a/src/Routes/Login.php
+++ b/src/Routes/Login.php
@@ -12,73 +12,73 @@ use Szurubooru\ViewProxies\UserViewProxy;
class Login extends AbstractRoute
{
- private $authService;
- private $userService;
- private $tokenService;
- private $privilegeService;
- private $inputReader;
- private $userViewProxy;
- private $tokenViewProxy;
+ private $authService;
+ private $userService;
+ private $tokenService;
+ private $privilegeService;
+ private $inputReader;
+ private $userViewProxy;
+ private $tokenViewProxy;
- public function __construct(
- AuthService $authService,
- UserService $userService,
- TokenService $tokenService,
- PrivilegeService $privilegeService,
- InputReader $inputReader,
- UserViewProxy $userViewProxy,
- TokenViewProxy $tokenViewProxy)
- {
- $this->authService = $authService;
- $this->userService = $userService;
- $this->tokenService = $tokenService;
- $this->privilegeService = $privilegeService;
- $this->inputReader = $inputReader;
- $this->userViewProxy = $userViewProxy;
- $this->tokenViewProxy = $tokenViewProxy;
- }
+ public function __construct(
+ AuthService $authService,
+ UserService $userService,
+ TokenService $tokenService,
+ PrivilegeService $privilegeService,
+ InputReader $inputReader,
+ UserViewProxy $userViewProxy,
+ TokenViewProxy $tokenViewProxy)
+ {
+ $this->authService = $authService;
+ $this->userService = $userService;
+ $this->tokenService = $tokenService;
+ $this->privilegeService = $privilegeService;
+ $this->inputReader = $inputReader;
+ $this->userViewProxy = $userViewProxy;
+ $this->tokenViewProxy = $tokenViewProxy;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/login';
- }
+ public function getUrl()
+ {
+ return '/api/login';
+ }
- public function work($args)
- {
- if (isset($this->inputReader->userNameOrEmail) && isset($this->inputReader->password))
- {
- $formData = new LoginFormData($this->inputReader);
- $this->authService->loginFromCredentials($formData);
+ public function work($args)
+ {
+ if (isset($this->inputReader->userNameOrEmail) && isset($this->inputReader->password))
+ {
+ $formData = new LoginFormData($this->inputReader);
+ $this->authService->loginFromCredentials($formData);
- $user = $this->authService->getLoggedInUser();
- $this->userService->updateUserLastLoginTime($user);
- }
- elseif (isset($this->inputReader->token))
- {
- $token = $this->tokenService->getByName($this->inputReader->token);
- $this->authService->loginFromToken($token);
+ $user = $this->authService->getLoggedInUser();
+ $this->userService->updateUserLastLoginTime($user);
+ }
+ elseif (isset($this->inputReader->token))
+ {
+ $token = $this->tokenService->getByName($this->inputReader->token);
+ $this->authService->loginFromToken($token);
- $user = $this->authService->getLoggedInUser();
- $isFromCookie = boolval($this->inputReader->isFromCookie);
- if ($isFromCookie)
- $this->userService->updateUserLastLoginTime($user);
- }
- else
- {
- $this->authService->loginAnonymous();
- $user = $this->authService->getLoggedInUser();
- }
+ $user = $this->authService->getLoggedInUser();
+ $isFromCookie = boolval($this->inputReader->isFromCookie);
+ if ($isFromCookie)
+ $this->userService->updateUserLastLoginTime($user);
+ }
+ else
+ {
+ $this->authService->loginAnonymous();
+ $user = $this->authService->getLoggedInUser();
+ }
- return
- [
- 'token' => $this->tokenViewProxy->fromEntity($this->authService->getLoginToken()),
- 'user' => $this->userViewProxy->fromEntity($user),
- 'privileges' => $this->privilegeService->getCurrentPrivileges(),
- ];
- }
+ return
+ [
+ 'token' => $this->tokenViewProxy->fromEntity($this->authService->getLoginToken()),
+ 'user' => $this->userViewProxy->fromEntity($user),
+ 'privileges' => $this->privilegeService->getCurrentPrivileges(),
+ ];
+ }
}
diff --git a/src/Routes/Posts/AbstractPostRoute.php b/src/Routes/Posts/AbstractPostRoute.php
index 7b97bd3f..05b57bea 100644
--- a/src/Routes/Posts/AbstractPostRoute.php
+++ b/src/Routes/Posts/AbstractPostRoute.php
@@ -5,25 +5,25 @@ use Szurubooru\ViewProxies\PostViewProxy;
abstract class AbstractPostRoute extends AbstractRoute
{
- protected function getFullFetchConfig()
- {
- return
- [
- PostViewProxy::FETCH_RELATIONS => true,
- PostViewProxy::FETCH_TAGS => true,
- PostViewProxy::FETCH_USER => true,
- PostViewProxy::FETCH_HISTORY => true,
- PostViewProxy::FETCH_OWN_SCORE => true,
- PostViewProxy::FETCH_FAVORITES => true,
- PostViewProxy::FETCH_NOTES => true,
- ];
- }
+ protected function getFullFetchConfig()
+ {
+ return
+ [
+ PostViewProxy::FETCH_RELATIONS => true,
+ PostViewProxy::FETCH_TAGS => true,
+ PostViewProxy::FETCH_USER => true,
+ PostViewProxy::FETCH_HISTORY => true,
+ PostViewProxy::FETCH_OWN_SCORE => true,
+ PostViewProxy::FETCH_FAVORITES => true,
+ PostViewProxy::FETCH_NOTES => true,
+ ];
+ }
- protected function getLightFetchConfig()
- {
- return
- [
- PostViewProxy::FETCH_TAGS => true,
- ];
- }
+ protected function getLightFetchConfig()
+ {
+ return
+ [
+ PostViewProxy::FETCH_TAGS => true,
+ ];
+ }
}
diff --git a/src/Routes/Posts/CreatePost.php b/src/Routes/Posts/CreatePost.php
index d7f12406..de757cf4 100644
--- a/src/Routes/Posts/CreatePost.php
+++ b/src/Routes/Posts/CreatePost.php
@@ -9,44 +9,44 @@ use Szurubooru\ViewProxies\PostViewProxy;
class CreatePost extends AbstractPostRoute
{
- private $privilegeService;
- private $postService;
- private $inputReader;
- private $postViewProxy;
+ private $privilegeService;
+ private $postService;
+ private $inputReader;
+ private $postViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- InputReader $inputReader,
- PostViewProxy $postViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->inputReader = $inputReader;
- $this->postViewProxy = $postViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ InputReader $inputReader,
+ PostViewProxy $postViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->inputReader = $inputReader;
+ $this->postViewProxy = $postViewProxy;
+ }
- public function getMethods()
- {
- return ['POST'];
- }
+ public function getMethods()
+ {
+ return ['POST'];
+ }
- public function getUrl()
- {
- return '/api/posts';
- }
+ public function getUrl()
+ {
+ return '/api/posts';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::UPLOAD_POSTS);
- $formData = new UploadFormData($this->inputReader);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::UPLOAD_POSTS);
+ $formData = new UploadFormData($this->inputReader);
- $this->privilegeService->assertPrivilege(Privilege::UPLOAD_POSTS);
+ $this->privilegeService->assertPrivilege(Privilege::UPLOAD_POSTS);
- if ($formData->anonymous)
- $this->privilegeService->assertPrivilege(Privilege::UPLOAD_POSTS_ANONYMOUSLY);
+ if ($formData->anonymous)
+ $this->privilegeService->assertPrivilege(Privilege::UPLOAD_POSTS_ANONYMOUSLY);
- $post = $this->postService->createPost($formData);
- return $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig());
- }
+ $post = $this->postService->createPost($formData);
+ return $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig());
+ }
}
diff --git a/src/Routes/Posts/DeletePost.php b/src/Routes/Posts/DeletePost.php
index 24084f74..6b83861c 100644
--- a/src/Routes/Posts/DeletePost.php
+++ b/src/Routes/Posts/DeletePost.php
@@ -6,32 +6,32 @@ use Szurubooru\Services\PrivilegeService;
class DeletePost extends AbstractPostRoute
{
- private $privilegeService;
- private $postService;
+ private $privilegeService;
+ private $postService;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ }
- public function getMethods()
- {
- return ['DELETE'];
- }
+ public function getMethods()
+ {
+ return ['DELETE'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::DELETE_POSTS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::DELETE_POSTS);
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $this->postService->deletePost($post);
- }
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $this->postService->deletePost($post);
+ }
}
diff --git a/src/Routes/Posts/FeaturePost.php b/src/Routes/Posts/FeaturePost.php
index bb84e1c2..aa5ab365 100644
--- a/src/Routes/Posts/FeaturePost.php
+++ b/src/Routes/Posts/FeaturePost.php
@@ -7,35 +7,35 @@ use Szurubooru\Services\PrivilegeService;
class FeaturePost extends AbstractPostRoute
{
- private $privilegeService;
- private $postService;
- private $postFeatureService;
+ private $privilegeService;
+ private $postService;
+ private $postFeatureService;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- PostFeatureService $postFeatureService)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->postFeatureService = $postFeatureService;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ PostFeatureService $postFeatureService)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->postFeatureService = $postFeatureService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId/feature';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId/feature';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::FEATURE_POSTS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::FEATURE_POSTS);
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $this->postFeatureService->featurePost($post);
- }
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $this->postFeatureService->featurePost($post);
+ }
}
diff --git a/src/Routes/Posts/GetFeaturedPost.php b/src/Routes/Posts/GetFeaturedPost.php
index de55755f..160e4922 100644
--- a/src/Routes/Posts/GetFeaturedPost.php
+++ b/src/Routes/Posts/GetFeaturedPost.php
@@ -7,36 +7,36 @@ use Szurubooru\ViewProxies\UserViewProxy;
class GetFeaturedPost extends AbstractPostRoute
{
- private $postFeatureService;
- private $postViewProxy;
+ private $postFeatureService;
+ private $postViewProxy;
- public function __construct(
- PostFeatureService $postFeatureService,
- UserViewProxy $userViewProxy,
- PostViewProxy $postViewProxy)
- {
- $this->postFeatureService = $postFeatureService;
- $this->userViewProxy = $userViewProxy;
- $this->postViewProxy = $postViewProxy;
- }
+ public function __construct(
+ PostFeatureService $postFeatureService,
+ UserViewProxy $userViewProxy,
+ PostViewProxy $postViewProxy)
+ {
+ $this->postFeatureService = $postFeatureService;
+ $this->userViewProxy = $userViewProxy;
+ $this->postViewProxy = $postViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts/featured';
- }
+ public function getUrl()
+ {
+ return '/api/posts/featured';
+ }
- public function work($args)
- {
- $post = $this->postFeatureService->getFeaturedPost();
- $user = $this->postFeatureService->getFeaturedPostUser();
- return [
- 'user' => $this->userViewProxy->fromEntity($user),
- 'post' => $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig()),
- ];
- }
+ public function work($args)
+ {
+ $post = $this->postFeatureService->getFeaturedPost();
+ $user = $this->postFeatureService->getFeaturedPostUser();
+ return [
+ 'user' => $this->userViewProxy->fromEntity($user),
+ 'post' => $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig()),
+ ];
+ }
}
diff --git a/src/Routes/Posts/GetPost.php b/src/Routes/Posts/GetPost.php
index 502aafe5..91f4f612 100644
--- a/src/Routes/Posts/GetPost.php
+++ b/src/Routes/Posts/GetPost.php
@@ -7,35 +7,35 @@ use Szurubooru\ViewProxies\PostViewProxy;
class GetPost extends AbstractPostRoute
{
- private $privilegeService;
- private $postService;
- private $postViewProxy;
+ private $privilegeService;
+ private $postService;
+ private $postViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- PostViewProxy $postViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->postViewProxy = $postViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ PostViewProxy $postViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->postViewProxy = $postViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::VIEW_POSTS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::VIEW_POSTS);
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- return $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig());
- }
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ return $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig());
+ }
}
diff --git a/src/Routes/Posts/GetPostContent.php b/src/Routes/Posts/GetPostContent.php
index 8b06a5c2..a7ab9fe6 100644
--- a/src/Routes/Posts/GetPostContent.php
+++ b/src/Routes/Posts/GetPostContent.php
@@ -9,48 +9,48 @@ use Szurubooru\Services\PostService;
class GetPostContent extends AbstractPostRoute
{
- private $config;
- private $fileDao;
- private $postService;
- private $networkingService;
+ private $config;
+ private $fileDao;
+ private $postService;
+ private $networkingService;
- public function __construct(
- Config $config,
- PublicFileDao $fileDao,
- PostService $postService,
- NetworkingService $networkingService)
- {
- $this->config = $config;
- $this->fileDao = $fileDao;
- $this->postService = $postService;
- $this->networkingService = $networkingService;
- }
+ public function __construct(
+ Config $config,
+ PublicFileDao $fileDao,
+ PostService $postService,
+ NetworkingService $networkingService)
+ {
+ $this->config = $config;
+ $this->fileDao = $fileDao;
+ $this->postService = $postService;
+ $this->networkingService = $networkingService;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postName/content';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postName/content';
+ }
- public function work($args)
- {
- $post = $this->postService->getByName($args['postName']);
+ public function work($args)
+ {
+ $post = $this->postService->getByName($args['postName']);
- $customFileName = sprintf('%s_%s.%s',
- $this->config->basic->serviceName,
- $post->getName(),
- strtolower(MimeHelper::getExtension($post->getContentMimeType())));
+ $customFileName = sprintf('%s_%s.%s',
+ $this->config->basic->serviceName,
+ $post->getName(),
+ strtolower(MimeHelper::getExtension($post->getContentMimeType())));
- if ($post->getContentType() === Post::POST_TYPE_YOUTUBE)
- {
- $this->networkingService->nonCachedRedirect($post->getOriginalFileName());
- return;
- }
+ if ($post->getContentType() === Post::POST_TYPE_YOUTUBE)
+ {
+ $this->networkingService->nonCachedRedirect($post->getOriginalFileName());
+ return;
+ }
- $this->networkingService->serveFile($this->fileDao->getFullPath($post->getContentPath()), $customFileName);
- }
+ $this->networkingService->serveFile($this->fileDao->getFullPath($post->getContentPath()), $customFileName);
+ }
}
diff --git a/src/Routes/Posts/GetPostThumbnail.php b/src/Routes/Posts/GetPostThumbnail.php
index bf3e8149..f305de5d 100644
--- a/src/Routes/Posts/GetPostThumbnail.php
+++ b/src/Routes/Posts/GetPostThumbnail.php
@@ -9,41 +9,41 @@ use Szurubooru\Services\PostThumbnailService;
class GetPostThumbnail extends AbstractPostRoute
{
- private $config;
- private $fileDao;
- private $postService;
- private $networkingService;
- private $postThumbnailService;
+ private $config;
+ private $fileDao;
+ private $postService;
+ private $networkingService;
+ private $postThumbnailService;
- public function __construct(
- Config $config,
- PublicFileDao $fileDao,
- PostService $postService,
- NetworkingService $networkingService,
- PostThumbnailService $postThumbnailService)
- {
- $this->config = $config;
- $this->fileDao = $fileDao;
- $this->postService = $postService;
- $this->networkingService = $networkingService;
- $this->postThumbnailService = $postThumbnailService;
- }
+ public function __construct(
+ Config $config,
+ PublicFileDao $fileDao,
+ PostService $postService,
+ NetworkingService $networkingService,
+ PostThumbnailService $postThumbnailService)
+ {
+ $this->config = $config;
+ $this->fileDao = $fileDao;
+ $this->postService = $postService;
+ $this->networkingService = $networkingService;
+ $this->postThumbnailService = $postThumbnailService;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postName/thumbnail/:size';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postName/thumbnail/:size';
+ }
- public function work($args)
- {
- $size = $args['size'];
- $post = $this->postService->getByName($args['postName']);
- $thumbnailName = $this->postThumbnailService->generateIfNeeded($post, $size, $size);
- $this->networkingService->serveFile($this->fileDao->getFullPath($thumbnailName));
- }
+ public function work($args)
+ {
+ $size = $args['size'];
+ $post = $this->postService->getByName($args['postName']);
+ $thumbnailName = $this->postThumbnailService->generateIfNeeded($post, $size, $size);
+ $this->networkingService->serveFile($this->fileDao->getFullPath($thumbnailName));
+ }
}
diff --git a/src/Routes/Posts/GetPosts.php b/src/Routes/Posts/GetPosts.php
index 8e5ad955..3cdab1d6 100644
--- a/src/Routes/Posts/GetPosts.php
+++ b/src/Routes/Posts/GetPosts.php
@@ -10,52 +10,52 @@ use Szurubooru\ViewProxies\PostViewProxy;
class GetPosts extends AbstractPostRoute
{
- private $config;
- private $privilegeService;
- private $postService;
- private $postSearchParser;
- private $inputReader;
- private $postViewProxy;
+ private $config;
+ private $privilegeService;
+ private $postService;
+ private $postSearchParser;
+ private $inputReader;
+ private $postViewProxy;
- public function __construct(
- Config $config,
- PrivilegeService $privilegeService,
- PostService $postService,
- PostSearchParser $postSearchParser,
- InputReader $inputReader,
- PostViewProxy $postViewProxy)
- {
- $this->config = $config;
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->postSearchParser = $postSearchParser;
- $this->inputReader = $inputReader;
- $this->postViewProxy = $postViewProxy;
- }
+ public function __construct(
+ Config $config,
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ PostSearchParser $postSearchParser,
+ InputReader $inputReader,
+ PostViewProxy $postViewProxy)
+ {
+ $this->config = $config;
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->postSearchParser = $postSearchParser;
+ $this->inputReader = $inputReader;
+ $this->postViewProxy = $postViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts';
- }
+ public function getUrl()
+ {
+ return '/api/posts';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::LIST_POSTS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::LIST_POSTS);
- $filter = $this->postSearchParser->createFilterFromInputReader($this->inputReader);
- $filter->setPageSize($this->config->posts->postsPerPage);
- $this->postService->decorateFilterFromBrowsingSettings($filter);
+ $filter = $this->postSearchParser->createFilterFromInputReader($this->inputReader);
+ $filter->setPageSize($this->config->posts->postsPerPage);
+ $this->postService->decorateFilterFromBrowsingSettings($filter);
- $result = $this->postService->getFiltered($filter);
- $entities = $this->postViewProxy->fromArray($result->getEntities(), $this->getLightFetchConfig());
- return [
- 'data' => $entities,
- 'pageSize' => $result->getPageSize(),
- 'totalRecords' => $result->getTotalRecords()];
- }
+ $result = $this->postService->getFiltered($filter);
+ $entities = $this->postViewProxy->fromArray($result->getEntities(), $this->getLightFetchConfig());
+ return [
+ 'data' => $entities,
+ 'pageSize' => $result->getPageSize(),
+ 'totalRecords' => $result->getTotalRecords()];
+ }
}
diff --git a/src/Routes/Posts/Notes/AddPostNote.php b/src/Routes/Posts/Notes/AddPostNote.php
index 3df5a7aa..5e3fa76e 100644
--- a/src/Routes/Posts/Notes/AddPostNote.php
+++ b/src/Routes/Posts/Notes/AddPostNote.php
@@ -11,44 +11,44 @@ use Szurubooru\ViewProxies\PostNoteViewProxy;
class AddPostNote extends AbstractPostRoute
{
- private $inputReader;
- private $postService;
- private $postNotesService;
- private $privilegeService;
- private $postNoteViewProxy;
+ private $inputReader;
+ private $postService;
+ private $postNotesService;
+ private $privilegeService;
+ private $postNoteViewProxy;
- public function __construct(
- InputReader $inputReader,
- PostService $postService,
- PostNotesService $postNotesService,
- PrivilegeService $privilegeService,
- PostNoteViewProxy $postNoteViewProxy)
- {
- $this->inputReader = $inputReader;
- $this->postService = $postService;
- $this->postNotesService = $postNotesService;
- $this->privilegeService = $privilegeService;
- $this->postNoteViewProxy = $postNoteViewProxy;
- }
+ public function __construct(
+ InputReader $inputReader,
+ PostService $postService,
+ PostNotesService $postNotesService,
+ PrivilegeService $privilegeService,
+ PostNoteViewProxy $postNoteViewProxy)
+ {
+ $this->inputReader = $inputReader;
+ $this->postService = $postService;
+ $this->postNotesService = $postNotesService;
+ $this->privilegeService = $privilegeService;
+ $this->postNoteViewProxy = $postNoteViewProxy;
+ }
- public function getMethods()
- {
- return ['POST'];
- }
+ public function getMethods()
+ {
+ return ['POST'];
+ }
- public function getUrl()
- {
- return '/api/notes/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/notes/:postNameOrId';
+ }
- public function work($args)
- {
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ public function work($args)
+ {
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $this->privilegeService->assertPrivilege(Privilege::ADD_POST_NOTES);
+ $this->privilegeService->assertPrivilege(Privilege::ADD_POST_NOTES);
- $formData = new PostNoteFormData($this->inputReader);
- $postNote = $this->postNotesService->createPostNote($post, $formData);
- return $this->postNoteViewProxy->fromEntity($postNote);
- }
+ $formData = new PostNoteFormData($this->inputReader);
+ $postNote = $this->postNotesService->createPostNote($post, $formData);
+ return $this->postNoteViewProxy->fromEntity($postNote);
+ }
}
diff --git a/src/Routes/Posts/Notes/DeletePostNote.php b/src/Routes/Posts/Notes/DeletePostNote.php
index 8667fc89..f97c645a 100644
--- a/src/Routes/Posts/Notes/DeletePostNote.php
+++ b/src/Routes/Posts/Notes/DeletePostNote.php
@@ -7,31 +7,31 @@ use Szurubooru\Services\PrivilegeService;
class DeletePostNote extends AbstractPostRoute
{
- private $postNotesService;
- private $privilegeService;
+ private $postNotesService;
+ private $privilegeService;
- public function __construct(
- PostNotesService $postNotesService,
- PrivilegeService $privilegeService)
- {
- $this->postNotesService = $postNotesService;
- $this->privilegeService = $privilegeService;
- }
+ public function __construct(
+ PostNotesService $postNotesService,
+ PrivilegeService $privilegeService)
+ {
+ $this->postNotesService = $postNotesService;
+ $this->privilegeService = $privilegeService;
+ }
- public function getMethods()
- {
- return ['DELETE'];
- }
+ public function getMethods()
+ {
+ return ['DELETE'];
+ }
- public function getUrl()
- {
- return '/api/notes/:postNoteId';
- }
+ public function getUrl()
+ {
+ return '/api/notes/:postNoteId';
+ }
- public function work($args)
- {
- $postNote = $this->postNotesService->getById($args['postNoteId']);
- $this->privilegeService->assertPrivilege(Privilege::DELETE_POST_NOTES);
- return $this->postNotesService->deletePostNote($postNote);
- }
+ public function work($args)
+ {
+ $postNote = $this->postNotesService->getById($args['postNoteId']);
+ $this->privilegeService->assertPrivilege(Privilege::DELETE_POST_NOTES);
+ return $this->postNotesService->deletePostNote($postNote);
+ }
}
diff --git a/src/Routes/Posts/Notes/GetPostNotes.php b/src/Routes/Posts/Notes/GetPostNotes.php
index 5ef988fd..a5232bca 100644
--- a/src/Routes/Posts/Notes/GetPostNotes.php
+++ b/src/Routes/Posts/Notes/GetPostNotes.php
@@ -10,40 +10,40 @@ use Szurubooru\ViewProxies\PostNoteViewProxy;
class GetPostNotes extends AbstractPostRoute
{
- private $inputReader;
- private $postService;
- private $postNotesService;
- private $privilegeService;
- private $postNoteViewProxy;
+ private $inputReader;
+ private $postService;
+ private $postNotesService;
+ private $privilegeService;
+ private $postNoteViewProxy;
- public function __construct(
- InputReader $inputReader,
- PostService $postService,
- PostNotesService $postNotesService,
- PrivilegeService $privilegeService,
- PostNoteViewProxy $postNoteViewProxy)
- {
- $this->inputReader = $inputReader;
- $this->postService = $postService;
- $this->postNotesService = $postNotesService;
- $this->privilegeService = $privilegeService;
- $this->postNoteViewProxy = $postNoteViewProxy;
- }
+ public function __construct(
+ InputReader $inputReader,
+ PostService $postService,
+ PostNotesService $postNotesService,
+ PrivilegeService $privilegeService,
+ PostNoteViewProxy $postNoteViewProxy)
+ {
+ $this->inputReader = $inputReader;
+ $this->postService = $postService;
+ $this->postNotesService = $postNotesService;
+ $this->privilegeService = $privilegeService;
+ $this->postNoteViewProxy = $postNoteViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/notes/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/notes/:postNameOrId';
+ }
- public function work($args)
- {
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- $postNotes = $this->postNotesService->getByPost($post);
- return $this->postNoteViewProxy->fromArray($postNotes);
- }
+ public function work($args)
+ {
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ $postNotes = $this->postNotesService->getByPost($post);
+ return $this->postNoteViewProxy->fromArray($postNotes);
+ }
}
diff --git a/src/Routes/Posts/Notes/UpdatePostNote.php b/src/Routes/Posts/Notes/UpdatePostNote.php
index 76fa2656..a96bfd78 100644
--- a/src/Routes/Posts/Notes/UpdatePostNote.php
+++ b/src/Routes/Posts/Notes/UpdatePostNote.php
@@ -10,41 +10,41 @@ use Szurubooru\ViewProxies\PostNoteViewProxy;
class UpdatePostNote extends AbstractPostRoute
{
- private $inputReader;
- private $postNotesService;
- private $privilegeService;
- private $postNoteViewProxy;
+ private $inputReader;
+ private $postNotesService;
+ private $privilegeService;
+ private $postNoteViewProxy;
- public function __construct(
- InputReader $inputReader,
- PostNotesService $postNotesService,
- PrivilegeService $privilegeService,
- PostNoteViewProxy $postNoteViewProxy)
- {
- $this->inputReader = $inputReader;
- $this->postNotesService = $postNotesService;
- $this->privilegeService = $privilegeService;
- $this->postNoteViewProxy = $postNoteViewProxy;
- }
+ public function __construct(
+ InputReader $inputReader,
+ PostNotesService $postNotesService,
+ PrivilegeService $privilegeService,
+ PostNoteViewProxy $postNoteViewProxy)
+ {
+ $this->inputReader = $inputReader;
+ $this->postNotesService = $postNotesService;
+ $this->privilegeService = $privilegeService;
+ $this->postNoteViewProxy = $postNoteViewProxy;
+ }
- public function getMethods()
- {
- return ['PUT'];
- }
+ public function getMethods()
+ {
+ return ['PUT'];
+ }
- public function getUrl()
- {
- return '/api/notes/:postNoteId';
- }
+ public function getUrl()
+ {
+ return '/api/notes/:postNoteId';
+ }
- public function work($args)
- {
- $postNote = $this->postNotesService->getById($args['postNoteId']);
+ public function work($args)
+ {
+ $postNote = $this->postNotesService->getById($args['postNoteId']);
- $this->privilegeService->assertPrivilege(Privilege::EDIT_POST_NOTES);
+ $this->privilegeService->assertPrivilege(Privilege::EDIT_POST_NOTES);
- $formData = new PostNoteFormData($this->inputReader);
- $postNote = $this->postNotesService->updatePostNote($postNote, $formData);
- return $this->postNoteViewProxy->fromEntity($postNote);
- }
+ $formData = new PostNoteFormData($this->inputReader);
+ $postNote = $this->postNotesService->updatePostNote($postNote, $formData);
+ return $this->postNoteViewProxy->fromEntity($postNote);
+ }
}
diff --git a/src/Routes/Posts/UpdatePost.php b/src/Routes/Posts/UpdatePost.php
index 475dc1ef..5787af40 100644
--- a/src/Routes/Posts/UpdatePost.php
+++ b/src/Routes/Posts/UpdatePost.php
@@ -9,56 +9,56 @@ use Szurubooru\ViewProxies\PostViewProxy;
class UpdatePost extends AbstractPostRoute
{
- private $privilegeService;
- private $postService;
- private $inputReader;
- private $postViewProxy;
+ private $privilegeService;
+ private $postService;
+ private $inputReader;
+ private $postViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- PostService $postService,
- InputReader $inputReader,
- PostViewProxy $postViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->postService = $postService;
- $this->inputReader = $inputReader;
- $this->postViewProxy = $postViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ PostService $postService,
+ InputReader $inputReader,
+ PostViewProxy $postViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->postService = $postService;
+ $this->inputReader = $inputReader;
+ $this->postViewProxy = $postViewProxy;
+ }
- public function getMethods()
- {
- return ['POST'];
- }
+ public function getMethods()
+ {
+ return ['POST'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId';
+ }
- public function work($args)
- {
- $postNameOrId = $args['postNameOrId'];
- $post = $this->postService->getByNameOrId($postNameOrId);
- $formData = new PostEditFormData($this->inputReader);
+ public function work($args)
+ {
+ $postNameOrId = $args['postNameOrId'];
+ $post = $this->postService->getByNameOrId($postNameOrId);
+ $formData = new PostEditFormData($this->inputReader);
- if ($formData->content !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_CONTENT);
+ if ($formData->content !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_CONTENT);
- if ($formData->thumbnail !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_THUMBNAIL);
+ if ($formData->thumbnail !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_THUMBNAIL);
- if ($formData->safety !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_SAFETY);
+ if ($formData->safety !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_SAFETY);
- if ($formData->source !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_SOURCE);
+ if ($formData->source !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_SOURCE);
- if ($formData->tags !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_TAGS);
+ if ($formData->tags !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_POST_TAGS);
- $this->postService->updatePost($post, $formData);
- $post = $this->postService->getByNameOrId($postNameOrId);
- return $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig());
- }
+ $this->postService->updatePost($post, $formData);
+ $post = $this->postService->getByNameOrId($postNameOrId);
+ return $this->postViewProxy->fromEntity($post, $this->getFullFetchConfig());
+ }
}
diff --git a/src/Routes/Scores/AbstractScoreRoute.php b/src/Routes/Scores/AbstractScoreRoute.php
index 44807816..052181b8 100644
--- a/src/Routes/Scores/AbstractScoreRoute.php
+++ b/src/Routes/Scores/AbstractScoreRoute.php
@@ -9,40 +9,40 @@ use Szurubooru\Routes\AbstractRoute;
abstract class AbstractScoreRoute extends AbstractRoute
{
- private $privilegeService;
- private $scoreService;
- private $authService;
+ private $privilegeService;
+ private $scoreService;
+ private $authService;
- public function __construct(
- AuthService $authService,
- InputReader $inputReader,
- PrivilegeService $privilegeService,
- ScoreService $scoreService)
- {
- $this->authService = $authService;
- $this->inputReader = $inputReader;
- $this->privilegeService = $privilegeService;
- $this->scoreService = $scoreService;
- }
+ public function __construct(
+ AuthService $authService,
+ InputReader $inputReader,
+ PrivilegeService $privilegeService,
+ ScoreService $scoreService)
+ {
+ $this->authService = $authService;
+ $this->inputReader = $inputReader;
+ $this->privilegeService = $privilegeService;
+ $this->scoreService = $scoreService;
+ }
- protected function getScore(Entity $entity)
- {
- $user = $this->authService->getLoggedInUser();
- return [
- 'score' => $this->scoreService->getScoreValue($entity),
- 'ownScore' => $this->scoreService->getUserScoreValue($user, $entity),
- ];
- }
+ protected function getScore(Entity $entity)
+ {
+ $user = $this->authService->getLoggedInUser();
+ return [
+ 'score' => $this->scoreService->getScoreValue($entity),
+ 'ownScore' => $this->scoreService->getUserScoreValue($user, $entity),
+ ];
+ }
- protected function setScore(Entity $entity)
- {
- $this->privilegeService->assertLoggedIn();
- $score = intval($this->inputReader->score);
- $user = $this->authService->getLoggedInUser();
- $result = $this->scoreService->setUserScore($user, $entity, $score);
- return [
- 'score' => $this->scoreService->getScoreValue($entity),
- 'ownScore' => $result->getScore(),
- ];
- }
+ protected function setScore(Entity $entity)
+ {
+ $this->privilegeService->assertLoggedIn();
+ $score = intval($this->inputReader->score);
+ $user = $this->authService->getLoggedInUser();
+ $result = $this->scoreService->setUserScore($user, $entity, $score);
+ return [
+ 'score' => $this->scoreService->getScoreValue($entity),
+ 'ownScore' => $result->getScore(),
+ ];
+ }
}
diff --git a/src/Routes/Scores/GetCommentScore.php b/src/Routes/Scores/GetCommentScore.php
index 58b2325f..a1c6a08f 100644
--- a/src/Routes/Scores/GetCommentScore.php
+++ b/src/Routes/Scores/GetCommentScore.php
@@ -9,37 +9,37 @@ use Szurubooru\Services\ScoreService;
class GetCommentScore extends AbstractScoreRoute
{
- private $commentService;
+ private $commentService;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- CommentService $commentService,
- ScoreService $scoreService,
- InputReader $inputReader)
- {
- parent::__construct(
- $authService,
- $inputReader,
- $privilegeService,
- $scoreService);
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ CommentService $commentService,
+ ScoreService $scoreService,
+ InputReader $inputReader)
+ {
+ parent::__construct(
+ $authService,
+ $inputReader,
+ $privilegeService,
+ $scoreService);
- $this->commentService = $commentService;
- }
+ $this->commentService = $commentService;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/comments/:commentId/score';
- }
+ public function getUrl()
+ {
+ return '/api/comments/:commentId/score';
+ }
- public function work($args)
- {
- $comment = $this->commentService->getById($args['commentId']);
- return $this->getScore($comment);
- }
+ public function work($args)
+ {
+ $comment = $this->commentService->getById($args['commentId']);
+ return $this->getScore($comment);
+ }
}
diff --git a/src/Routes/Scores/GetPostScore.php b/src/Routes/Scores/GetPostScore.php
index fbb15130..0a90e009 100644
--- a/src/Routes/Scores/GetPostScore.php
+++ b/src/Routes/Scores/GetPostScore.php
@@ -9,37 +9,37 @@ use Szurubooru\Services\ScoreService;
class GetPostScore extends AbstractScoreRoute
{
- private $postService;
+ private $postService;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- PostService $postService,
- ScoreService $scoreService,
- InputReader $inputReader)
- {
- parent::__construct(
- $authService,
- $inputReader,
- $privilegeService,
- $scoreService);
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ PostService $postService,
+ ScoreService $scoreService,
+ InputReader $inputReader)
+ {
+ parent::__construct(
+ $authService,
+ $inputReader,
+ $privilegeService,
+ $scoreService);
- $this->postService = $postService;
- }
+ $this->postService = $postService;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId/score';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId/score';
+ }
- public function work($args)
- {
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- return $this->getScore($post);
- }
+ public function work($args)
+ {
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ return $this->getScore($post);
+ }
}
diff --git a/src/Routes/Scores/SetCommentScore.php b/src/Routes/Scores/SetCommentScore.php
index 70355748..bd1a1ea3 100644
--- a/src/Routes/Scores/SetCommentScore.php
+++ b/src/Routes/Scores/SetCommentScore.php
@@ -9,37 +9,37 @@ use Szurubooru\Services\ScoreService;
class SetCommentScore extends AbstractScoreRoute
{
- private $commentService;
+ private $commentService;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- CommentService $commentService,
- ScoreService $scoreService,
- InputReader $inputReader)
- {
- parent::__construct(
- $authService,
- $inputReader,
- $privilegeService,
- $scoreService);
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ CommentService $commentService,
+ ScoreService $scoreService,
+ InputReader $inputReader)
+ {
+ parent::__construct(
+ $authService,
+ $inputReader,
+ $privilegeService,
+ $scoreService);
- $this->commentService = $commentService;
- }
+ $this->commentService = $commentService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/comments/:commentId/score';
- }
+ public function getUrl()
+ {
+ return '/api/comments/:commentId/score';
+ }
- public function work($args)
- {
- $comment = $this->commentService->getById($args['commentId']);
- return $this->setScore($comment);
- }
+ public function work($args)
+ {
+ $comment = $this->commentService->getById($args['commentId']);
+ return $this->setScore($comment);
+ }
}
diff --git a/src/Routes/Scores/SetPostScore.php b/src/Routes/Scores/SetPostScore.php
index 1b5a8a65..8ca564f4 100644
--- a/src/Routes/Scores/SetPostScore.php
+++ b/src/Routes/Scores/SetPostScore.php
@@ -9,37 +9,37 @@ use Szurubooru\Services\ScoreService;
class SetPostScore extends AbstractScoreRoute
{
- private $postService;
+ private $postService;
- public function __construct(
- PrivilegeService $privilegeService,
- AuthService $authService,
- PostService $postService,
- ScoreService $scoreService,
- InputReader $inputReader)
- {
- parent::__construct(
- $authService,
- $inputReader,
- $privilegeService,
- $scoreService);
+ public function __construct(
+ PrivilegeService $privilegeService,
+ AuthService $authService,
+ PostService $postService,
+ ScoreService $scoreService,
+ InputReader $inputReader)
+ {
+ parent::__construct(
+ $authService,
+ $inputReader,
+ $privilegeService,
+ $scoreService);
- $this->postService = $postService;
- }
+ $this->postService = $postService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/posts/:postNameOrId/score';
- }
+ public function getUrl()
+ {
+ return '/api/posts/:postNameOrId/score';
+ }
- public function work($args)
- {
- $post = $this->postService->getByNameOrId($args['postNameOrId']);
- return $this->setScore($post);
- }
+ public function work($args)
+ {
+ $post = $this->postService->getByNameOrId($args['postNameOrId']);
+ return $this->setScore($post);
+ }
}
diff --git a/src/Routes/Tags/AbstractTagRoute.php b/src/Routes/Tags/AbstractTagRoute.php
index ed64d7bf..ed1da51a 100644
--- a/src/Routes/Tags/AbstractTagRoute.php
+++ b/src/Routes/Tags/AbstractTagRoute.php
@@ -5,13 +5,13 @@ use Szurubooru\ViewProxies\TagViewProxy;
abstract class AbstractTagRoute extends AbstractRoute
{
- protected function getFullFetchConfig()
- {
- return
- [
- TagViewProxy::FETCH_IMPLICATIONS => true,
- TagViewProxy::FETCH_SUGGESTIONS => true,
- TagViewProxy::FETCH_HISTORY => true,
- ];
- }
+ protected function getFullFetchConfig()
+ {
+ return
+ [
+ TagViewProxy::FETCH_IMPLICATIONS => true,
+ TagViewProxy::FETCH_SUGGESTIONS => true,
+ TagViewProxy::FETCH_HISTORY => true,
+ ];
+ }
}
diff --git a/src/Routes/Tags/DeleteTag.php b/src/Routes/Tags/DeleteTag.php
index 786189c7..0cd827a0 100644
--- a/src/Routes/Tags/DeleteTag.php
+++ b/src/Routes/Tags/DeleteTag.php
@@ -6,31 +6,31 @@ use Szurubooru\Services\TagService;
class DeleteTag extends AbstractTagRoute
{
- private $privilegeService;
- private $tagService;
+ private $privilegeService;
+ private $tagService;
- public function __construct(
- PrivilegeService $privilegeService,
- TagService $tagService)
- {
- $this->privilegeService = $privilegeService;
- $this->tagService = $tagService;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ TagService $tagService)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->tagService = $tagService;
+ }
- public function getMethods()
- {
- return ['DELETE'];
- }
+ public function getMethods()
+ {
+ return ['DELETE'];
+ }
- public function getUrl()
- {
- return '/api/tags/:tagName';
- }
+ public function getUrl()
+ {
+ return '/api/tags/:tagName';
+ }
- public function work($args)
- {
- $tag = $this->tagService->getByName($args['tagName']);
- $this->privilegeService->assertPrivilege(Privilege::DELETE_TAGS);
- return $this->tagService->deleteTag($tag);
- }
+ public function work($args)
+ {
+ $tag = $this->tagService->getByName($args['tagName']);
+ $this->privilegeService->assertPrivilege(Privilege::DELETE_TAGS);
+ return $this->tagService->deleteTag($tag);
+ }
}
diff --git a/src/Routes/Tags/GetTag.php b/src/Routes/Tags/GetTag.php
index 00bb3217..6c0c6836 100644
--- a/src/Routes/Tags/GetTag.php
+++ b/src/Routes/Tags/GetTag.php
@@ -7,35 +7,35 @@ use Szurubooru\ViewProxies\TagViewProxy;
class GetTag extends AbstractTagRoute
{
- private $privilegeService;
- private $tagService;
- private $tagViewProxy;
+ private $privilegeService;
+ private $tagService;
+ private $tagViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- TagService $tagService,
- TagViewProxy $tagViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->tagService = $tagService;
- $this->tagViewProxy = $tagViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ TagService $tagService,
+ TagViewProxy $tagViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->tagService = $tagService;
+ $this->tagViewProxy = $tagViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/tags/:tagName';
- }
+ public function getUrl()
+ {
+ return '/api/tags/:tagName';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::LIST_TAGS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::LIST_TAGS);
- $tag = $this->tagService->getByName($args['tagName']);
- return $this->tagViewProxy->fromEntity($tag, $this->getFullFetchConfig());
- }
+ $tag = $this->tagService->getByName($args['tagName']);
+ return $this->tagViewProxy->fromEntity($tag, $this->getFullFetchConfig());
+ }
}
diff --git a/src/Routes/Tags/GetTagSiblings.php b/src/Routes/Tags/GetTagSiblings.php
index e6ffcfa2..bda22e44 100644
--- a/src/Routes/Tags/GetTagSiblings.php
+++ b/src/Routes/Tags/GetTagSiblings.php
@@ -7,39 +7,39 @@ use Szurubooru\ViewProxies\TagViewProxy;
class GetTagSiblings extends AbstractTagRoute
{
- private $privilegeService;
- private $tagService;
- private $tagViewProxy;
+ private $privilegeService;
+ private $tagService;
+ private $tagViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- TagService $tagService,
- TagViewProxy $tagViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->tagService = $tagService;
- $this->tagViewProxy = $tagViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ TagService $tagService,
+ TagViewProxy $tagViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->tagService = $tagService;
+ $this->tagViewProxy = $tagViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/tags/:tagName/siblings';
- }
+ public function getUrl()
+ {
+ return '/api/tags/:tagName/siblings';
+ }
- public function work($args)
- {
- $tagName = $args['tagName'];
- $this->privilegeService->assertPrivilege(Privilege::LIST_TAGS);
- $tag = $this->tagService->getByName($tagName);
- $result = $this->tagService->getSiblings($tagName);
- $entities = $this->tagViewProxy->fromArray($result);
- return [
- 'data' => $entities,
- ];
- }
+ public function work($args)
+ {
+ $tagName = $args['tagName'];
+ $this->privilegeService->assertPrivilege(Privilege::LIST_TAGS);
+ $tag = $this->tagService->getByName($tagName);
+ $result = $this->tagService->getSiblings($tagName);
+ $entities = $this->tagViewProxy->fromArray($result);
+ return [
+ 'data' => $entities,
+ ];
+ }
}
diff --git a/src/Routes/Tags/GetTags.php b/src/Routes/Tags/GetTags.php
index 5a4ec930..47bb9596 100644
--- a/src/Routes/Tags/GetTags.php
+++ b/src/Routes/Tags/GetTags.php
@@ -9,48 +9,48 @@ use Szurubooru\ViewProxies\TagViewProxy;
class GetTags extends AbstractTagRoute
{
- private $privilegeService;
- private $tagService;
- private $tagViewProxy;
- private $tagSearchParser;
- private $inputReader;
+ private $privilegeService;
+ private $tagService;
+ private $tagViewProxy;
+ private $tagSearchParser;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- TagService $tagService,
- TagViewProxy $tagViewProxy,
- TagSearchParser $tagSearchParser,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->tagService = $tagService;
- $this->tagViewProxy = $tagViewProxy;
- $this->tagSearchParser = $tagSearchParser;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ TagService $tagService,
+ TagViewProxy $tagViewProxy,
+ TagSearchParser $tagSearchParser,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->tagService = $tagService;
+ $this->tagViewProxy = $tagViewProxy;
+ $this->tagSearchParser = $tagSearchParser;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/tags';
- }
+ public function getUrl()
+ {
+ return '/api/tags';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::LIST_TAGS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::LIST_TAGS);
- $filter = $this->tagSearchParser->createFilterFromInputReader($this->inputReader);
- $filter->setPageSize(50);
+ $filter = $this->tagSearchParser->createFilterFromInputReader($this->inputReader);
+ $filter->setPageSize(50);
- $result = $this->tagService->getFiltered($filter);
- $entities = $this->tagViewProxy->fromArray($result->getEntities(), $this->getFullFetchConfig());
- return [
- 'data' => $entities,
- 'pageSize' => $result->getPageSize(),
- 'totalRecords' => $result->getTotalRecords()];
- }
+ $result = $this->tagService->getFiltered($filter);
+ $entities = $this->tagViewProxy->fromArray($result->getEntities(), $this->getFullFetchConfig());
+ return [
+ 'data' => $entities,
+ 'pageSize' => $result->getPageSize(),
+ 'totalRecords' => $result->getTotalRecords()];
+ }
}
diff --git a/src/Routes/Tags/MergeTags.php b/src/Routes/Tags/MergeTags.php
index 20c30160..8a0f9e5b 100644
--- a/src/Routes/Tags/MergeTags.php
+++ b/src/Routes/Tags/MergeTags.php
@@ -7,37 +7,37 @@ use Szurubooru\Services\TagService;
class MergeTags extends AbstractTagRoute
{
- private $privilegeService;
- private $tagService;
- private $inputReader;
+ private $privilegeService;
+ private $tagService;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- TagService $tagService,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->tagService = $tagService;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ TagService $tagService,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->tagService = $tagService;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/tags/:tagName/merge';
- }
+ public function getUrl()
+ {
+ return '/api/tags/:tagName/merge';
+ }
- public function work($args)
- {
- $tagName = $args['tagName'];
- $targetTagName = $this->inputReader->targetTag;
- $sourceTag = $this->tagService->getByName($tagName);
- $targetTag = $this->tagService->getByName($targetTagName);
- $this->privilegeService->assertPrivilege(Privilege::MERGE_TAGS);
- return $this->tagService->mergeTag($sourceTag, $targetTag);
- }
+ public function work($args)
+ {
+ $tagName = $args['tagName'];
+ $targetTagName = $this->inputReader->targetTag;
+ $sourceTag = $this->tagService->getByName($tagName);
+ $targetTag = $this->tagService->getByName($targetTagName);
+ $this->privilegeService->assertPrivilege(Privilege::MERGE_TAGS);
+ return $this->tagService->mergeTag($sourceTag, $targetTag);
+ }
}
diff --git a/src/Routes/Tags/UpdateTag.php b/src/Routes/Tags/UpdateTag.php
index eb1c1c49..7f848e7f 100644
--- a/src/Routes/Tags/UpdateTag.php
+++ b/src/Routes/Tags/UpdateTag.php
@@ -9,54 +9,54 @@ use Szurubooru\ViewProxies\TagViewProxy;
class UpdateTag extends AbstractTagRoute
{
- private $privilegeService;
- private $tagService;
- private $tagViewProxy;
- private $inputReader;
+ private $privilegeService;
+ private $tagService;
+ private $tagViewProxy;
+ private $inputReader;
- public function __construct(
- PrivilegeService $privilegeService,
- TagService $tagService,
- TagViewProxy $tagViewProxy,
- InputReader $inputReader)
- {
- $this->privilegeService = $privilegeService;
- $this->tagService = $tagService;
- $this->tagViewProxy = $tagViewProxy;
- $this->inputReader = $inputReader;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ TagService $tagService,
+ TagViewProxy $tagViewProxy,
+ InputReader $inputReader)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->tagService = $tagService;
+ $this->tagViewProxy = $tagViewProxy;
+ $this->inputReader = $inputReader;
+ }
- public function getMethods()
- {
- return ['PUT'];
- }
+ public function getMethods()
+ {
+ return ['PUT'];
+ }
- public function getUrl()
- {
- return '/api/tags/:tagName';
- }
+ public function getUrl()
+ {
+ return '/api/tags/:tagName';
+ }
- public function work($args)
- {
- $tag = $this->tagService->getByName($args['tagName']);
- $formData = new TagEditFormData($this->inputReader);
+ public function work($args)
+ {
+ $tag = $this->tagService->getByName($args['tagName']);
+ $formData = new TagEditFormData($this->inputReader);
- if ($formData->name !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_NAME);
+ if ($formData->name !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_NAME);
- if ($formData->category !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_CATEGORY);
+ if ($formData->category !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_CATEGORY);
- if ($formData->banned !== null)
- $this->privilegeService->assertPrivilege(Privilege::BAN_TAGS);
+ if ($formData->banned !== null)
+ $this->privilegeService->assertPrivilege(Privilege::BAN_TAGS);
- if ($formData->implications !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_IMPLICATIONS);
+ if ($formData->implications !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_IMPLICATIONS);
- if ($formData->suggestions !== null)
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_SUGGESTIONS);
+ if ($formData->suggestions !== null)
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_TAG_SUGGESTIONS);
- $tag = $this->tagService->updateTag($tag, $formData);
- return $this->tagViewProxy->fromEntity($tag, $this->getFullFetchConfig());
- }
+ $tag = $this->tagService->updateTag($tag, $formData);
+ return $this->tagViewProxy->fromEntity($tag, $this->getFullFetchConfig());
+ }
}
diff --git a/src/Routes/Users/ActivateAccount.php b/src/Routes/Users/ActivateAccount.php
index 5209728c..790bb542 100644
--- a/src/Routes/Users/ActivateAccount.php
+++ b/src/Routes/Users/ActivateAccount.php
@@ -4,26 +4,26 @@ use Szurubooru\Services\UserService;
class ActivateAccount extends AbstractUserRoute
{
- private $userService;
+ private $userService;
- public function __construct(UserService $userService)
- {
- $this->userService = $userService;
- }
+ public function __construct(UserService $userService)
+ {
+ $this->userService = $userService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/activation/:userNameOrEmail';
- }
+ public function getUrl()
+ {
+ return '/api/activation/:userNameOrEmail';
+ }
- public function work($args)
- {
- $user = $this->userService->getByNameOrEmail($args['userNameOrEmail'], true);
- return $this->userService->sendActivationEmail($user);
- }
+ public function work($args)
+ {
+ $user = $this->userService->getByNameOrEmail($args['userNameOrEmail'], true);
+ return $this->userService->sendActivationEmail($user);
+ }
}
diff --git a/src/Routes/Users/CreateUser.php b/src/Routes/Users/CreateUser.php
index 6fdafb12..a8dcee94 100644
--- a/src/Routes/Users/CreateUser.php
+++ b/src/Routes/Users/CreateUser.php
@@ -9,38 +9,38 @@ use Szurubooru\ViewProxies\UserViewProxy;
class CreateUser extends AbstractUserRoute
{
- private $privilegeService;
- private $userService;
- private $inputReader;
- private $userViewProxy;
+ private $privilegeService;
+ private $userService;
+ private $inputReader;
+ private $userViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- UserService $userService,
- InputReader $inputReader,
- UserViewProxy $userViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->userService = $userService;
- $this->inputReader = $inputReader;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ UserService $userService,
+ InputReader $inputReader,
+ UserViewProxy $userViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->userService = $userService;
+ $this->inputReader = $inputReader;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['POST'];
- }
+ public function getMethods()
+ {
+ return ['POST'];
+ }
- public function getUrl()
- {
- return '/api/users';
- }
+ public function getUrl()
+ {
+ return '/api/users';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::REGISTER);
- $formData = new RegistrationFormData($this->inputReader);
- $user = $this->userService->createUser($formData);
- return $this->userViewProxy->fromEntity($user);
- }
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::REGISTER);
+ $formData = new RegistrationFormData($this->inputReader);
+ $user = $this->userService->createUser($formData);
+ return $this->userViewProxy->fromEntity($user);
+ }
}
diff --git a/src/Routes/Users/DeleteUser.php b/src/Routes/Users/DeleteUser.php
index 8b2985e2..92f04108 100644
--- a/src/Routes/Users/DeleteUser.php
+++ b/src/Routes/Users/DeleteUser.php
@@ -7,37 +7,37 @@ use Szurubooru\Services\UserService;
class DeleteUser extends AbstractUserRoute
{
- private $privilegeService;
- private $userService;
+ private $privilegeService;
+ private $userService;
- public function __construct(
- PrivilegeService $privilegeService,
- UserService $userService)
- {
- $this->privilegeService = $privilegeService;
- $this->userService = $userService;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ UserService $userService)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->userService = $userService;
+ }
- public function getMethods()
- {
- return ['DELETE'];
- }
+ public function getMethods()
+ {
+ return ['DELETE'];
+ }
- public function getUrl()
- {
- return '/api/users/:userNameOrEmail';
- }
+ public function getUrl()
+ {
+ return '/api/users/:userNameOrEmail';
+ }
- public function work($args)
- {
- $userNameOrEmail = $args['userNameOrEmail'];
+ public function work($args)
+ {
+ $userNameOrEmail = $args['userNameOrEmail'];
- $this->privilegeService->assertPrivilege(
- $this->privilegeService->isLoggedIn($userNameOrEmail)
- ? Privilege::DELETE_OWN_ACCOUNT
- : Privilege::DELETE_ALL_ACCOUNTS);
+ $this->privilegeService->assertPrivilege(
+ $this->privilegeService->isLoggedIn($userNameOrEmail)
+ ? Privilege::DELETE_OWN_ACCOUNT
+ : Privilege::DELETE_ALL_ACCOUNTS);
- $user = $this->userService->getByNameOrEmail($userNameOrEmail);
- return $this->userService->deleteUser($user);
- }
+ $user = $this->userService->getByNameOrEmail($userNameOrEmail);
+ return $this->userService->deleteUser($user);
+ }
}
diff --git a/src/Routes/Users/FinishActivation.php b/src/Routes/Users/FinishActivation.php
index 79a6a3ec..dfe33f3c 100644
--- a/src/Routes/Users/FinishActivation.php
+++ b/src/Routes/Users/FinishActivation.php
@@ -5,30 +5,30 @@ use Szurubooru\Services\UserService;
class FinishActivation extends AbstractUserRoute
{
- private $userService;
- private $tokenService;
+ private $userService;
+ private $tokenService;
- public function __construct(
- UserService $userService,
- TokenService $tokenService)
- {
- $this->userService = $userService;
- $this->tokenService = $tokenService;
- }
+ public function __construct(
+ UserService $userService,
+ TokenService $tokenService)
+ {
+ $this->userService = $userService;
+ $this->tokenService = $tokenService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/finish-activation/:tokenName';
- }
+ public function getUrl()
+ {
+ return '/api/finish-activation/:tokenName';
+ }
- public function work($args)
- {
- $token = $this->tokenService->getByName($args['tokenName']);
- $this->userService->finishActivation($token);
- }
+ public function work($args)
+ {
+ $token = $this->tokenService->getByName($args['tokenName']);
+ $this->userService->finishActivation($token);
+ }
}
diff --git a/src/Routes/Users/FinishPasswordReset.php b/src/Routes/Users/FinishPasswordReset.php
index 9280b7b5..a85c8efa 100644
--- a/src/Routes/Users/FinishPasswordReset.php
+++ b/src/Routes/Users/FinishPasswordReset.php
@@ -5,30 +5,30 @@ use Szurubooru\Services\UserService;
class FinishPasswordReset extends AbstractUserRoute
{
- private $userService;
- private $tokenService;
+ private $userService;
+ private $tokenService;
- public function __construct(
- UserService $userService,
- TokenService $tokenService)
- {
- $this->userService = $userService;
- $this->tokenService = $tokenService;
- }
+ public function __construct(
+ UserService $userService,
+ TokenService $tokenService)
+ {
+ $this->userService = $userService;
+ $this->tokenService = $tokenService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/finish-password-reset/:tokenName';
- }
+ public function getUrl()
+ {
+ return '/api/finish-password-reset/:tokenName';
+ }
- public function work($args)
- {
- $token = $this->tokenService->getByName($args['tokenName']);
- return ['newPassword' => $this->userService->finishPasswordReset($token)];
- }
+ public function work($args)
+ {
+ $token = $this->tokenService->getByName($args['tokenName']);
+ return ['newPassword' => $this->userService->finishPasswordReset($token)];
+ }
}
diff --git a/src/Routes/Users/GetUser.php b/src/Routes/Users/GetUser.php
index c9c4a46b..c3d1209e 100644
--- a/src/Routes/Users/GetUser.php
+++ b/src/Routes/Users/GetUser.php
@@ -8,39 +8,39 @@ use Szurubooru\ViewProxies\UserViewProxy;
class GetUser extends AbstractUserRoute
{
- private $privilegeService;
- private $userService;
- private $userSearchParser;
- private $userViewProxy;
+ private $privilegeService;
+ private $userService;
+ private $userSearchParser;
+ private $userViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- UserService $userService,
- UserSearchParser $userSearchParser,
- UserViewProxy $userViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->userService = $userService;
- $this->userSearchParser = $userSearchParser;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ UserService $userService,
+ UserSearchParser $userSearchParser,
+ UserViewProxy $userViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->userService = $userService;
+ $this->userSearchParser = $userSearchParser;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/users/:userNameOrEmail';
- }
+ public function getUrl()
+ {
+ return '/api/users/:userNameOrEmail';
+ }
- public function work($args)
- {
- $userNameOrEmail = $args['userNameOrEmail'];
- if (!$this->privilegeService->isLoggedIn($userNameOrEmail))
- $this->privilegeService->assertPrivilege(Privilege::VIEW_USERS);
- $user = $this->userService->getByNameOrEmail($userNameOrEmail);
- return $this->userViewProxy->fromEntity($user);
- }
+ public function work($args)
+ {
+ $userNameOrEmail = $args['userNameOrEmail'];
+ if (!$this->privilegeService->isLoggedIn($userNameOrEmail))
+ $this->privilegeService->assertPrivilege(Privilege::VIEW_USERS);
+ $user = $this->userService->getByNameOrEmail($userNameOrEmail);
+ return $this->userViewProxy->fromEntity($user);
+ }
}
diff --git a/src/Routes/Users/GetUserAvatar.php b/src/Routes/Users/GetUserAvatar.php
index 41d18d76..0ea66a0b 100644
--- a/src/Routes/Users/GetUserAvatar.php
+++ b/src/Routes/Users/GetUserAvatar.php
@@ -9,87 +9,87 @@ use Szurubooru\Services\UserService;
class GetUserAvatar extends AbstractUserRoute
{
- private $fileDao;
- private $userService;
- private $networkingService;
- private $thumbnailService;
+ private $fileDao;
+ private $userService;
+ private $networkingService;
+ private $thumbnailService;
- public function __construct(
- PublicFileDao $fileDao,
- UserService $userService,
- NetworkingService $networkingService,
- ThumbnailService $thumbnailService)
- {
- $this->fileDao = $fileDao;
- $this->userService = $userService;
- $this->networkingService = $networkingService;
- $this->thumbnailService = $thumbnailService;
- }
+ public function __construct(
+ PublicFileDao $fileDao,
+ UserService $userService,
+ NetworkingService $networkingService,
+ ThumbnailService $thumbnailService)
+ {
+ $this->fileDao = $fileDao;
+ $this->userService = $userService;
+ $this->networkingService = $networkingService;
+ $this->thumbnailService = $thumbnailService;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/users/:userName/avatar/:size';
- }
+ public function getUrl()
+ {
+ return '/api/users/:userName/avatar/:size';
+ }
- public function work($args)
- {
- $userName = $args['userName'];
- $size = $args['size'];
+ public function work($args)
+ {
+ $userName = $args['userName'];
+ $size = $args['size'];
- try
- {
- $user = $this->userService->getByName($userName);
- }
- catch (\Exception $e)
- {
- $this->serveBlankFile($size);
- }
+ try
+ {
+ $user = $this->userService->getByName($userName);
+ }
+ catch (\Exception $e)
+ {
+ $this->serveBlankFile($size);
+ }
- switch ($user->getAvatarStyle())
- {
- case User::AVATAR_STYLE_GRAVATAR:
- $hash = md5(strtolower(trim($user->getEmail() ? $user->getEmail() : $user->getId() . $user->getName())));
- $url = 'https://www.gravatar.com/avatar/' . $hash . '?d=retro&s=' . $size;
- $this->serveFromUrl($url);
- break;
+ switch ($user->getAvatarStyle())
+ {
+ case User::AVATAR_STYLE_GRAVATAR:
+ $hash = md5(strtolower(trim($user->getEmail() ? $user->getEmail() : $user->getId() . $user->getName())));
+ $url = 'https://www.gravatar.com/avatar/' . $hash . '?d=retro&s=' . $size;
+ $this->serveFromUrl($url);
+ break;
- case User::AVATAR_STYLE_BLANK:
- $this->serveBlankFile($size);
- break;
+ case User::AVATAR_STYLE_BLANK:
+ $this->serveBlankFile($size);
+ break;
- case User::AVATAR_STYLE_MANUAL:
- $this->serveFromFile($user->getCustomAvatarSourceContentPath(), $size);
- break;
+ case User::AVATAR_STYLE_MANUAL:
+ $this->serveFromFile($user->getCustomAvatarSourceContentPath(), $size);
+ break;
- default:
- $this->serveBlankFile($size);
- break;
- }
- }
+ default:
+ $this->serveBlankFile($size);
+ break;
+ }
+ }
- private function serveFromUrl($url)
- {
- $this->networkingService->redirect($url);
- }
+ private function serveFromUrl($url)
+ {
+ $this->networkingService->redirect($url);
+ }
- private function serveFromFile($sourceName, $size)
- {
- $thumbnailName = $this->thumbnailService->generateIfNeeded($sourceName, $size, $size);
- $this->networkingService->serveFile($this->fileDao->getFullPath($thumbnailName));
- }
+ private function serveFromFile($sourceName, $size)
+ {
+ $thumbnailName = $this->thumbnailService->generateIfNeeded($sourceName, $size, $size);
+ $this->networkingService->serveFile($this->fileDao->getFullPath($thumbnailName));
+ }
- private function serveBlankFile($size)
- {
- $this->serveFromFile($this->getBlankAvatarSourceContentPath(), $size);
- }
+ private function serveBlankFile($size)
+ {
+ $this->serveFromFile($this->getBlankAvatarSourceContentPath(), $size);
+ }
- private function getBlankAvatarSourceContentPath()
- {
- return 'avatars/blank.png';
- }
+ private function getBlankAvatarSourceContentPath()
+ {
+ return 'avatars/blank.png';
+ }
}
diff --git a/src/Routes/Users/GetUsers.php b/src/Routes/Users/GetUsers.php
index 624e3717..b9a8a9a3 100644
--- a/src/Routes/Users/GetUsers.php
+++ b/src/Routes/Users/GetUsers.php
@@ -10,50 +10,50 @@ use Szurubooru\ViewProxies\UserViewProxy;
class GetUsers extends AbstractUserRoute
{
- private $config;
- private $privilegeService;
- private $userService;
- private $userSearchParser;
- private $inputReader;
- private $userViewProxy;
+ private $config;
+ private $privilegeService;
+ private $userService;
+ private $userSearchParser;
+ private $inputReader;
+ private $userViewProxy;
- public function __construct(
- Config $config,
- PrivilegeService $privilegeService,
- UserService $userService,
- UserSearchParser $userSearchParser,
- InputReader $inputReader,
- UserViewProxy $userViewProxy)
- {
- $this->config = $config;
- $this->privilegeService = $privilegeService;
- $this->userService = $userService;
- $this->userSearchParser = $userSearchParser;
- $this->inputReader = $inputReader;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ Config $config,
+ PrivilegeService $privilegeService,
+ UserService $userService,
+ UserSearchParser $userSearchParser,
+ InputReader $inputReader,
+ UserViewProxy $userViewProxy)
+ {
+ $this->config = $config;
+ $this->privilegeService = $privilegeService;
+ $this->userService = $userService;
+ $this->userSearchParser = $userSearchParser;
+ $this->inputReader = $inputReader;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['GET'];
- }
+ public function getMethods()
+ {
+ return ['GET'];
+ }
- public function getUrl()
- {
- return '/api/users';
- }
+ public function getUrl()
+ {
+ return '/api/users';
+ }
- public function work($args)
- {
- $this->privilegeService->assertPrivilege(Privilege::LIST_USERS);
+ public function work($args)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::LIST_USERS);
- $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
- $filter->setPageSize($this->config->users->usersPerPage);
- $result = $this->userService->getFiltered($filter);
- $entities = $this->userViewProxy->fromArray($result->getEntities());
- return [
- 'data' => $entities,
- 'pageSize' => $result->getPageSize(),
- 'totalRecords' => $result->getTotalRecords()];
- }
+ $filter = $this->userSearchParser->createFilterFromInputReader($this->inputReader);
+ $filter->setPageSize($this->config->users->usersPerPage);
+ $result = $this->userService->getFiltered($filter);
+ $entities = $this->userViewProxy->fromArray($result->getEntities());
+ return [
+ 'data' => $entities,
+ 'pageSize' => $result->getPageSize(),
+ 'totalRecords' => $result->getTotalRecords()];
+ }
}
diff --git a/src/Routes/Users/PasswordReset.php b/src/Routes/Users/PasswordReset.php
index 866ed808..b70344fc 100644
--- a/src/Routes/Users/PasswordReset.php
+++ b/src/Routes/Users/PasswordReset.php
@@ -4,24 +4,24 @@ use Szurubooru\Services\UserService;
class PasswordReset extends AbstractUserRoute
{
- public function __construct(UserService $userService)
- {
- $this->userService = $userService;
- }
+ public function __construct(UserService $userService)
+ {
+ $this->userService = $userService;
+ }
- public function getMethods()
- {
- return ['POST', 'PUT'];
- }
+ public function getMethods()
+ {
+ return ['POST', 'PUT'];
+ }
- public function getUrl()
- {
- return '/api/password-reset/:userNameOrEmail';
- }
+ public function getUrl()
+ {
+ return '/api/password-reset/:userNameOrEmail';
+ }
- public function work($args)
- {
- $user = $this->userService->getByNameOrEmail($args['userNameOrEmail']);
- return $this->userService->sendPasswordResetEmail($user);
- }
+ public function work($args)
+ {
+ $user = $this->userService->getByNameOrEmail($args['userNameOrEmail']);
+ return $this->userService->sendPasswordResetEmail($user);
+ }
}
diff --git a/src/Routes/Users/UpdateUser.php b/src/Routes/Users/UpdateUser.php
index 9d9d4775..e7c74072 100644
--- a/src/Routes/Users/UpdateUser.php
+++ b/src/Routes/Users/UpdateUser.php
@@ -9,88 +9,88 @@ use Szurubooru\ViewProxies\UserViewProxy;
class UpdateUser extends AbstractUserRoute
{
- private $privilegeService;
- private $userService;
- private $inputReader;
- private $userViewProxy;
+ private $privilegeService;
+ private $userService;
+ private $inputReader;
+ private $userViewProxy;
- public function __construct(
- PrivilegeService $privilegeService,
- UserService $userService,
- InputReader $inputReader,
- UserViewProxy $userViewProxy)
- {
- $this->privilegeService = $privilegeService;
- $this->userService = $userService;
- $this->inputReader = $inputReader;
- $this->userViewProxy = $userViewProxy;
- }
+ public function __construct(
+ PrivilegeService $privilegeService,
+ UserService $userService,
+ InputReader $inputReader,
+ UserViewProxy $userViewProxy)
+ {
+ $this->privilegeService = $privilegeService;
+ $this->userService = $userService;
+ $this->inputReader = $inputReader;
+ $this->userViewProxy = $userViewProxy;
+ }
- public function getMethods()
- {
- return ['POST'];
- }
+ public function getMethods()
+ {
+ return ['POST'];
+ }
- public function getUrl()
- {
- return '/api/users/:userNameOrEmail';
- }
+ public function getUrl()
+ {
+ return '/api/users/:userNameOrEmail';
+ }
- public function work($args)
- {
- $userNameOrEmail = $args['userNameOrEmail'];
+ public function work($args)
+ {
+ $userNameOrEmail = $args['userNameOrEmail'];
- $user = $this->userService->getByNameOrEmail($userNameOrEmail);
- $formData = new UserEditFormData($this->inputReader);
+ $user = $this->userService->getByNameOrEmail($userNameOrEmail);
+ $formData = new UserEditFormData($this->inputReader);
- if ($formData->avatarStyle !== null || $formData->avatarContent !== null)
- {
- $this->privilegeService->assertPrivilege(
- $this->privilegeService->isLoggedIn($userNameOrEmail)
- ? Privilege::CHANGE_OWN_AVATAR_STYLE
- : Privilege::CHANGE_ALL_AVATAR_STYLES);
- }
+ if ($formData->avatarStyle !== null || $formData->avatarContent !== null)
+ {
+ $this->privilegeService->assertPrivilege(
+ $this->privilegeService->isLoggedIn($userNameOrEmail)
+ ? Privilege::CHANGE_OWN_AVATAR_STYLE
+ : Privilege::CHANGE_ALL_AVATAR_STYLES);
+ }
- if ($formData->userName !== null)
- {
- $this->privilegeService->assertPrivilege(
- $this->privilegeService->isLoggedIn($userNameOrEmail)
- ? Privilege::CHANGE_OWN_NAME
- : Privilege::CHANGE_ALL_NAMES);
- }
+ if ($formData->userName !== null)
+ {
+ $this->privilegeService->assertPrivilege(
+ $this->privilegeService->isLoggedIn($userNameOrEmail)
+ ? Privilege::CHANGE_OWN_NAME
+ : Privilege::CHANGE_ALL_NAMES);
+ }
- if ($formData->password !== null)
- {
- $this->privilegeService->assertPrivilege(
- $this->privilegeService->isLoggedIn($userNameOrEmail)
- ? Privilege::CHANGE_OWN_PASSWORD
- : Privilege::CHANGE_ALL_PASSWORDS);
- }
+ if ($formData->password !== null)
+ {
+ $this->privilegeService->assertPrivilege(
+ $this->privilegeService->isLoggedIn($userNameOrEmail)
+ ? Privilege::CHANGE_OWN_PASSWORD
+ : Privilege::CHANGE_ALL_PASSWORDS);
+ }
- if ($formData->email !== null)
- {
- $this->privilegeService->assertPrivilege(
- $this->privilegeService->isLoggedIn($userNameOrEmail)
- ? Privilege::CHANGE_OWN_EMAIL_ADDRESS
- : Privilege::CHANGE_ALL_EMAIL_ADDRESSES);
- }
+ if ($formData->email !== null)
+ {
+ $this->privilegeService->assertPrivilege(
+ $this->privilegeService->isLoggedIn($userNameOrEmail)
+ ? Privilege::CHANGE_OWN_EMAIL_ADDRESS
+ : Privilege::CHANGE_ALL_EMAIL_ADDRESSES);
+ }
- if ($formData->accessRank)
- {
- $this->privilegeService->assertPrivilege(Privilege::CHANGE_ACCESS_RANK);
- }
+ if ($formData->accessRank)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::CHANGE_ACCESS_RANK);
+ }
- if ($formData->browsingSettings)
- {
- $this->privilegeService->assertLoggedIn($userNameOrEmail);
- }
+ if ($formData->browsingSettings)
+ {
+ $this->privilegeService->assertLoggedIn($userNameOrEmail);
+ }
- if ($formData->banned !== null)
- {
- $this->privilegeService->assertPrivilege(Privilege::BAN_USERS);
- }
+ if ($formData->banned !== null)
+ {
+ $this->privilegeService->assertPrivilege(Privilege::BAN_USERS);
+ }
- $user = $this->userService->updateUser($user, $formData);
- return $this->userViewProxy->fromEntity($user);
- }
+ $user = $this->userService->updateUser($user, $formData);
+ return $this->userViewProxy->fromEntity($user);
+ }
}
diff --git a/src/Search/Filters/BasicFilter.php b/src/Search/Filters/BasicFilter.php
index 41100c83..376a42e2 100644
--- a/src/Search/Filters/BasicFilter.php
+++ b/src/Search/Filters/BasicFilter.php
@@ -4,59 +4,59 @@ use Szurubooru\Search\Requirements\Requirement;
class BasicFilter implements IFilter
{
- private $order = [];
- private $requirements = [];
- private $pageNumber;
- private $pageSize;
+ private $order = [];
+ private $requirements = [];
+ private $pageNumber;
+ private $pageSize;
- public function getOrder()
- {
- return $this->order;
- }
+ public function getOrder()
+ {
+ return $this->order;
+ }
- public function setOrder($order)
- {
- $this->order = $order;
- }
+ public function setOrder($order)
+ {
+ $this->order = $order;
+ }
- public function addRequirement(Requirement $requirement)
- {
- $this->requirements[] = $requirement;
- }
+ public function addRequirement(Requirement $requirement)
+ {
+ $this->requirements[] = $requirement;
+ }
- public function getRequirements()
- {
- return $this->requirements;
- }
+ public function getRequirements()
+ {
+ return $this->requirements;
+ }
- public function getRequirementsByType($type)
- {
- $requirements = [];
- foreach ($this->getRequirements() as $key => $requirement)
- {
- if ($requirement->getType() === $type)
- $requirements[$key] = $requirement;
- }
- return $requirements;
- }
+ public function getRequirementsByType($type)
+ {
+ $requirements = [];
+ foreach ($this->getRequirements() as $key => $requirement)
+ {
+ if ($requirement->getType() === $type)
+ $requirements[$key] = $requirement;
+ }
+ return $requirements;
+ }
- public function getPageSize()
- {
- return $this->pageSize;
- }
+ public function getPageSize()
+ {
+ return $this->pageSize;
+ }
- public function setPageSize($pageSize)
- {
- $this->pageSize = $pageSize;
- }
+ public function setPageSize($pageSize)
+ {
+ $this->pageSize = $pageSize;
+ }
- public function getPageNumber()
- {
- return $this->pageNumber;
- }
+ public function getPageNumber()
+ {
+ return $this->pageNumber;
+ }
- public function setPageNumber($pageNumber)
- {
- $this->pageNumber = $pageNumber;
- }
+ public function setPageNumber($pageNumber)
+ {
+ $this->pageNumber = $pageNumber;
+ }
}
diff --git a/src/Search/Filters/CommentFilter.php b/src/Search/Filters/CommentFilter.php
index 7346425c..ddcba99e 100644
--- a/src/Search/Filters/CommentFilter.php
+++ b/src/Search/Filters/CommentFilter.php
@@ -3,12 +3,12 @@ namespace Szurubooru\Search\Filters;
class CommentFilter extends BasicFilter implements IFilter
{
- const ORDER_ID = 'id';
+ const ORDER_ID = 'id';
- const REQUIREMENT_POST_ID = 'postId';
+ const REQUIREMENT_POST_ID = 'postId';
- public function __construct()
- {
- $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
- }
+ public function __construct()
+ {
+ $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
+ }
}
diff --git a/src/Search/Filters/IFilter.php b/src/Search/Filters/IFilter.php
index 31fed929..22cd20d3 100644
--- a/src/Search/Filters/IFilter.php
+++ b/src/Search/Filters/IFilter.php
@@ -4,24 +4,24 @@ use Szurubooru\Search\Requirements\Requirement;
interface IFilter
{
- const ORDER_RANDOM = 'random';
+ const ORDER_RANDOM = 'random';
- const ORDER_ASC = 1;
- const ORDER_DESC = -1;
+ const ORDER_ASC = 1;
+ const ORDER_DESC = -1;
- public function getOrder();
+ public function getOrder();
- public function setOrder($order);
+ public function setOrder($order);
- public function getRequirements();
+ public function getRequirements();
- public function addRequirement(Requirement $requirement);
+ public function addRequirement(Requirement $requirement);
- public function getPageSize();
+ public function getPageSize();
- public function getPageNumber();
+ public function getPageNumber();
- public function setPageSize($pageSize);
+ public function setPageSize($pageSize);
- public function setPageNumber($pageNumber);
+ public function setPageNumber($pageNumber);
}
diff --git a/src/Search/Filters/PostFilter.php b/src/Search/Filters/PostFilter.php
index 2dbe3845..a90491f7 100644
--- a/src/Search/Filters/PostFilter.php
+++ b/src/Search/Filters/PostFilter.php
@@ -3,34 +3,34 @@ namespace Szurubooru\Search\Filters;
class PostFilter extends BasicFilter implements IFilter
{
- const ORDER_ID = 'id';
- const ORDER_FAV_COUNT = 'favCount';
- const ORDER_TAG_COUNT = 'tagCount';
- const ORDER_COMMENT_COUNT = 'commentCount';
- const ORDER_SCORE = 'score';
- const ORDER_LAST_EDIT_TIME = 'lastEditTime';
- const ORDER_FILE_SIZE = 'originalFileSize';
- const ORDER_LAST_COMMENT_TIME = 'lastCommentTime';
- const ORDER_LAST_FAV_TIME = 'lastFavTime';
- const ORDER_LAST_FEATURE_TIME = 'lastFeatureTime';
+ const ORDER_ID = 'id';
+ const ORDER_FAV_COUNT = 'favCount';
+ const ORDER_TAG_COUNT = 'tagCount';
+ const ORDER_COMMENT_COUNT = 'commentCount';
+ const ORDER_SCORE = 'score';
+ const ORDER_LAST_EDIT_TIME = 'lastEditTime';
+ const ORDER_FILE_SIZE = 'originalFileSize';
+ const ORDER_LAST_COMMENT_TIME = 'lastCommentTime';
+ const ORDER_LAST_FAV_TIME = 'lastFavTime';
+ const ORDER_LAST_FEATURE_TIME = 'lastFeatureTime';
- const REQUIREMENT_TAG = 'tag';
- const REQUIREMENT_ID = 'id';
- const REQUIREMENT_DATE = 'uploadTime';
- const REQUIREMENT_HASH = 'name';
- const REQUIREMENT_TAG_COUNT = 'tagCount';
- const REQUIREMENT_FAV_COUNT = 'favCount';
- const REQUIREMENT_COMMENT_COUNT = 'commentCount';
- const REQUIREMENT_SCORE = 'score';
- const REQUIREMENT_UPLOADER = 'uploader.name';
- const REQUIREMENT_SAFETY = 'safety';
- const REQUIREMENT_FAVORITE = 'favoritedBy.name';
- const REQUIREMENT_COMMENT_AUTHOR = 'commentedBy.name';
- const REQUIREMENT_TYPE = 'contentType';
- const REQUIREMENT_USER_SCORE = 'userScore';
+ const REQUIREMENT_TAG = 'tag';
+ const REQUIREMENT_ID = 'id';
+ const REQUIREMENT_DATE = 'uploadTime';
+ const REQUIREMENT_HASH = 'name';
+ const REQUIREMENT_TAG_COUNT = 'tagCount';
+ const REQUIREMENT_FAV_COUNT = 'favCount';
+ const REQUIREMENT_COMMENT_COUNT = 'commentCount';
+ const REQUIREMENT_SCORE = 'score';
+ const REQUIREMENT_UPLOADER = 'uploader.name';
+ const REQUIREMENT_SAFETY = 'safety';
+ const REQUIREMENT_FAVORITE = 'favoritedBy.name';
+ const REQUIREMENT_COMMENT_AUTHOR = 'commentedBy.name';
+ const REQUIREMENT_TYPE = 'contentType';
+ const REQUIREMENT_USER_SCORE = 'userScore';
- public function __construct()
- {
- $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
- }
+ public function __construct()
+ {
+ $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
+ }
}
diff --git a/src/Search/Filters/SnapshotFilter.php b/src/Search/Filters/SnapshotFilter.php
index 4fd14e60..e919a7ca 100644
--- a/src/Search/Filters/SnapshotFilter.php
+++ b/src/Search/Filters/SnapshotFilter.php
@@ -3,13 +3,13 @@ namespace Szurubooru\Search\Filters;
class SnapshotFilter extends BasicFilter implements IFilter
{
- const ORDER_ID = 'id';
+ const ORDER_ID = 'id';
- const REQUIREMENT_PRIMARY_KEY = 'primaryKey';
- const REQUIREMENT_TYPE = 'type';
+ const REQUIREMENT_PRIMARY_KEY = 'primaryKey';
+ const REQUIREMENT_TYPE = 'type';
- public function __construct()
- {
- $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
- }
+ public function __construct()
+ {
+ $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
+ }
}
diff --git a/src/Search/Filters/TagFilter.php b/src/Search/Filters/TagFilter.php
index 7d3b32ee..da7cb6f1 100644
--- a/src/Search/Filters/TagFilter.php
+++ b/src/Search/Filters/TagFilter.php
@@ -3,16 +3,16 @@ namespace Szurubooru\Search\Filters;
class TagFilter extends BasicFilter implements IFilter
{
- const ORDER_ID = 'id';
- const ORDER_NAME = 'name';
- const ORDER_CREATION_TIME = 'creationTime';
- const ORDER_USAGE_COUNT = 'usages';
+ const ORDER_ID = 'id';
+ const ORDER_NAME = 'name';
+ const ORDER_CREATION_TIME = 'creationTime';
+ const ORDER_USAGE_COUNT = 'usages';
- const REQUIREMENT_PARTIAL_TAG_NAME = 'partialTagName';
- const REQUIREMENT_CATEGORY = 'category';
+ const REQUIREMENT_PARTIAL_TAG_NAME = 'partialTagName';
+ const REQUIREMENT_CATEGORY = 'category';
- public function __construct()
- {
- $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
- }
+ public function __construct()
+ {
+ $this->setOrder([self::ORDER_ID => self::ORDER_DESC]);
+ }
}
diff --git a/src/Search/Filters/UserFilter.php b/src/Search/Filters/UserFilter.php
index cc87e3e7..40569387 100644
--- a/src/Search/Filters/UserFilter.php
+++ b/src/Search/Filters/UserFilter.php
@@ -3,11 +3,11 @@ namespace Szurubooru\Search\Filters;
class UserFilter extends BasicFilter implements IFilter
{
- const ORDER_NAME = 'name';
- const ORDER_REGISTRATION_TIME = 'registrationTime';
+ const ORDER_NAME = 'name';
+ const ORDER_REGISTRATION_TIME = 'registrationTime';
- public function __construct()
- {
- $this->setOrder([self::ORDER_NAME => self::ORDER_ASC]);
- }
+ public function __construct()
+ {
+ $this->setOrder([self::ORDER_NAME => self::ORDER_ASC]);
+ }
}
diff --git a/src/Search/Parsers/AbstractSearchParser.php b/src/Search/Parsers/AbstractSearchParser.php
index 3a859403..79c8fccb 100644
--- a/src/Search/Parsers/AbstractSearchParser.php
+++ b/src/Search/Parsers/AbstractSearchParser.php
@@ -11,180 +11,180 @@ use Szurubooru\Search\Tokens\SearchToken;
abstract class AbstractSearchParser
{
- const ALLOW_COMPOSITE = 1;
- const ALLOW_RANGES = 2;
+ const ALLOW_COMPOSITE = 1;
+ const ALLOW_RANGES = 2;
- public function createFilterFromInputReader(InputReader $inputReader)
- {
- $filter = $this->createFilter();
- $filter->setOrder($this->getOrder($inputReader->order, false) + $filter->getOrder());
+ public function createFilterFromInputReader(InputReader $inputReader)
+ {
+ $filter = $this->createFilter();
+ $filter->setOrder($this->getOrder($inputReader->order, false) + $filter->getOrder());
- if ($inputReader->page)
- {
- $filter->setPageNumber($inputReader->page);
- $filter->setPageSize(25);
- }
+ if ($inputReader->page)
+ {
+ $filter->setPageNumber($inputReader->page);
+ $filter->setPageSize(25);
+ }
- $tokens = $this->tokenize($inputReader->query);
+ $tokens = $this->tokenize($inputReader->query);
- foreach ($tokens as $token)
- {
- if ($token instanceof NamedSearchToken)
- {
- if ($token->getKey() === 'order')
- $filter->setOrder($this->getOrder($token->getValue(), $token->isNegated()) + $filter->getOrder());
- else
- $this->decorateFilterFromNamedToken($filter, $token);
- }
- elseif ($token instanceof SearchToken)
- $this->decorateFilterFromToken($filter, $token);
- else
- throw new \RuntimeException('Invalid search token type: ' . get_class($token));
- }
+ foreach ($tokens as $token)
+ {
+ if ($token instanceof NamedSearchToken)
+ {
+ if ($token->getKey() === 'order')
+ $filter->setOrder($this->getOrder($token->getValue(), $token->isNegated()) + $filter->getOrder());
+ else
+ $this->decorateFilterFromNamedToken($filter, $token);
+ }
+ elseif ($token instanceof SearchToken)
+ $this->decorateFilterFromToken($filter, $token);
+ else
+ throw new \RuntimeException('Invalid search token type: ' . get_class($token));
+ }
- return $filter;
- }
+ return $filter;
+ }
- protected abstract function createFilter();
+ protected abstract function createFilter();
- protected abstract function decorateFilterFromToken(IFilter $filter, SearchToken $token);
+ protected abstract function decorateFilterFromToken(IFilter $filter, SearchToken $token);
- protected abstract function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken);
+ protected abstract function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken);
- protected abstract function getOrderColumn($tokenText);
+ protected abstract function getOrderColumn($tokenText);
- protected function createRequirementValue($text, $flags = 0, callable $valueDecorator = null)
- {
- if ($valueDecorator === null)
- {
- $valueDecorator = function($value)
- {
- return $value;
- };
- }
+ protected function createRequirementValue($text, $flags = 0, callable $valueDecorator = null)
+ {
+ if ($valueDecorator === null)
+ {
+ $valueDecorator = function($value)
+ {
+ return $value;
+ };
+ }
- if ((($flags & self::ALLOW_RANGES) === self::ALLOW_RANGES) && substr_count($text, '..') === 1)
- {
- list ($minValue, $maxValue) = explode('..', $text);
- $minValue = $valueDecorator($minValue);
- $maxValue = $valueDecorator($maxValue);
- $tokenValue = new RequirementRangedValue();
- $tokenValue->setMinValue($minValue);
- $tokenValue->setMaxValue($maxValue);
- return $tokenValue;
- }
- else if ((($flags & self::ALLOW_COMPOSITE) === self::ALLOW_COMPOSITE) && strpos($text, ',') !== false)
- {
- $values = explode(',', $text);
- $values = array_map($valueDecorator, $values);
- $tokenValue = new RequirementCompositeValue();
- $tokenValue->setValues($values);
- return $tokenValue;
- }
+ if ((($flags & self::ALLOW_RANGES) === self::ALLOW_RANGES) && substr_count($text, '..') === 1)
+ {
+ list ($minValue, $maxValue) = explode('..', $text);
+ $minValue = $valueDecorator($minValue);
+ $maxValue = $valueDecorator($maxValue);
+ $tokenValue = new RequirementRangedValue();
+ $tokenValue->setMinValue($minValue);
+ $tokenValue->setMaxValue($maxValue);
+ return $tokenValue;
+ }
+ else if ((($flags & self::ALLOW_COMPOSITE) === self::ALLOW_COMPOSITE) && strpos($text, ',') !== false)
+ {
+ $values = explode(',', $text);
+ $values = array_map($valueDecorator, $values);
+ $tokenValue = new RequirementCompositeValue();
+ $tokenValue->setValues($values);
+ return $tokenValue;
+ }
- $value = $valueDecorator($text);
- return new RequirementSingleValue($value);
- }
+ $value = $valueDecorator($text);
+ return new RequirementSingleValue($value);
+ }
- protected function addRequirementFromToken($filter, $token, $type, $flags, callable $valueDecorator = null)
- {
- $requirement = new Requirement();
- $requirement->setType($type);
- $requirement->setValue($this->createRequirementValue($token->getValue(), $flags, $valueDecorator));
- $requirement->setNegated($token->isNegated());
- $filter->addRequirement($requirement);
- }
+ protected function addRequirementFromToken($filter, $token, $type, $flags, callable $valueDecorator = null)
+ {
+ $requirement = new Requirement();
+ $requirement->setType($type);
+ $requirement->setValue($this->createRequirementValue($token->getValue(), $flags, $valueDecorator));
+ $requirement->setNegated($token->isNegated());
+ $filter->addRequirement($requirement);
+ }
- private function getOrder($query, $negated)
- {
- $order = [];
- $tokens = array_filter(preg_split('/\s+/', trim($query)));
+ private function getOrder($query, $negated)
+ {
+ $order = [];
+ $tokens = array_filter(preg_split('/\s+/', trim($query)));
- foreach ($tokens as $token)
- {
- $token = preg_split('/,|\s+/', $token);
- $orderToken = $token[0];
+ foreach ($tokens as $token)
+ {
+ $token = preg_split('/,|\s+/', $token);
+ $orderToken = $token[0];
- if (count($token) === 1)
- {
- $orderDir = IFilter::ORDER_DESC;
- }
- elseif (count($token) === 2)
- {
- if ($token[1] === 'desc')
- $orderDir = IFilter::ORDER_DESC;
- elseif ($token[1] === 'asc')
- $orderDir = IFilter::ORDER_ASC;
- else
- throw new \Exception('Wrong search order direction');
- }
- else
- throw new \Exception('Wrong search order token');
+ if (count($token) === 1)
+ {
+ $orderDir = IFilter::ORDER_DESC;
+ }
+ elseif (count($token) === 2)
+ {
+ if ($token[1] === 'desc')
+ $orderDir = IFilter::ORDER_DESC;
+ elseif ($token[1] === 'asc')
+ $orderDir = IFilter::ORDER_ASC;
+ else
+ throw new \Exception('Wrong search order direction');
+ }
+ else
+ throw new \Exception('Wrong search order token');
- $orderColumn = $this->getOrderColumn($orderToken);
- if ($orderColumn === null)
- throw new \InvalidArgumentException('Invalid search order token: ' . $orderToken);
+ $orderColumn = $this->getOrderColumn($orderToken);
+ if ($orderColumn === null)
+ throw new \InvalidArgumentException('Invalid search order token: ' . $orderToken);
- if ($negated)
- {
- $orderDir = $orderDir == IFilter::ORDER_DESC ? IFilter::ORDER_ASC : IFilter::ORDER_DESC;
- }
+ if ($negated)
+ {
+ $orderDir = $orderDir == IFilter::ORDER_DESC ? IFilter::ORDER_ASC : IFilter::ORDER_DESC;
+ }
- $order[$orderColumn] = $orderDir;
- }
+ $order[$orderColumn] = $orderDir;
+ }
- return $order;
- }
+ return $order;
+ }
- private function tokenize($query)
- {
- $searchTokens = [];
+ private function tokenize($query)
+ {
+ $searchTokens = [];
- foreach (array_filter(preg_split('/\s+/', trim($query))) as $tokenText)
- {
- $negated = false;
- if (substr($tokenText, 0, 1) === '-')
- {
- $negated = true;
- $tokenText = substr($tokenText, 1);
- }
+ foreach (array_filter(preg_split('/\s+/', trim($query))) as $tokenText)
+ {
+ $negated = false;
+ if (substr($tokenText, 0, 1) === '-')
+ {
+ $negated = true;
+ $tokenText = substr($tokenText, 1);
+ }
- $colonPosition = strpos($tokenText, ':');
- if (($colonPosition !== false) && ($colonPosition > 0))
- {
- $searchToken = new NamedSearchToken();
- list ($tokenKey, $tokenValue) = explode(':', $tokenText, 2);
- $searchToken->setKey($tokenKey);
- $searchToken->setValue($tokenValue);
- }
- else
- {
- $searchToken = new SearchToken();
- $searchToken->setValue($tokenText);
- }
+ $colonPosition = strpos($tokenText, ':');
+ if (($colonPosition !== false) && ($colonPosition > 0))
+ {
+ $searchToken = new NamedSearchToken();
+ list ($tokenKey, $tokenValue) = explode(':', $tokenText, 2);
+ $searchToken->setKey($tokenKey);
+ $searchToken->setValue($tokenValue);
+ }
+ else
+ {
+ $searchToken = new SearchToken();
+ $searchToken->setValue($tokenText);
+ }
- $searchToken->setNegated($negated);
- $searchTokens[] = $searchToken;
- }
+ $searchToken->setNegated($negated);
+ $searchTokens[] = $searchToken;
+ }
- return $searchTokens;
- }
+ return $searchTokens;
+ }
- protected function matches($text, $array)
- {
- $text = $this->transformText($text);
- foreach ($array as $elem)
- {
- if ($this->transformText($elem) === $text)
- return true;
- }
- return false;
- }
+ protected function matches($text, $array)
+ {
+ $text = $this->transformText($text);
+ foreach ($array as $elem)
+ {
+ if ($this->transformText($elem) === $text)
+ return true;
+ }
+ return false;
+ }
- protected function transformText($text)
- {
- return str_replace('_', '', strtolower($text));
- }
+ protected function transformText($text)
+ {
+ return str_replace('_', '', strtolower($text));
+ }
}
diff --git a/src/Search/Parsers/PostSearchParser.php b/src/Search/Parsers/PostSearchParser.php
index 8dcf7ce9..a8d33893 100644
--- a/src/Search/Parsers/PostSearchParser.php
+++ b/src/Search/Parsers/PostSearchParser.php
@@ -13,359 +13,359 @@ use Szurubooru\Services\PrivilegeService;
class PostSearchParser extends AbstractSearchParser
{
- private $authService;
- private $privilegeService;
+ private $authService;
+ private $privilegeService;
- public function __construct(
- AuthService $authService,
- PrivilegeService $privilegeService)
- {
- $this->authService = $authService;
- $this->privilegeService = $privilegeService;
- }
+ public function __construct(
+ AuthService $authService,
+ PrivilegeService $privilegeService)
+ {
+ $this->authService = $authService;
+ $this->privilegeService = $privilegeService;
+ }
- protected function createFilter()
- {
- return new PostFilter;
- }
+ protected function createFilter()
+ {
+ return new PostFilter;
+ }
- protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
- {
- $requirement = new Requirement();
- $requirement->setType(PostFilter::REQUIREMENT_TAG);
- $requirement->setValue($this->createRequirementValue($token->getValue()));
- $requirement->setNegated($token->isNegated());
- $filter->addRequirement($requirement);
- }
+ protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
+ {
+ $requirement = new Requirement();
+ $requirement->setType(PostFilter::REQUIREMENT_TAG);
+ $requirement->setValue($this->createRequirementValue($token->getValue()));
+ $requirement->setNegated($token->isNegated());
+ $filter->addRequirement($requirement);
+ }
- protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $token)
- {
- $tokenKey = $token->getKey();
- $tokenValue = $token->getValue();
+ protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $token)
+ {
+ $tokenKey = $token->getKey();
+ $tokenValue = $token->getValue();
- $countAliases =
- [
- 'tag_count' => 'tags',
- 'fav_count' => 'favs',
- 'score' => 'score',
- 'comment_count' => 'comments',
- ];
- foreach ($countAliases as $realKey => $baseAlias)
- {
- if ($this->matches($tokenKey, [$baseAlias . '_min', $baseAlias . '_max']))
- {
- $token = new NamedSearchToken();
- $token->setKey($realKey);
- $token->setValue(strpos($tokenKey, 'min') !== false ? $tokenValue . '..' : '..' . $tokenValue);
- return $this->decorateFilterFromNamedToken($filter, $token);
- }
- }
+ $countAliases =
+ [
+ 'tag_count' => 'tags',
+ 'fav_count' => 'favs',
+ 'score' => 'score',
+ 'comment_count' => 'comments',
+ ];
+ foreach ($countAliases as $realKey => $baseAlias)
+ {
+ if ($this->matches($tokenKey, [$baseAlias . '_min', $baseAlias . '_max']))
+ {
+ $token = new NamedSearchToken();
+ $token->setKey($realKey);
+ $token->setValue(strpos($tokenKey, 'min') !== false ? $tokenValue . '..' : '..' . $tokenValue);
+ return $this->decorateFilterFromNamedToken($filter, $token);
+ }
+ }
- $map =
- [
- [['id'], [$this, 'addIdRequirement']],
- [['hash', 'name'], [$this, 'addHashRequirement']],
- [['date', 'time'], [$this, 'addDateRequirement']],
- [['tag_count', 'tags'], [$this, 'addTagCountRequirement']],
- [['fav_count', 'favs'], [$this, 'addFavCountRequirement']],
- [['comment_count', 'comments'], [$this, 'addCommentCountRequirement']],
- [['score'], [$this, 'addScoreRequirement']],
- [['uploader', 'uploader', 'uploaded', 'submit', 'submitter', 'submitted'], [$this, 'addUploaderRequirement']],
- [['safety', 'rating'], [$this, 'addSafetyRequirement']],
- [['fav'], [$this, 'addFavRequirement']],
- [['type'], [$this, 'addTypeRequirement']],
- [['comment', 'comment_author', 'commented'], [$this, 'addCommentAuthorRequirement']],
- ];
+ $map =
+ [
+ [['id'], [$this, 'addIdRequirement']],
+ [['hash', 'name'], [$this, 'addHashRequirement']],
+ [['date', 'time'], [$this, 'addDateRequirement']],
+ [['tag_count', 'tags'], [$this, 'addTagCountRequirement']],
+ [['fav_count', 'favs'], [$this, 'addFavCountRequirement']],
+ [['comment_count', 'comments'], [$this, 'addCommentCountRequirement']],
+ [['score'], [$this, 'addScoreRequirement']],
+ [['uploader', 'uploader', 'uploaded', 'submit', 'submitter', 'submitted'], [$this, 'addUploaderRequirement']],
+ [['safety', 'rating'], [$this, 'addSafetyRequirement']],
+ [['fav'], [$this, 'addFavRequirement']],
+ [['type'], [$this, 'addTypeRequirement']],
+ [['comment', 'comment_author', 'commented'], [$this, 'addCommentAuthorRequirement']],
+ ];
- foreach ($map as $item)
- {
- list ($aliases, $callback) = $item;
- if ($this->matches($tokenKey, $aliases))
- return $callback($filter, $token);
- }
+ foreach ($map as $item)
+ {
+ list ($aliases, $callback) = $item;
+ if ($this->matches($tokenKey, $aliases))
+ return $callback($filter, $token);
+ }
- if ($this->matches($tokenKey, ['special']))
- {
- $specialMap =
- [
- [['liked'], [$this, 'addOwnLikedRequirement']],
- [['disliked'], [$this, 'addOwnDislikedRequirement']],
- [['fav'], [$this, 'addOwnFavRequirement']],
- ];
+ if ($this->matches($tokenKey, ['special']))
+ {
+ $specialMap =
+ [
+ [['liked'], [$this, 'addOwnLikedRequirement']],
+ [['disliked'], [$this, 'addOwnDislikedRequirement']],
+ [['fav'], [$this, 'addOwnFavRequirement']],
+ ];
- foreach ($specialMap as $item)
- {
- list ($aliases, $callback) = $item;
- if ($this->matches($token->getValue(), $aliases))
- return $callback($filter, $token);
- }
+ foreach ($specialMap as $item)
+ {
+ list ($aliases, $callback) = $item;
+ if ($this->matches($token->getValue(), $aliases))
+ return $callback($filter, $token);
+ }
- throw new NotSupportedException(
- 'Unknown value for special search term: ' . $token->getValue()
- . '. Possible search terms: '
- . join(', ', array_map(function($term) { return join('/', $term[0]); }, $specialMap)));
- }
+ throw new NotSupportedException(
+ 'Unknown value for special search term: ' . $token->getValue()
+ . '. Possible search terms: '
+ . join(', ', array_map(function($term) { return join('/', $term[0]); }, $specialMap)));
+ }
- throw new NotSupportedException('Unknown search term: ' . $token->getKey()
- . '. Possible search terms: special, '
- . join(', ', array_map(function($term) { return join('/', $term[0]); }, $map)));
- }
+ throw new NotSupportedException('Unknown search term: ' . $token->getKey()
+ . '. Possible search terms: special, '
+ . join(', ', array_map(function($term) { return join('/', $term[0]); }, $map)));
+ }
- protected function getOrderColumn($tokenText)
- {
- if ($this->matches($tokenText, ['random']))
- return PostFilter::ORDER_RANDOM;
+ protected function getOrderColumn($tokenText)
+ {
+ if ($this->matches($tokenText, ['random']))
+ return PostFilter::ORDER_RANDOM;
- if ($this->matches($tokenText, ['id']))
- return PostFilter::ORDER_ID;
+ if ($this->matches($tokenText, ['id']))
+ return PostFilter::ORDER_ID;
- if ($this->matches($tokenText, ['time', 'date']))
- return PostFilter::ORDER_LAST_EDIT_TIME;
+ if ($this->matches($tokenText, ['time', 'date']))
+ return PostFilter::ORDER_LAST_EDIT_TIME;
- if ($this->matches($tokenText, ['score']))
- return PostFilter::ORDER_SCORE;
+ if ($this->matches($tokenText, ['score']))
+ return PostFilter::ORDER_SCORE;
- if ($this->matches($tokenText, ['file_size']))
- return PostFilter::ORDER_FILE_SIZE;
+ if ($this->matches($tokenText, ['file_size']))
+ return PostFilter::ORDER_FILE_SIZE;
- if ($this->matches($tokenText, ['tag_count', 'tags', 'tag']))
- return PostFilter::ORDER_TAG_COUNT;
+ if ($this->matches($tokenText, ['tag_count', 'tags', 'tag']))
+ return PostFilter::ORDER_TAG_COUNT;
- if ($this->matches($tokenText, ['fav_count', 'fags', 'fav']))
- return PostFilter::ORDER_FAV_COUNT;
+ if ($this->matches($tokenText, ['fav_count', 'fags', 'fav']))
+ return PostFilter::ORDER_FAV_COUNT;
- if ($this->matches($tokenText, ['comment_count', 'comments', 'comment']))
- return PostFilter::ORDER_COMMENT_COUNT;
+ if ($this->matches($tokenText, ['comment_count', 'comments', 'comment']))
+ return PostFilter::ORDER_COMMENT_COUNT;
- if ($this->matches($tokenText, ['fav_time', 'fav_date']))
- return PostFilter::ORDER_LAST_FAV_TIME;
+ if ($this->matches($tokenText, ['fav_time', 'fav_date']))
+ return PostFilter::ORDER_LAST_FAV_TIME;
- if ($this->matches($tokenText, ['comment_time', 'comment_date']))
- return PostFilter::ORDER_LAST_COMMENT_TIME;
+ if ($this->matches($tokenText, ['comment_time', 'comment_date']))
+ return PostFilter::ORDER_LAST_COMMENT_TIME;
- if ($this->matches($tokenText, ['feature_time', 'feature_date', 'featured', 'feature']))
- return PostFilter::ORDER_LAST_FEATURE_TIME;
+ if ($this->matches($tokenText, ['feature_time', 'feature_date', 'featured', 'feature']))
+ return PostFilter::ORDER_LAST_FEATURE_TIME;
- throw new NotSupportedException();
- }
+ throw new NotSupportedException();
+ }
- private function addOwnLikedRequirement($filter, $token)
- {
- $this->privilegeService->assertLoggedIn();
- $this->addUserScoreRequirement(
- $filter,
- $this->authService->getLoggedInUser()->getName(),
- 1,
- $token->isNegated());
- }
+ private function addOwnLikedRequirement($filter, $token)
+ {
+ $this->privilegeService->assertLoggedIn();
+ $this->addUserScoreRequirement(
+ $filter,
+ $this->authService->getLoggedInUser()->getName(),
+ 1,
+ $token->isNegated());
+ }
- private function addOwnDislikedRequirement($filter, $token)
- {
- $this->privilegeService->assertLoggedIn();
- $this->addUserScoreRequirement(
- $filter,
- $this->authService->getLoggedInUser()->getName(),
- -1,
- $token->isNegated());
- }
+ private function addOwnDislikedRequirement($filter, $token)
+ {
+ $this->privilegeService->assertLoggedIn();
+ $this->addUserScoreRequirement(
+ $filter,
+ $this->authService->getLoggedInUser()->getName(),
+ -1,
+ $token->isNegated());
+ }
- private function addOwnFavRequirement($filter, $token)
- {
- $this->privilegeService->assertLoggedIn();
- $token = new NamedSearchToken();
- $token->setKey('fav');
- $token->setValue($this->authService->getLoggedInUser()->getName());
- $this->decorateFilterFromNamedToken($filter, $token);
- }
+ private function addOwnFavRequirement($filter, $token)
+ {
+ $this->privilegeService->assertLoggedIn();
+ $token = new NamedSearchToken();
+ $token->setKey('fav');
+ $token->setValue($this->authService->getLoggedInUser()->getName());
+ $this->decorateFilterFromNamedToken($filter, $token);
+ }
- private function addIdRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_ID,
- self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
- }
+ private function addIdRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_ID,
+ self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
+ }
- private function addHashRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_HASH,
- self::ALLOW_COMPOSITE);
- }
+ private function addHashRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_HASH,
+ self::ALLOW_COMPOSITE);
+ }
- private function addDateRequirement($filter, $token)
- {
- if (substr_count($token->getValue(), '..') === 1)
- {
- list ($dateMin, $dateMax) = explode('..', $token->getValue());
- $timeMin = $this->dateToTime($dateMin)[0];
- $timeMax = $this->dateToTime($dateMax)[1];
- }
- else
- {
- $date = $token->getValue();
- list ($timeMin, $timeMax) = $this->dateToTime($date);
- }
+ private function addDateRequirement($filter, $token)
+ {
+ if (substr_count($token->getValue(), '..') === 1)
+ {
+ list ($dateMin, $dateMax) = explode('..', $token->getValue());
+ $timeMin = $this->dateToTime($dateMin)[0];
+ $timeMax = $this->dateToTime($dateMax)[1];
+ }
+ else
+ {
+ $date = $token->getValue();
+ list ($timeMin, $timeMax) = $this->dateToTime($date);
+ }
- $finalString = '';
- if ($timeMin)
- $finalString .= date('c', $timeMin);
- $finalString .= '..';
- if ($timeMax)
- $finalString .= date('c', $timeMax);
+ $finalString = '';
+ if ($timeMin)
+ $finalString .= date('c', $timeMin);
+ $finalString .= '..';
+ if ($timeMax)
+ $finalString .= date('c', $timeMax);
- $token->setValue($finalString);
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_DATE,
- self::ALLOW_RANGES);
- }
+ $token->setValue($finalString);
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_DATE,
+ self::ALLOW_RANGES);
+ }
- private function addTagCountRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_TAG_COUNT,
- self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
- }
+ private function addTagCountRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_TAG_COUNT,
+ self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
+ }
- private function addFavCountRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_FAV_COUNT,
- self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
- }
+ private function addFavCountRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_FAV_COUNT,
+ self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
+ }
- private function addCommentCountRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_COMMENT_COUNT,
- self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
- }
+ private function addCommentCountRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_COMMENT_COUNT,
+ self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
+ }
- private function addScoreRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_SCORE,
- self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
- }
+ private function addScoreRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_SCORE,
+ self::ALLOW_COMPOSITE | self::ALLOW_RANGES);
+ }
- private function addUploaderRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_UPLOADER,
- self::ALLOW_COMPOSITE);
- }
+ private function addUploaderRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_UPLOADER,
+ self::ALLOW_COMPOSITE);
+ }
- private function addSafetyRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_SAFETY,
- self::ALLOW_COMPOSITE,
- function ($value)
- {
- return EnumHelper::postSafetyFromString($value);
- });
- }
+ private function addSafetyRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_SAFETY,
+ self::ALLOW_COMPOSITE,
+ function ($value)
+ {
+ return EnumHelper::postSafetyFromString($value);
+ });
+ }
- private function addFavRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_FAVORITE,
- self::ALLOW_COMPOSITE);
- }
+ private function addFavRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_FAVORITE,
+ self::ALLOW_COMPOSITE);
+ }
- private function addTypeRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_TYPE,
- self::ALLOW_COMPOSITE,
- function ($value)
- {
- return EnumHelper::postTypeFromString($value);
- });
- }
+ private function addTypeRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_TYPE,
+ self::ALLOW_COMPOSITE,
+ function ($value)
+ {
+ return EnumHelper::postTypeFromString($value);
+ });
+ }
- private function addCommentAuthorRequirement($filter, $token)
- {
- $this->addRequirementFromToken(
- $filter,
- $token,
- PostFilter::REQUIREMENT_COMMENT_AUTHOR,
- self::ALLOW_COMPOSITE);
- }
+ private function addCommentAuthorRequirement($filter, $token)
+ {
+ $this->addRequirementFromToken(
+ $filter,
+ $token,
+ PostFilter::REQUIREMENT_COMMENT_AUTHOR,
+ self::ALLOW_COMPOSITE);
+ }
- private function addUserScoreRequirement($filter, $userName, $score, $isNegated)
- {
- $tokenValue = new RequirementCompositeValue();
- $tokenValue->setValues([$userName, $score]);
- $requirement = new Requirement();
- $requirement->setType(PostFilter::REQUIREMENT_USER_SCORE);
- $requirement->setValue($tokenValue);
- $requirement->setNegated($isNegated);
- $filter->addRequirement($requirement);
- }
+ private function addUserScoreRequirement($filter, $userName, $score, $isNegated)
+ {
+ $tokenValue = new RequirementCompositeValue();
+ $tokenValue->setValues([$userName, $score]);
+ $requirement = new Requirement();
+ $requirement->setType(PostFilter::REQUIREMENT_USER_SCORE);
+ $requirement->setValue($tokenValue);
+ $requirement->setNegated($isNegated);
+ $filter->addRequirement($requirement);
+ }
- private function dateToTime($value)
- {
- $value = strtolower(trim($value));
- if (!$value)
- {
- return null;
- }
- elseif ($value === 'today')
- {
- $timeMin = mktime(0, 0, 0);
- $timeMax = mktime(24, 0, -1);
- }
- elseif ($value === 'yesterday')
- {
- $timeMin = mktime(-24, 0, 0);
- $timeMax = mktime(0, 0, -1);
- }
- elseif (preg_match('/^(\d{4})$/', $value, $matches))
- {
- $year = intval($matches[1]);
- $timeMin = mktime(0, 0, 0, 1, 1, $year);
- $timeMax = mktime(0, 0, -1, 1, 1, $year + 1);
- }
- elseif (preg_match('/^(\d{4})-(\d{1,2})$/', $value, $matches))
- {
- $year = intval($matches[1]);
- $month = intval($matches[2]);
- $timeMin = mktime(0, 0, 0, $month, 1, $year);
- $timeMax = mktime(0, 0, -1, $month + 1, 1, $year);
- }
- elseif (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value, $matches))
- {
- $year = intval($matches[1]);
- $month = intval($matches[2]);
- $day = intval($matches[3]);
- $timeMin = mktime(0, 0, 0, $month, $day, $year);
- $timeMax = mktime(0, 0, -1, $month, $day + 1, $year);
- }
- else
- throw new \Exception('Invalid date format: ' . $value);
+ private function dateToTime($value)
+ {
+ $value = strtolower(trim($value));
+ if (!$value)
+ {
+ return null;
+ }
+ elseif ($value === 'today')
+ {
+ $timeMin = mktime(0, 0, 0);
+ $timeMax = mktime(24, 0, -1);
+ }
+ elseif ($value === 'yesterday')
+ {
+ $timeMin = mktime(-24, 0, 0);
+ $timeMax = mktime(0, 0, -1);
+ }
+ elseif (preg_match('/^(\d{4})$/', $value, $matches))
+ {
+ $year = intval($matches[1]);
+ $timeMin = mktime(0, 0, 0, 1, 1, $year);
+ $timeMax = mktime(0, 0, -1, 1, 1, $year + 1);
+ }
+ elseif (preg_match('/^(\d{4})-(\d{1,2})$/', $value, $matches))
+ {
+ $year = intval($matches[1]);
+ $month = intval($matches[2]);
+ $timeMin = mktime(0, 0, 0, $month, 1, $year);
+ $timeMax = mktime(0, 0, -1, $month + 1, 1, $year);
+ }
+ elseif (preg_match('/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value, $matches))
+ {
+ $year = intval($matches[1]);
+ $month = intval($matches[2]);
+ $day = intval($matches[3]);
+ $timeMin = mktime(0, 0, 0, $month, $day, $year);
+ $timeMax = mktime(0, 0, -1, $month, $day + 1, $year);
+ }
+ else
+ throw new \Exception('Invalid date format: ' . $value);
- return [$timeMin, $timeMax];
- }
+ return [$timeMin, $timeMax];
+ }
}
diff --git a/src/Search/Parsers/SnapshotSearchParser.php b/src/Search/Parsers/SnapshotSearchParser.php
index 2b531e81..caa76532 100644
--- a/src/Search/Parsers/SnapshotSearchParser.php
+++ b/src/Search/Parsers/SnapshotSearchParser.php
@@ -10,39 +10,39 @@ use Szurubooru\Search\Tokens\SearchToken;
class SnapshotSearchParser extends AbstractSearchParser
{
- protected function createFilter()
- {
- return new SnapshotFilter;
- }
+ protected function createFilter()
+ {
+ return new SnapshotFilter;
+ }
- protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
- {
- if (substr_count($token->getValue(), ',') !== 1)
- throw new NotSupportedException();
+ protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
+ {
+ if (substr_count($token->getValue(), ',') !== 1)
+ throw new NotSupportedException();
- if ($token->isNegated())
- throw new NotSupportedException();
+ if ($token->isNegated())
+ throw new NotSupportedException();
- list ($type, $primaryKey) = explode(',', $token->getValue());
+ list ($type, $primaryKey) = explode(',', $token->getValue());
- $requirement = new Requirement();
- $requirement->setType(SnapshotFilter::REQUIREMENT_PRIMARY_KEY);
- $requirement->setValue($this->createRequirementValue($primaryKey));
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setType(SnapshotFilter::REQUIREMENT_PRIMARY_KEY);
+ $requirement->setValue($this->createRequirementValue($primaryKey));
+ $filter->addRequirement($requirement);
- $requirement = new Requirement();
- $requirement->setType(SnapshotFilter::REQUIREMENT_TYPE);
- $requirement->setValue($this->createRequirementValue(EnumHelper::snapshotTypeFromString($type)));
- $filter->addRequirement($requirement);
- }
+ $requirement = new Requirement();
+ $requirement->setType(SnapshotFilter::REQUIREMENT_TYPE);
+ $requirement->setValue($this->createRequirementValue(EnumHelper::snapshotTypeFromString($type)));
+ $filter->addRequirement($requirement);
+ }
- protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken)
- {
- throw new NotSupportedException();
- }
+ protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken)
+ {
+ throw new NotSupportedException();
+ }
- protected function getOrderColumn($tokenText)
- {
- throw new NotSupportedException();
- }
+ protected function getOrderColumn($tokenText)
+ {
+ throw new NotSupportedException();
+ }
}
diff --git a/src/Search/Parsers/TagSearchParser.php b/src/Search/Parsers/TagSearchParser.php
index 45f5be27..a271d3dc 100644
--- a/src/Search/Parsers/TagSearchParser.php
+++ b/src/Search/Parsers/TagSearchParser.php
@@ -10,48 +10,48 @@ use Szurubooru\Search\Tokens\SearchToken;
class TagSearchParser extends AbstractSearchParser
{
- protected function createFilter()
- {
- return new TagFilter;
- }
+ protected function createFilter()
+ {
+ return new TagFilter;
+ }
- protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
- {
- $requirement = new Requirement();
- $requirement->setType(TagFilter::REQUIREMENT_PARTIAL_TAG_NAME);
- $requirement->setValue(new RequirementSingleValue($token->getValue()));
- $requirement->setNegated($token->isNegated());
- $filter->addRequirement($requirement);
- }
+ protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
+ {
+ $requirement = new Requirement();
+ $requirement->setType(TagFilter::REQUIREMENT_PARTIAL_TAG_NAME);
+ $requirement->setValue(new RequirementSingleValue($token->getValue()));
+ $requirement->setNegated($token->isNegated());
+ $filter->addRequirement($requirement);
+ }
- protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken)
- {
- if ($this->matches($namedToken->getKey(), ['category']))
- {
- return $this->addRequirementFromToken(
- $filter,
- $namedToken,
- TagFilter::REQUIREMENT_CATEGORY,
- self::ALLOW_COMPOSITE);
- }
+ protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken)
+ {
+ if ($this->matches($namedToken->getKey(), ['category']))
+ {
+ return $this->addRequirementFromToken(
+ $filter,
+ $namedToken,
+ TagFilter::REQUIREMENT_CATEGORY,
+ self::ALLOW_COMPOSITE);
+ }
- throw new NotSupportedException();
- }
+ throw new NotSupportedException();
+ }
- protected function getOrderColumn($tokenText)
- {
- if ($this->matches($tokenText, ['id']))
- return TagFilter::ORDER_ID;
+ protected function getOrderColumn($tokenText)
+ {
+ if ($this->matches($tokenText, ['id']))
+ return TagFilter::ORDER_ID;
- if ($this->matches($tokenText, ['name']))
- return TagFilter::ORDER_NAME;
+ if ($this->matches($tokenText, ['name']))
+ return TagFilter::ORDER_NAME;
- if ($this->matches($tokenText, ['creation_time', 'creation_date']))
- return TagFilter::ORDER_CREATION_TIME;
+ if ($this->matches($tokenText, ['creation_time', 'creation_date']))
+ return TagFilter::ORDER_CREATION_TIME;
- if ($this->matches($tokenText, ['usage_count', 'usages']))
- return TagFilter::ORDER_USAGE_COUNT;
+ if ($this->matches($tokenText, ['usage_count', 'usages']))
+ return TagFilter::ORDER_USAGE_COUNT;
- throw new NotSupportedException();
- }
+ throw new NotSupportedException();
+ }
}
diff --git a/src/Search/Parsers/UserSearchParser.php b/src/Search/Parsers/UserSearchParser.php
index 6a360c5a..143a9b4b 100644
--- a/src/Search/Parsers/UserSearchParser.php
+++ b/src/Search/Parsers/UserSearchParser.php
@@ -8,29 +8,29 @@ use Szurubooru\Search\Tokens\SearchToken;
class UserSearchParser extends AbstractSearchParser
{
- protected function createFilter()
- {
- return new UserFilter;
- }
+ protected function createFilter()
+ {
+ return new UserFilter;
+ }
- protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
- {
- throw new NotSupportedException();
- }
+ protected function decorateFilterFromToken(IFilter $filter, SearchToken $token)
+ {
+ throw new NotSupportedException();
+ }
- protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken)
- {
- throw new NotSupportedException();
- }
+ protected function decorateFilterFromNamedToken(IFilter $filter, NamedSearchToken $namedToken)
+ {
+ throw new NotSupportedException();
+ }
- protected function getOrderColumn($tokenText)
- {
- if ($this->matches($tokenText, ['name']))
- return UserFilter::ORDER_NAME;
+ protected function getOrderColumn($tokenText)
+ {
+ if ($this->matches($tokenText, ['name']))
+ return UserFilter::ORDER_NAME;
- if ($this->matches($tokenText, ['registration_time', 'registration_date']))
- return UserFilter::ORDER_REGISTRATION_TIME;
+ if ($this->matches($tokenText, ['registration_time', 'registration_date']))
+ return UserFilter::ORDER_REGISTRATION_TIME;
- throw new NotSupportedException();
- }
+ throw new NotSupportedException();
+ }
}
diff --git a/src/Search/Requirements/IRequirementValue.php b/src/Search/Requirements/IRequirementValue.php
index 17befaa8..9ff7472c 100644
--- a/src/Search/Requirements/IRequirementValue.php
+++ b/src/Search/Requirements/IRequirementValue.php
@@ -3,5 +3,5 @@ namespace Szurubooru\Search\Requirements;
interface IRequirementValue
{
- public function getValues();
+ public function getValues();
}
diff --git a/src/Search/Requirements/Requirement.php b/src/Search/Requirements/Requirement.php
index e73c35a7..9f22eec7 100644
--- a/src/Search/Requirements/Requirement.php
+++ b/src/Search/Requirements/Requirement.php
@@ -3,37 +3,37 @@ namespace Szurubooru\Search\Requirements;
class Requirement
{
- private $negated = false;
- private $type;
- private $value;
+ private $negated = false;
+ private $type;
+ private $value;
- public function isNegated()
- {
- return $this->negated;
- }
+ public function isNegated()
+ {
+ return $this->negated;
+ }
- public function setNegated($negated)
- {
- $this->negated = $negated;
- }
+ public function setNegated($negated)
+ {
+ $this->negated = $negated;
+ }
- public function getType()
- {
- return $this->type;
- }
+ public function getType()
+ {
+ return $this->type;
+ }
- public function setType($type)
- {
- $this->type = $type;
- }
+ public function setType($type)
+ {
+ $this->type = $type;
+ }
- public function getValue()
- {
- return $this->value;
- }
+ public function getValue()
+ {
+ return $this->value;
+ }
- public function setValue(IRequirementValue $value)
- {
- $this->value = $value;
- }
+ public function setValue(IRequirementValue $value)
+ {
+ $this->value = $value;
+ }
}
diff --git a/src/Search/Requirements/RequirementCompositeValue.php b/src/Search/Requirements/RequirementCompositeValue.php
index 6de957f9..93145adf 100644
--- a/src/Search/Requirements/RequirementCompositeValue.php
+++ b/src/Search/Requirements/RequirementCompositeValue.php
@@ -3,20 +3,20 @@ namespace Szurubooru\Search\Requirements;
class RequirementCompositeValue implements IRequirementValue
{
- private $values = [];
+ private $values = [];
- public function __construct(array $values = [])
- {
- $this->setValues($values);
- }
+ public function __construct(array $values = [])
+ {
+ $this->setValues($values);
+ }
- public function getValues()
- {
- return $this->values;
- }
+ public function getValues()
+ {
+ return $this->values;
+ }
- public function setValues(array $values)
- {
- $this->values = $values;
- }
+ public function setValues(array $values)
+ {
+ $this->values = $values;
+ }
}
diff --git a/src/Search/Requirements/RequirementRangedValue.php b/src/Search/Requirements/RequirementRangedValue.php
index 4035e2d5..b871e658 100644
--- a/src/Search/Requirements/RequirementRangedValue.php
+++ b/src/Search/Requirements/RequirementRangedValue.php
@@ -3,31 +3,31 @@ namespace Szurubooru\Search\Requirements;
class RequirementRangedValue implements IRequirementValue
{
- private $minValue = null;
- private $maxValue = null;
+ private $minValue = null;
+ private $maxValue = null;
- public function getMinValue()
- {
- return $this->minValue;
- }
+ public function getMinValue()
+ {
+ return $this->minValue;
+ }
- public function setMinValue($minValue)
- {
- $this->minValue = $minValue;
- }
+ public function setMinValue($minValue)
+ {
+ $this->minValue = $minValue;
+ }
- public function getMaxValue()
- {
- return $this->maxValue;
- }
+ public function getMaxValue()
+ {
+ return $this->maxValue;
+ }
- public function setMaxValue($maxValue)
- {
- $this->maxValue = $maxValue;
- }
+ public function setMaxValue($maxValue)
+ {
+ $this->maxValue = $maxValue;
+ }
- public function getValues()
- {
- return range($this->minValue, $this->maxValue);
- }
+ public function getValues()
+ {
+ return range($this->minValue, $this->maxValue);
+ }
}
diff --git a/src/Search/Requirements/RequirementSingleValue.php b/src/Search/Requirements/RequirementSingleValue.php
index 5a59616b..594a0f79 100644
--- a/src/Search/Requirements/RequirementSingleValue.php
+++ b/src/Search/Requirements/RequirementSingleValue.php
@@ -3,25 +3,25 @@ namespace Szurubooru\Search\Requirements;
class RequirementSingleValue implements IRequirementValue
{
- private $value;
+ private $value;
- public function __construct($value)
- {
- $this->setValue($value);
- }
+ public function __construct($value)
+ {
+ $this->setValue($value);
+ }
- public function getValue()
- {
- return $this->value;
- }
+ public function getValue()
+ {
+ return $this->value;
+ }
- public function setValue($value)
- {
- $this->value = $value;
- }
+ public function setValue($value)
+ {
+ $this->value = $value;
+ }
- public function getValues()
- {
- return [$this->value];
- }
+ public function getValues()
+ {
+ return [$this->value];
+ }
}
diff --git a/src/Search/Result.php b/src/Search/Result.php
index 1563bf94..feae8d8d 100644
--- a/src/Search/Result.php
+++ b/src/Search/Result.php
@@ -4,59 +4,59 @@ use Szurubooru\Search\Filters\IFilter;
class Result
{
- public $pageNumber;
- public $pageSize;
- public $searchFilter;
- public $entities;
- public $totalRecords;
+ public $pageNumber;
+ public $pageSize;
+ public $searchFilter;
+ public $entities;
+ public $totalRecords;
- public function setSearchFilter(IFilter $searchFilter = null)
- {
- $this->searchFilter = $searchFilter;
- }
+ public function setSearchFilter(IFilter $searchFilter = null)
+ {
+ $this->searchFilter = $searchFilter;
+ }
- public function getSearchFilter()
- {
- return $this->searchFilter;
- }
+ public function getSearchFilter()
+ {
+ return $this->searchFilter;
+ }
- public function setPageNumber($pageNumber)
- {
- $this->pageNumber = $pageNumber;
- }
+ public function setPageNumber($pageNumber)
+ {
+ $this->pageNumber = $pageNumber;
+ }
- public function getPageNumber()
- {
- return $this->pageNumber;
- }
+ public function getPageNumber()
+ {
+ return $this->pageNumber;
+ }
- public function setPageSize($pageSize)
- {
- $this->pageSize = $pageSize;
- }
+ public function setPageSize($pageSize)
+ {
+ $this->pageSize = $pageSize;
+ }
- public function getPageSize()
- {
- return $this->pageSize;
- }
+ public function getPageSize()
+ {
+ return $this->pageSize;
+ }
- public function setEntities(array $entities)
- {
- $this->entities = $entities;
- }
+ public function setEntities(array $entities)
+ {
+ $this->entities = $entities;
+ }
- public function getEntities()
- {
- return $this->entities;
- }
+ public function getEntities()
+ {
+ return $this->entities;
+ }
- public function setTotalRecords($totalRecords)
- {
- $this->totalRecords = $totalRecords;
- }
+ public function setTotalRecords($totalRecords)
+ {
+ $this->totalRecords = $totalRecords;
+ }
- public function getTotalRecords()
- {
- return $this->totalRecords;
- }
+ public function getTotalRecords()
+ {
+ return $this->totalRecords;
+ }
}
diff --git a/src/Search/Tokens/NamedSearchToken.php b/src/Search/Tokens/NamedSearchToken.php
index 2bbe63a4..91c60ca4 100644
--- a/src/Search/Tokens/NamedSearchToken.php
+++ b/src/Search/Tokens/NamedSearchToken.php
@@ -3,15 +3,15 @@ namespace Szurubooru\Search\Tokens;
class NamedSearchToken extends SearchToken
{
- private $key = false;
+ private $key = false;
- public function setKey($key)
- {
- $this->key = $key;
- }
+ public function setKey($key)
+ {
+ $this->key = $key;
+ }
- public function getKey()
- {
- return $this->key;
- }
+ public function getKey()
+ {
+ return $this->key;
+ }
}
diff --git a/src/Search/Tokens/SearchToken.php b/src/Search/Tokens/SearchToken.php
index cdde59aa..49afb0ad 100644
--- a/src/Search/Tokens/SearchToken.php
+++ b/src/Search/Tokens/SearchToken.php
@@ -3,26 +3,26 @@ namespace Szurubooru\Search\Tokens;
class SearchToken
{
- private $negated = false;
- private $value;
+ private $negated = false;
+ private $value;
- public function isNegated()
- {
- return $this->negated;
- }
+ public function isNegated()
+ {
+ return $this->negated;
+ }
- public function setNegated($negated)
- {
- $this->negated = $negated;
- }
+ public function setNegated($negated)
+ {
+ $this->negated = $negated;
+ }
- public function getValue()
- {
- return $this->value;
- }
+ public function getValue()
+ {
+ return $this->value;
+ }
- public function setValue($value)
- {
- $this->value = $value;
- }
+ public function setValue($value)
+ {
+ $this->value = $value;
+ }
}
diff --git a/src/Services/AuthService.php b/src/Services/AuthService.php
index e5ce8fd4..ff619f63 100644
--- a/src/Services/AuthService.php
+++ b/src/Services/AuthService.php
@@ -10,110 +10,110 @@ use Szurubooru\Services\UserService;
class AuthService
{
- private $loggedInUser = null;
- private $loginToken = null;
+ private $loggedInUser = null;
+ private $loginToken = null;
- private $config;
- private $passwordService;
- private $timeService;
- private $userService;
- private $tokenService;
+ private $config;
+ private $passwordService;
+ private $timeService;
+ private $userService;
+ private $tokenService;
- public function __construct(
- Config $config,
- PasswordService $passwordService,
- TimeService $timeService,
- TokenService $tokenService,
- UserService $userService)
- {
- $this->config = $config;
- $this->passwordService = $passwordService;
- $this->timeService = $timeService;
- $this->tokenService = $tokenService;
- $this->userService = $userService;
+ public function __construct(
+ Config $config,
+ PasswordService $passwordService,
+ TimeService $timeService,
+ TokenService $tokenService,
+ UserService $userService)
+ {
+ $this->config = $config;
+ $this->passwordService = $passwordService;
+ $this->timeService = $timeService;
+ $this->tokenService = $tokenService;
+ $this->userService = $userService;
- $this->loggedInUser = $this->getAnonymousUser();
- }
+ $this->loggedInUser = $this->getAnonymousUser();
+ }
- public function isLoggedIn()
- {
- return $this->loginToken !== null;
- }
+ public function isLoggedIn()
+ {
+ return $this->loginToken !== null;
+ }
- public function getLoggedInUser()
- {
- return $this->loggedInUser;
- }
+ public function getLoggedInUser()
+ {
+ return $this->loggedInUser;
+ }
- public function getLoginToken()
- {
- return $this->loginToken;
- }
+ public function getLoginToken()
+ {
+ return $this->loginToken;
+ }
- public function loginFromCredentials($formData)
- {
- $user = $this->userService->getByNameOrEmail($formData->userNameOrEmail);
- $this->doFinalChecksOnUser($user);
+ public function loginFromCredentials($formData)
+ {
+ $user = $this->userService->getByNameOrEmail($formData->userNameOrEmail);
+ $this->doFinalChecksOnUser($user);
- $hashValid = $this->passwordService->isHashValid(
- $formData->password,
- $user->getPasswordSalt(),
- $user->getPasswordHash());
+ $hashValid = $this->passwordService->isHashValid(
+ $formData->password,
+ $user->getPasswordSalt(),
+ $user->getPasswordHash());
- if (!$hashValid)
- throw new \InvalidArgumentException('Specified password is invalid.');
+ if (!$hashValid)
+ throw new \InvalidArgumentException('Specified password is invalid.');
- $this->loginToken = $this->createAndSaveLoginToken($user);
- $this->loggedInUser = $user;
- }
+ $this->loginToken = $this->createAndSaveLoginToken($user);
+ $this->loggedInUser = $user;
+ }
- public function loginFromToken(Token $token)
- {
- if ($token->getPurpose() !== Token::PURPOSE_LOGIN)
- throw new \Exception('This token is not a login token.');
+ public function loginFromToken(Token $token)
+ {
+ if ($token->getPurpose() !== Token::PURPOSE_LOGIN)
+ throw new \Exception('This token is not a login token.');
- $user = $this->userService->getById($token->getAdditionalData());
- $this->doFinalChecksOnUser($user);
+ $user = $this->userService->getById($token->getAdditionalData());
+ $this->doFinalChecksOnUser($user);
- $this->loginToken = $token;
- $this->loggedInUser = $user;
- }
+ $this->loginToken = $token;
+ $this->loggedInUser = $user;
+ }
- public function getAnonymousUser()
- {
- $user = new User();
- $user->setName('Anonymous user');
- $user->setAccessRank(User::ACCESS_RANK_ANONYMOUS);
- $user->setAvatarStyle(User::AVATAR_STYLE_BLANK);
- return $user;
- }
+ public function getAnonymousUser()
+ {
+ $user = new User();
+ $user->setName('Anonymous user');
+ $user->setAccessRank(User::ACCESS_RANK_ANONYMOUS);
+ $user->setAvatarStyle(User::AVATAR_STYLE_BLANK);
+ return $user;
+ }
- public function loginAnonymous()
- {
- $this->loginToken = null;
- $this->loggedInUser = $this->getAnonymousUser();
- }
+ public function loginAnonymous()
+ {
+ $this->loginToken = null;
+ $this->loggedInUser = $this->getAnonymousUser();
+ }
- public function logout()
- {
- if (!$this->isLoggedIn())
- throw new \Exception('Not logged in.');
+ public function logout()
+ {
+ if (!$this->isLoggedIn())
+ throw new \Exception('Not logged in.');
- $this->tokenService->invalidateByName($this->loginToken);
- $this->loginToken = null;
- }
+ $this->tokenService->invalidateByName($this->loginToken);
+ $this->loginToken = null;
+ }
- private function createAndSaveLoginToken(User $user)
- {
- return $this->tokenService->createAndSaveToken($user->getId(), Token::PURPOSE_LOGIN);
- }
+ private function createAndSaveLoginToken(User $user)
+ {
+ return $this->tokenService->createAndSaveToken($user->getId(), Token::PURPOSE_LOGIN);
+ }
- private function doFinalChecksOnUser($user)
- {
- if (!$user->isAccountConfirmed() && $this->config->security->needEmailActivationToRegister)
- throw new \DomainException('User didn\'t confirm account yet.');
+ private function doFinalChecksOnUser($user)
+ {
+ if (!$user->isAccountConfirmed() && $this->config->security->needEmailActivationToRegister)
+ throw new \DomainException('User didn\'t confirm account yet.');
- if ($user->isBanned())
- throw new \DomainException('Banned!');
- }
+ if ($user->isBanned())
+ throw new \DomainException('Banned!');
+ }
}
diff --git a/src/Services/CommentService.php b/src/Services/CommentService.php
index ca6d7aed..75240f9b 100644
--- a/src/Services/CommentService.php
+++ b/src/Services/CommentService.php
@@ -11,97 +11,97 @@ use Szurubooru\Validator;
class CommentService
{
- private $validator;
- private $commentDao;
- private $transactionManager;
- private $authService;
- private $timeService;
+ private $validator;
+ private $commentDao;
+ private $transactionManager;
+ private $authService;
+ private $timeService;
- public function __construct(
- Validator $validator,
- CommentDao $commentDao,
- TransactionManager $transactionManager,
- AuthService $authService,
- TimeService $timeService)
- {
- $this->validator = $validator;
- $this->commentDao = $commentDao;
- $this->transactionManager = $transactionManager;
- $this->authService = $authService;
- $this->timeService = $timeService;
- }
+ public function __construct(
+ Validator $validator,
+ CommentDao $commentDao,
+ TransactionManager $transactionManager,
+ AuthService $authService,
+ TimeService $timeService)
+ {
+ $this->validator = $validator;
+ $this->commentDao = $commentDao;
+ $this->transactionManager = $transactionManager;
+ $this->authService = $authService;
+ $this->timeService = $timeService;
+ }
- public function getById($commentId)
- {
- $transactionFunc = function() use ($commentId)
- {
- $comment = $this->commentDao->findById($commentId);
- if (!$comment)
- throw new \InvalidArgumentException('Comment with ID "' . $commentId . '" was not found.');
- return $comment;
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getById($commentId)
+ {
+ $transactionFunc = function() use ($commentId)
+ {
+ $comment = $this->commentDao->findById($commentId);
+ if (!$comment)
+ throw new \InvalidArgumentException('Comment with ID "' . $commentId . '" was not found.');
+ return $comment;
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getByPost(Post $post)
- {
- $transactionFunc = function() use ($post)
- {
- return $this->commentDao->findByPost($post);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getByPost(Post $post)
+ {
+ $transactionFunc = function() use ($post)
+ {
+ return $this->commentDao->findByPost($post);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getFiltered(CommentFilter $filter)
- {
- $transactionFunc = function() use ($filter)
- {
- return $this->commentDao->findFiltered($filter);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFiltered(CommentFilter $filter)
+ {
+ $transactionFunc = function() use ($filter)
+ {
+ return $this->commentDao->findFiltered($filter);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function createComment(Post $post, $text)
- {
- $transactionFunc = function() use ($post, $text)
- {
- $comment = new Comment();
- $comment->setCreationTime($this->timeService->getCurrentTime());
- $comment->setLastEditTime($this->timeService->getCurrentTime());
- $comment->setUser($this->authService->isLoggedIn() ? $this->authService->getLoggedInUser() : null);
- $comment->setPost($post);
+ public function createComment(Post $post, $text)
+ {
+ $transactionFunc = function() use ($post, $text)
+ {
+ $comment = new Comment();
+ $comment->setCreationTime($this->timeService->getCurrentTime());
+ $comment->setLastEditTime($this->timeService->getCurrentTime());
+ $comment->setUser($this->authService->isLoggedIn() ? $this->authService->getLoggedInUser() : null);
+ $comment->setPost($post);
- $this->updateCommentText($comment, $text);
+ $this->updateCommentText($comment, $text);
- return $this->commentDao->save($comment);
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ return $this->commentDao->save($comment);
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function updateComment(Comment $comment, $newText)
- {
- $transactionFunc = function() use ($comment, $newText)
- {
- $comment->setLastEditTime($this->timeService->getCurrentTime());
+ public function updateComment(Comment $comment, $newText)
+ {
+ $transactionFunc = function() use ($comment, $newText)
+ {
+ $comment->setLastEditTime($this->timeService->getCurrentTime());
- $this->updateCommentText($comment, $newText);
- return $this->commentDao->save($comment);
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ $this->updateCommentText($comment, $newText);
+ return $this->commentDao->save($comment);
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function deleteComment(Comment $comment)
- {
- $transactionFunc = function() use ($comment)
- {
- $this->commentDao->deleteById($comment->getId());
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ public function deleteComment(Comment $comment)
+ {
+ $transactionFunc = function() use ($comment)
+ {
+ $this->commentDao->deleteById($comment->getId());
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
- private function updateCommentText(Comment $comment, $text)
- {
- $this->validator->validateLength($text, 5, 2000, 'Comment text');
- $comment->setText($text);
- }
+ private function updateCommentText(Comment $comment, $text)
+ {
+ $this->validator->validateLength($text, 5, 2000, 'Comment text');
+ $comment->setText($text);
+ }
}
diff --git a/src/Services/EmailService.php b/src/Services/EmailService.php
index 17951dc7..c4d7809e 100644
--- a/src/Services/EmailService.php
+++ b/src/Services/EmailService.php
@@ -6,89 +6,89 @@ use \Szurubooru\Entities\User;
class EmailService
{
- private $config;
+ private $config;
- public function __construct(Config $config)
- {
- $this->config = $config;
- }
+ public function __construct(Config $config)
+ {
+ $this->config = $config;
+ }
- public function sendPasswordResetEmail(User $user, Token $token)
- {
- if (!$user->getEmail())
- throw new \BadMethodCall('An activated e-mail addreses is needed to reset the password.');
+ public function sendPasswordResetEmail(User $user, Token $token)
+ {
+ if (!$user->getEmail())
+ throw new \BadMethodCall('An activated e-mail addreses is needed to reset the password.');
- $mailSubject = $this->tokenize($this->config->mail->passwordResetSubject);
- $mailBody = $this->tokenizeFile(
- $this->config->mail->passwordResetBodyPath,
- [
- 'link' => $this->config->basic->serviceBaseUrl . '#/password-reset/' . $token->getName(),
- ]);
+ $mailSubject = $this->tokenize($this->config->mail->passwordResetSubject);
+ $mailBody = $this->tokenizeFile(
+ $this->config->mail->passwordResetBodyPath,
+ [
+ 'link' => $this->config->basic->serviceBaseUrl . '#/password-reset/' . $token->getName(),
+ ]);
- $this->sendEmail($user->getEmail(), $mailSubject, $mailBody);
- }
+ $this->sendEmail($user->getEmail(), $mailSubject, $mailBody);
+ }
- public function sendActivationEmail(User $user, Token $token)
- {
- if (!$user->getEmailUnconfirmed())
- throw new \BadMethodCallException('An e-mail address is needed to activate the account.');
+ public function sendActivationEmail(User $user, Token $token)
+ {
+ if (!$user->getEmailUnconfirmed())
+ throw new \BadMethodCallException('An e-mail address is needed to activate the account.');
- $mailSubject = $this->tokenize($this->config->mail->activationSubject);
- $mailBody = $this->tokenizeFile(
- $this->config->mail->activationBodyPath,
- [
- 'link' => $this->config->basic->serviceBaseUrl . '#/activate/' . $token->getName(),
- ]);
+ $mailSubject = $this->tokenize($this->config->mail->activationSubject);
+ $mailBody = $this->tokenizeFile(
+ $this->config->mail->activationBodyPath,
+ [
+ 'link' => $this->config->basic->serviceBaseUrl . '#/activate/' . $token->getName(),
+ ]);
- $this->sendEmail($user->getEmailUnconfirmed(), $mailSubject, $mailBody);
- }
+ $this->sendEmail($user->getEmailUnconfirmed(), $mailSubject, $mailBody);
+ }
- private function sendEmail($recipientEmail, $subject, $body)
- {
- $domain = substr($this->config->mail->botEmail, strpos($this->config->mail->botEmail, '@') + 1);
+ private function sendEmail($recipientEmail, $subject, $body)
+ {
+ $domain = substr($this->config->mail->botEmail, strpos($this->config->mail->botEmail, '@') + 1);
- $clientIp = isset($_SERVER['SERVER_ADDR'])
- ? $_SERVER['SERVER_ADDR']
- : '';
+ $clientIp = isset($_SERVER['SERVER_ADDR'])
+ ? $_SERVER['SERVER_ADDR']
+ : '';
- $body = wordwrap($body, 70);
- if (empty($recipientEmail))
- throw new \InvalidArgumentException('Destination e-mail address was not found');
+ $body = wordwrap($body, 70);
+ if (empty($recipientEmail))
+ throw new \InvalidArgumentException('Destination e-mail address was not found');
- $messageId = sha1(date('r') . uniqid()) . '@' . $domain;
+ $messageId = sha1(date('r') . uniqid()) . '@' . $domain;
- $headers = [];
- $headers[] = sprintf('MIME-Version: 1.0');
- $headers[] = sprintf('Content-Transfer-Encoding: 7bit');
- $headers[] = sprintf('Date: %s', date('r'));
- $headers[] = sprintf('Message-ID: <%s>', $messageId);
- $headers[] = sprintf('From: %s <%s>', $this->config->mail->botName, $this->config->mail->botEmail);
- $headers[] = sprintf('Reply-To: %s', $this->config->mail->botEmail);
- $headers[] = sprintf('Return-Path: %s', $this->config->mail->botEmail);
- $headers[] = sprintf('Subject: %s', $subject);
- $headers[] = sprintf('Content-Type: text/plain; charset=utf-8');
- $headers[] = sprintf('X-Mailer: PHP/%s', phpversion());
- $headers[] = sprintf('X-Originating-IP: %s', $clientIp);
+ $headers = [];
+ $headers[] = sprintf('MIME-Version: 1.0');
+ $headers[] = sprintf('Content-Transfer-Encoding: 7bit');
+ $headers[] = sprintf('Date: %s', date('r'));
+ $headers[] = sprintf('Message-ID: <%s>', $messageId);
+ $headers[] = sprintf('From: %s <%s>', $this->config->mail->botName, $this->config->mail->botEmail);
+ $headers[] = sprintf('Reply-To: %s', $this->config->mail->botEmail);
+ $headers[] = sprintf('Return-Path: %s', $this->config->mail->botEmail);
+ $headers[] = sprintf('Subject: %s', $subject);
+ $headers[] = sprintf('Content-Type: text/plain; charset=utf-8');
+ $headers[] = sprintf('X-Mailer: PHP/%s', phpversion());
+ $headers[] = sprintf('X-Originating-IP: %s', $clientIp);
- $encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
+ $encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
- mail($recipientEmail, $encodedSubject, $body, implode("\r\n", $headers), '-f' . $this->config->mail->botEmail);
- }
+ mail($recipientEmail, $encodedSubject, $body, implode("\r\n", $headers), '-f' . $this->config->mail->botEmail);
+ }
- private function tokenizeFile($templatePath, $tokens = [])
- {
- $text = file_get_contents($this->config->getDataDirectory() . DIRECTORY_SEPARATOR . $templatePath);
- return $this->tokenize($text, $tokens);
- }
+ private function tokenizeFile($templatePath, $tokens = [])
+ {
+ $text = file_get_contents($this->config->getDataDirectory() . DIRECTORY_SEPARATOR . $templatePath);
+ return $this->tokenize($text, $tokens);
+ }
- private function tokenize($text, $tokens = [])
- {
- $tokens['serviceBaseUrl'] = $this->config->basic->serviceBaseUrl;
- $tokens['serviceName'] = $this->config->basic->serviceName;
+ private function tokenize($text, $tokens = [])
+ {
+ $tokens['serviceBaseUrl'] = $this->config->basic->serviceBaseUrl;
+ $tokens['serviceName'] = $this->config->basic->serviceName;
- foreach ($tokens as $key => $value)
- $text = str_ireplace('{' . $key . '}', $value, $text);
+ foreach ($tokens as $key => $value)
+ $text = str_ireplace('{' . $key . '}', $value, $text);
- return $text;
- }
+ return $text;
+ }
}
diff --git a/src/Services/FavoritesService.php b/src/Services/FavoritesService.php
index 2270237b..64b6fb7d 100644
--- a/src/Services/FavoritesService.php
+++ b/src/Services/FavoritesService.php
@@ -10,58 +10,58 @@ use Szurubooru\Services\TimeService;
class FavoritesService
{
- private $favoritesDao;
- private $scoreDao;
- private $userDao;
- private $transactionManager;
- private $timeService;
+ private $favoritesDao;
+ private $scoreDao;
+ private $userDao;
+ private $transactionManager;
+ private $timeService;
- public function __construct(
- FavoritesDao $favoritesDao,
- ScoreDao $scoreDao,
- UserDao $userDao,
- TransactionManager $transactionManager,
- TimeService $timeService)
- {
- $this->favoritesDao = $favoritesDao;
- $this->scoreDao = $scoreDao;
- $this->userDao = $userDao;
- $this->transactionManager = $transactionManager;
- $this->timeService = $timeService;
- }
+ public function __construct(
+ FavoritesDao $favoritesDao,
+ ScoreDao $scoreDao,
+ UserDao $userDao,
+ TransactionManager $transactionManager,
+ TimeService $timeService)
+ {
+ $this->favoritesDao = $favoritesDao;
+ $this->scoreDao = $scoreDao;
+ $this->userDao = $userDao;
+ $this->transactionManager = $transactionManager;
+ $this->timeService = $timeService;
+ }
- public function getFavoriteUsers(Entity $entity)
- {
- $transactionFunc = function() use ($entity)
- {
- $favorites = $this->favoritesDao->findByEntity($entity);
- $userIds = [];
- foreach ($favorites as $favorite)
- {
- $userIds[] = $favorite->getUserId();
- }
- return $this->userDao->findByIds($userIds);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFavoriteUsers(Entity $entity)
+ {
+ $transactionFunc = function() use ($entity)
+ {
+ $favorites = $this->favoritesDao->findByEntity($entity);
+ $userIds = [];
+ foreach ($favorites as $favorite)
+ {
+ $userIds[] = $favorite->getUserId();
+ }
+ return $this->userDao->findByIds($userIds);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function addFavorite(User $user, Entity $entity)
- {
- $transactionFunc = function() use ($user, $entity)
- {
- $this->scoreDao->setUserScore($user, $entity, 1);
+ public function addFavorite(User $user, Entity $entity)
+ {
+ $transactionFunc = function() use ($user, $entity)
+ {
+ $this->scoreDao->setUserScore($user, $entity, 1);
- return $this->favoritesDao->set($user, $entity);
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ return $this->favoritesDao->set($user, $entity);
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function deleteFavorite(User $user, Entity $entity)
- {
- $transactionFunc = function() use ($user, $entity)
- {
- $this->favoritesDao->delete($user, $entity);
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ public function deleteFavorite(User $user, Entity $entity)
+ {
+ $transactionFunc = function() use ($user, $entity)
+ {
+ $this->favoritesDao->delete($user, $entity);
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
}
diff --git a/src/Services/HistoryService.php b/src/Services/HistoryService.php
index d737917b..e0b5c1ed 100644
--- a/src/Services/HistoryService.php
+++ b/src/Services/HistoryService.php
@@ -9,120 +9,120 @@ use Szurubooru\Services\TimeService;
class HistoryService
{
- private $snapshotDao;
- private $timeService;
- private $authService;
- private $transactionManager;
+ private $snapshotDao;
+ private $timeService;
+ private $authService;
+ private $transactionManager;
- public function __construct(
- SnapshotDao $snapshotDao,
- TransactionManager $transactionManager,
- TimeService $timeService,
- AuthService $authService)
- {
- $this->snapshotDao = $snapshotDao;
- $this->timeService = $timeService;
- $this->authService = $authService;
- $this->transactionManager = $transactionManager;
- }
+ public function __construct(
+ SnapshotDao $snapshotDao,
+ TransactionManager $transactionManager,
+ TimeService $timeService,
+ AuthService $authService)
+ {
+ $this->snapshotDao = $snapshotDao;
+ $this->timeService = $timeService;
+ $this->authService = $authService;
+ $this->transactionManager = $transactionManager;
+ }
- public function getFiltered(SnapshotFilter $filter)
- {
- $transactionFunc = function() use ($filter)
- {
- return $this->snapshotDao->findFiltered($filter);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFiltered(SnapshotFilter $filter)
+ {
+ $transactionFunc = function() use ($filter)
+ {
+ return $this->snapshotDao->findFiltered($filter);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function saveSnapshot(Snapshot $snapshot)
- {
- $transactionFunc = function() use ($snapshot)
- {
- $snapshot->setTime($this->timeService->getCurrentTime());
- $snapshot->setUser($this->authService->getLoggedInUser());
+ public function saveSnapshot(Snapshot $snapshot)
+ {
+ $transactionFunc = function() use ($snapshot)
+ {
+ $snapshot->setTime($this->timeService->getCurrentTime());
+ $snapshot->setUser($this->authService->getLoggedInUser());
- $earlierSnapshots = array_values($this->snapshotDao->findEarlierSnapshots($snapshot));
- $snapshotsLeft = count($earlierSnapshots);
+ $earlierSnapshots = array_values($this->snapshotDao->findEarlierSnapshots($snapshot));
+ $snapshotsLeft = count($earlierSnapshots);
- while (true)
- {
- $lastSnapshot = array_shift($earlierSnapshots);
- $dataDifference = $this->getSnapshotDataDifference($snapshot, $lastSnapshot);
- $snapshot->setDataDifference($dataDifference);
+ while (true)
+ {
+ $lastSnapshot = array_shift($earlierSnapshots);
+ $dataDifference = $this->getSnapshotDataDifference($snapshot, $lastSnapshot);
+ $snapshot->setDataDifference($dataDifference);
- if ($lastSnapshot === null)
- break;
+ if ($lastSnapshot === null)
+ break;
- //recent snapshots should be merged
- $isFresh = ((strtotime($snapshot->getTime()) - strtotime($lastSnapshot->getTime())) <= 5 * 60);
- if (!$isFresh || $lastSnapshot->getUserId() !== $snapshot->getUserId())
- break;
+ //recent snapshots should be merged
+ $isFresh = ((strtotime($snapshot->getTime()) - strtotime($lastSnapshot->getTime())) <= 5 * 60);
+ if (!$isFresh || $lastSnapshot->getUserId() !== $snapshot->getUserId())
+ break;
- //delete the current snapshot
- if ($snapshot->getId())
- $this->snapshotDao->deleteById($snapshot->getId());
+ //delete the current snapshot
+ if ($snapshot->getId())
+ $this->snapshotDao->deleteById($snapshot->getId());
- //become previous snapshot, but keep the current data
- $snapshot->setId($lastSnapshot->getId());
- if ($snapshot->getOperation() !== Snapshot::OPERATION_DELETE)
- $snapshot->setOperation($lastSnapshot->getOperation());
+ //become previous snapshot, but keep the current data
+ $snapshot->setId($lastSnapshot->getId());
+ if ($snapshot->getOperation() !== Snapshot::OPERATION_DELETE)
+ $snapshot->setOperation($lastSnapshot->getOperation());
- -- $snapshotsLeft;
- }
+ -- $snapshotsLeft;
+ }
- $onlyRemovalLeft = (!$snapshotsLeft && $snapshot->getOperation() === Snapshot::OPERATION_DELETE);
+ $onlyRemovalLeft = (!$snapshotsLeft && $snapshot->getOperation() === Snapshot::OPERATION_DELETE);
- $emptyDiff = (empty($dataDifference['+']) && empty($dataDifference['-']));
- if ($onlyRemovalLeft || $emptyDiff)
- {
- if ($snapshot->getId())
- $this->snapshotDao->deleteById($snapshot->getId());
- return array_shift($earlierSnapshots);
- }
+ $emptyDiff = (empty($dataDifference['+']) && empty($dataDifference['-']));
+ if ($onlyRemovalLeft || $emptyDiff)
+ {
+ if ($snapshot->getId())
+ $this->snapshotDao->deleteById($snapshot->getId());
+ return array_shift($earlierSnapshots);
+ }
- return $this->snapshotDao->save($snapshot);
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ return $this->snapshotDao->save($snapshot);
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function getSnapshotDataDifference(Snapshot $newSnapshot, Snapshot $oldSnapshot = null)
- {
- return $this->getDataDifference(
- $newSnapshot->getData(),
- $oldSnapshot ? $oldSnapshot->getData() : []);
- }
+ public function getSnapshotDataDifference(Snapshot $newSnapshot, Snapshot $oldSnapshot = null)
+ {
+ return $this->getDataDifference(
+ $newSnapshot->getData(),
+ $oldSnapshot ? $oldSnapshot->getData() : []);
+ }
- public function getDataDifference($newData, $oldData)
- {
- $diffFunction = function($base, $other)
- {
- $result = [];
- foreach ($base as $key => $value)
- {
- if (is_array($base[$key]))
- {
- $result[$key] = [];
- foreach ($base[$key] as $subValue)
- {
- if (!isset($other[$key]) || !in_array($subValue, $other[$key]))
- $result[$key] []= $subValue;
- }
- if (empty($result[$key]))
- unset($result[$key]);
- }
- elseif (!isset($other[$key]) || $base[$key] !== $other[$key])
- {
- $result[$key] = $value;
- }
- }
- return $result;
+ public function getDataDifference($newData, $oldData)
+ {
+ $diffFunction = function($base, $other)
+ {
+ $result = [];
+ foreach ($base as $key => $value)
+ {
+ if (is_array($base[$key]))
+ {
+ $result[$key] = [];
+ foreach ($base[$key] as $subValue)
+ {
+ if (!isset($other[$key]) || !in_array($subValue, $other[$key]))
+ $result[$key] []= $subValue;
+ }
+ if (empty($result[$key]))
+ unset($result[$key]);
+ }
+ elseif (!isset($other[$key]) || $base[$key] !== $other[$key])
+ {
+ $result[$key] = $value;
+ }
+ }
+ return $result;
- };
+ };
- return [
- '+' => $diffFunction($newData, $oldData),
- '-' => $diffFunction($oldData, $newData),
- ];
- }
+ return [
+ '+' => $diffFunction($newData, $oldData),
+ '-' => $diffFunction($oldData, $newData),
+ ];
+ }
}
diff --git a/src/Services/ISnapshotProvider.php b/src/Services/ISnapshotProvider.php
index 78db0f04..576c38d8 100644
--- a/src/Services/ISnapshotProvider.php
+++ b/src/Services/ISnapshotProvider.php
@@ -4,7 +4,7 @@ use Szurubooru\Entities\Entity;
interface ISnapshotProvider
{
- public function getCreationSnapshot(Entity $entity);
- public function getChangeSnapshot(Entity $entity);
- public function getDeleteSnapshot(Entity $entity);
+ public function getCreationSnapshot(Entity $entity);
+ public function getChangeSnapshot(Entity $entity);
+ public function getDeleteSnapshot(Entity $entity);
}
diff --git a/src/Services/ImageConverter.php b/src/Services/ImageConverter.php
index 7956bf3a..242baeea 100644
--- a/src/Services/ImageConverter.php
+++ b/src/Services/ImageConverter.php
@@ -6,117 +6,117 @@ use Szurubooru\Services\ImageManipulation\ImageManipulator;
class ImageConverter
{
- const PROGRAM_NAME_DUMP_GNASH = 'dump-gnash';
- const PROGRAM_NAME_SWFRENDER = 'swfrender';
- const PROGRAM_NAME_FFMPEG = 'ffmpeg';
- const PROGRAM_NAME_FFMPEGTHUMBNAILER = 'ffmpegthumbnailer';
+ const PROGRAM_NAME_DUMP_GNASH = 'dump-gnash';
+ const PROGRAM_NAME_SWFRENDER = 'swfrender';
+ const PROGRAM_NAME_FFMPEG = 'ffmpeg';
+ const PROGRAM_NAME_FFMPEGTHUMBNAILER = 'ffmpegthumbnailer';
- private $imageManipulator;
+ private $imageManipulator;
- public function __construct(ImageManipulator $imageManipulator)
- {
- $this->imageManipulator = $imageManipulator;
- }
+ public function __construct(ImageManipulator $imageManipulator)
+ {
+ $this->imageManipulator = $imageManipulator;
+ }
- public function createImageFromBuffer($source)
- {
- $tmpSourcePath = tempnam(sys_get_temp_dir(), 'thumb') . '.dat';
- $tmpTargetPath = tempnam(sys_get_temp_dir(), 'thumb') . '.png';
- try
- {
- file_put_contents($tmpSourcePath, $source);
- $this->convert($tmpSourcePath, $tmpTargetPath);
+ public function createImageFromBuffer($source)
+ {
+ $tmpSourcePath = tempnam(sys_get_temp_dir(), 'thumb') . '.dat';
+ $tmpTargetPath = tempnam(sys_get_temp_dir(), 'thumb') . '.png';
+ try
+ {
+ file_put_contents($tmpSourcePath, $source);
+ $this->convert($tmpSourcePath, $tmpTargetPath);
- $tmpSource = file_get_contents($tmpTargetPath);
- return $this->imageManipulator->loadFromBuffer($tmpSource);
- }
- finally
- {
- $this->deleteIfExists($tmpSourcePath);
- $this->deleteIfExists($tmpTargetPath);
- }
- }
+ $tmpSource = file_get_contents($tmpTargetPath);
+ return $this->imageManipulator->loadFromBuffer($tmpSource);
+ }
+ finally
+ {
+ $this->deleteIfExists($tmpSourcePath);
+ $this->deleteIfExists($tmpTargetPath);
+ }
+ }
- public function convert($sourcePath, $targetPath)
- {
- $mime = MimeHelper::getMimeTypeFromFile($sourcePath);
+ public function convert($sourcePath, $targetPath)
+ {
+ $mime = MimeHelper::getMimeTypeFromFile($sourcePath);
- if (MimeHelper::isImage($mime))
- copy($sourcePath, $targetPath);
+ if (MimeHelper::isImage($mime))
+ copy($sourcePath, $targetPath);
- elseif (MimeHelper::isFlash($mime))
- $this->convertFromFlash($sourcePath, $targetPath);
+ elseif (MimeHelper::isFlash($mime))
+ $this->convertFromFlash($sourcePath, $targetPath);
- elseif (MimeHelper::isVideo($mime))
- $this->convertFromVideo($sourcePath, $targetPath);
+ elseif (MimeHelper::isVideo($mime))
+ $this->convertFromVideo($sourcePath, $targetPath);
- else
- throw new \Exception('Error while converting file to image - unrecognized MIME: ' . $mime);
- }
+ else
+ throw new \Exception('Error while converting file to image - unrecognized MIME: ' . $mime);
+ }
- private function convertFromFlash($sourcePath, $targetPath)
- {
- if (ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_DUMP_GNASH))
- {
- ProgramExecutor::run(
- self::PROGRAM_NAME_DUMP_GNASH,
- [
- '--screenshot', 'last',
- '--screenshot-file', $targetPath,
- '-1',
- '-r1',
- '--max-advances', '15',
- $sourcePath,
- ]);
- }
+ private function convertFromFlash($sourcePath, $targetPath)
+ {
+ if (ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_DUMP_GNASH))
+ {
+ ProgramExecutor::run(
+ self::PROGRAM_NAME_DUMP_GNASH,
+ [
+ '--screenshot', 'last',
+ '--screenshot-file', $targetPath,
+ '-1',
+ '-r1',
+ '--max-advances', '15',
+ $sourcePath,
+ ]);
+ }
- if (!file_exists($targetPath) && ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_SWFRENDER))
- {
- ProgramExecutor::run(
- self::PROGRAM_NAME_SWFRENDER,
- [
- 'swfrender',
- $sourcePath,
- '-o',
- $targetPath,
- ]);
- }
+ if (!file_exists($targetPath) && ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_SWFRENDER))
+ {
+ ProgramExecutor::run(
+ self::PROGRAM_NAME_SWFRENDER,
+ [
+ 'swfrender',
+ $sourcePath,
+ '-o',
+ $targetPath,
+ ]);
+ }
- if (!file_exists($targetPath))
- throw new \Exception('Error while converting Flash file to image');
- }
+ if (!file_exists($targetPath))
+ throw new \Exception('Error while converting Flash file to image');
+ }
- private function convertFromVideo($sourcePath, $targetPath)
- {
- if (ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_FFMPEGTHUMBNAILER))
- {
- ProgramExecutor::run(
- self::PROGRAM_NAME_FFMPEGTHUMBNAILER,
- [
- '-i' . $sourcePath,
- '-o' . $targetPath,
- '-s0',
- '-t12%%'
- ]);
- }
+ private function convertFromVideo($sourcePath, $targetPath)
+ {
+ if (ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_FFMPEGTHUMBNAILER))
+ {
+ ProgramExecutor::run(
+ self::PROGRAM_NAME_FFMPEGTHUMBNAILER,
+ [
+ '-i' . $sourcePath,
+ '-o' . $targetPath,
+ '-s0',
+ '-t12%%'
+ ]);
+ }
- if (!file_exists($targetPath) && ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_FFMPEG))
- {
- ProgramExecutor::run(self::PROGRAM_NAME_FFMPEG,
- [
- '-i', $sourcePath,
- '-vframes', '1',
- $targetPath
- ]);
- }
+ if (!file_exists($targetPath) && ProgramExecutor::isProgramAvailable(self::PROGRAM_NAME_FFMPEG))
+ {
+ ProgramExecutor::run(self::PROGRAM_NAME_FFMPEG,
+ [
+ '-i', $sourcePath,
+ '-vframes', '1',
+ $targetPath
+ ]);
+ }
- if (!file_exists($targetPath))
- throw new \Exception('Error while converting video file to image');
- }
+ if (!file_exists($targetPath))
+ throw new \Exception('Error while converting video file to image');
+ }
- private function deleteIfExists($path)
- {
- if (file_exists($path))
- unlink($path);
- }
+ private function deleteIfExists($path)
+ {
+ if (file_exists($path))
+ unlink($path);
+ }
}
diff --git a/src/Services/ImageManipulation/GdImageManipulator.php b/src/Services/ImageManipulation/GdImageManipulator.php
index 9f8aa58d..eea75bfb 100644
--- a/src/Services/ImageManipulation/GdImageManipulator.php
+++ b/src/Services/ImageManipulation/GdImageManipulator.php
@@ -3,92 +3,92 @@ namespace Szurubooru\Services\ImageManipulation;
class GdImageManipulator implements IImageManipulator
{
- public function loadFromBuffer($source)
- {
- try
- {
- return imagecreatefromstring($source);
- }
- catch (\Exception $e)
- {
- return null;
- }
- }
+ public function loadFromBuffer($source)
+ {
+ try
+ {
+ return imagecreatefromstring($source);
+ }
+ catch (\Exception $e)
+ {
+ return null;
+ }
+ }
- public function getImageWidth($imageResource)
- {
- return imagesx($imageResource);
- }
+ public function getImageWidth($imageResource)
+ {
+ return imagesx($imageResource);
+ }
- public function getImageHeight($imageResource)
- {
- return imagesy($imageResource);
- }
+ public function getImageHeight($imageResource)
+ {
+ return imagesy($imageResource);
+ }
- public function resizeImage(&$imageResource, $width, $height)
- {
- $targetImageResource = imagecreatetruecolor($width, $height);
+ public function resizeImage(&$imageResource, $width, $height)
+ {
+ $targetImageResource = imagecreatetruecolor($width, $height);
- imagecopyresampled(
- $targetImageResource,
- $imageResource,
- 0, 0,
- 0, 0,
- $width,
- $height,
- imagesx($imageResource),
- imagesy($imageResource));
+ imagecopyresampled(
+ $targetImageResource,
+ $imageResource,
+ 0, 0,
+ 0, 0,
+ $width,
+ $height,
+ imagesx($imageResource),
+ imagesy($imageResource));
- $imageResource = $targetImageResource;
- }
+ $imageResource = $targetImageResource;
+ }
- public function cropImage(&$imageResource, $width, $height, $originX, $originY)
- {
- if ($originX + $width > imagesx($imageResource))
- $width = imagesx($imageResource) - $originX;
- if ($originY + $height > imagesy($imageResource))
- $height = imagesy($imageResource) - $originY;
+ public function cropImage(&$imageResource, $width, $height, $originX, $originY)
+ {
+ if ($originX + $width > imagesx($imageResource))
+ $width = imagesx($imageResource) - $originX;
+ if ($originY + $height > imagesy($imageResource))
+ $height = imagesy($imageResource) - $originY;
- if ($originX < 0)
- $width = $width + $originX;
- if ($originY < 0)
- $height = $height + $originY;
+ if ($originX < 0)
+ $width = $width + $originX;
+ if ($originY < 0)
+ $height = $height + $originY;
- if ($width < 1)
- $width = 1;
- if ($height < 1)
- $height = 1;
+ if ($width < 1)
+ $width = 1;
+ if ($height < 1)
+ $height = 1;
- $imageResource = imagecrop($imageResource, [
- 'x' => $originX,
- 'y' => $originY,
- 'width' => $width,
- 'height' => $height]);
- }
+ $imageResource = imagecrop($imageResource, [
+ 'x' => $originX,
+ 'y' => $originY,
+ 'width' => $width,
+ 'height' => $height]);
+ }
- public function saveToBuffer($imageResource, $format)
- {
- ob_start();
+ public function saveToBuffer($imageResource, $format)
+ {
+ ob_start();
- switch ($format)
- {
- case self::FORMAT_JPEG:
- imagejpeg($imageResource);
- break;
+ switch ($format)
+ {
+ case self::FORMAT_JPEG:
+ imagejpeg($imageResource);
+ break;
- case self::FORMAT_PNG:
- imagepng($imageResource);
- break;
+ case self::FORMAT_PNG:
+ imagepng($imageResource);
+ break;
- default:
- throw new \InvalidArgumentException('Not supported');
- }
+ default:
+ throw new \InvalidArgumentException('Not supported');
+ }
- $buffer = ob_get_contents();
- ob_end_clean();
+ $buffer = ob_get_contents();
+ ob_end_clean();
- if (!$buffer)
- throw new \InvalidArgumentException('Not supported');
- return $buffer;
- }
+ if (!$buffer)
+ throw new \InvalidArgumentException('Not supported');
+ return $buffer;
+ }
}
diff --git a/src/Services/ImageManipulation/IImageManipulator.php b/src/Services/ImageManipulation/IImageManipulator.php
index c0a638ca..1d36558c 100644
--- a/src/Services/ImageManipulation/IImageManipulator.php
+++ b/src/Services/ImageManipulation/IImageManipulator.php
@@ -3,18 +3,18 @@ namespace Szurubooru\Services\ImageManipulation;
interface IImageManipulator
{
- const FORMAT_JPEG = 0;
- const FORMAT_PNG = 1;
+ const FORMAT_JPEG = 0;
+ const FORMAT_PNG = 1;
- public function loadFromBuffer($source);
+ public function loadFromBuffer($source);
- public function getImageWidth($imageResource);
+ public function getImageWidth($imageResource);
- public function getImageHeight($imageResource);
+ public function getImageHeight($imageResource);
- public function resizeImage(&$imageResource, $width, $height);
+ public function resizeImage(&$imageResource, $width, $height);
- public function cropImage(&$imageResource, $width, $height, $originX, $originY);
+ public function cropImage(&$imageResource, $width, $height, $originX, $originY);
- public function saveToBuffer($imageResource, $format);
+ public function saveToBuffer($imageResource, $format);
}
diff --git a/src/Services/ImageManipulation/ImageManipulator.php b/src/Services/ImageManipulation/ImageManipulator.php
index 3f23fa51..a5ec7481 100644
--- a/src/Services/ImageManipulation/ImageManipulator.php
+++ b/src/Services/ImageManipulation/ImageManipulator.php
@@ -5,53 +5,53 @@ use Szurubooru\Services\ImageManipulation\ImagickImageManipulator;
class ImageManipulator implements IImageManipulator
{
- private $strategy;
+ private $strategy;
- public function __construct(
- ImagickImageManipulator $imagickImageManipulator,
- GdImageManipulator $gdImageManipulator)
- {
- if (extension_loaded('imagick'))
- {
- $this->strategy = $imagickImageManipulator;
- }
- else if (extension_loaded('gd'))
- {
- $this->strategy = $gdImageManipulator;
- }
- else
- {
- throw new \RuntimeException('Neither imagick or gd image extensions are enabled');
- }
- }
+ public function __construct(
+ ImagickImageManipulator $imagickImageManipulator,
+ GdImageManipulator $gdImageManipulator)
+ {
+ if (extension_loaded('imagick'))
+ {
+ $this->strategy = $imagickImageManipulator;
+ }
+ else if (extension_loaded('gd'))
+ {
+ $this->strategy = $gdImageManipulator;
+ }
+ else
+ {
+ throw new \RuntimeException('Neither imagick or gd image extensions are enabled');
+ }
+ }
- public function loadFromBuffer($source)
- {
- return $this->strategy->loadFromBuffer($source);
- }
+ public function loadFromBuffer($source)
+ {
+ return $this->strategy->loadFromBuffer($source);
+ }
- public function getImageWidth($imageResource)
- {
- return $this->strategy->getImageWidth($imageResource);
- }
+ public function getImageWidth($imageResource)
+ {
+ return $this->strategy->getImageWidth($imageResource);
+ }
- public function getImageHeight($imageResource)
- {
- return $this->strategy->getImageHeight($imageResource);
- }
+ public function getImageHeight($imageResource)
+ {
+ return $this->strategy->getImageHeight($imageResource);
+ }
- public function resizeImage(&$imageResource, $width, $height)
- {
- return $this->strategy->resizeImage($imageResource, $width, $height);
- }
+ public function resizeImage(&$imageResource, $width, $height)
+ {
+ return $this->strategy->resizeImage($imageResource, $width, $height);
+ }
- public function cropImage(&$imageResource, $width, $height, $originX, $originY)
- {
- return $this->strategy->cropImage($imageResource, $width, $height, $originX, $originY);
- }
+ public function cropImage(&$imageResource, $width, $height, $originX, $originY)
+ {
+ return $this->strategy->cropImage($imageResource, $width, $height, $originX, $originY);
+ }
- public function saveToBuffer($source, $format)
- {
- return $this->strategy->saveToBuffer($source, $format);
- }
+ public function saveToBuffer($source, $format)
+ {
+ return $this->strategy->saveToBuffer($source, $format);
+ }
}
diff --git a/src/Services/ImageManipulation/ImagickImageManipulator.php b/src/Services/ImageManipulation/ImagickImageManipulator.php
index d2e189cb..9779a436 100644
--- a/src/Services/ImageManipulation/ImagickImageManipulator.php
+++ b/src/Services/ImageManipulation/ImagickImageManipulator.php
@@ -3,63 +3,63 @@ namespace Szurubooru\Services\ImageManipulation;
class ImagickImageManipulator implements IImageManipulator
{
- public function loadFromBuffer($source)
- {
- try
- {
- $image = new \Imagick();
- $image->readImageBlob($source);
- if ($image->getImageFormat() == 'GIF')
- $image = $image->coalesceImages();
- return $image;
- }
- catch (\Exception $e)
- {
- return null;
- }
- }
+ public function loadFromBuffer($source)
+ {
+ try
+ {
+ $image = new \Imagick();
+ $image->readImageBlob($source);
+ if ($image->getImageFormat() == 'GIF')
+ $image = $image->coalesceImages();
+ return $image;
+ }
+ catch (\Exception $e)
+ {
+ return null;
+ }
+ }
- public function getImageWidth($imageResource)
- {
- return $imageResource->getImageWidth();
- }
+ public function getImageWidth($imageResource)
+ {
+ return $imageResource->getImageWidth();
+ }
- public function getImageHeight($imageResource)
- {
- return $imageResource->getImageHeight();
- }
+ public function getImageHeight($imageResource)
+ {
+ return $imageResource->getImageHeight();
+ }
- public function resizeImage(&$imageResource, $width, $height)
- {
- $imageResource->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 0.9);
- }
+ public function resizeImage(&$imageResource, $width, $height)
+ {
+ $imageResource->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 0.9);
+ }
- public function cropImage(&$imageResource, $width, $height, $originX, $originY)
- {
- $imageResource->cropImage($width, $height, $originX, $originY);
- $imageResource->setImagePage(0, 0, 0, 0);
- }
+ public function cropImage(&$imageResource, $width, $height, $originX, $originY)
+ {
+ $imageResource->cropImage($width, $height, $originX, $originY);
+ $imageResource->setImagePage(0, 0, 0, 0);
+ }
- public function saveToBuffer($imageResource, $format)
- {
- switch ($format)
- {
- case self::FORMAT_JPEG:
- $matte = new \Imagick();
- $matte->newImage($imageResource->getImageWidth(), $imageResource->getImageHeight(), 'white');
- $matte->compositeimage($imageResource, \Imagick::COMPOSITE_OVER, 0, 0);
- $imageResource = $matte;
- $imageResource->setImageFormat('jpeg');
- break;
+ public function saveToBuffer($imageResource, $format)
+ {
+ switch ($format)
+ {
+ case self::FORMAT_JPEG:
+ $matte = new \Imagick();
+ $matte->newImage($imageResource->getImageWidth(), $imageResource->getImageHeight(), 'white');
+ $matte->compositeimage($imageResource, \Imagick::COMPOSITE_OVER, 0, 0);
+ $imageResource = $matte;
+ $imageResource->setImageFormat('jpeg');
+ break;
- case self::FORMAT_PNG:
- $imageResource->setImageFormat('png');
- break;
+ case self::FORMAT_PNG:
+ $imageResource->setImageFormat('png');
+ break;
- default:
- throw new \InvalidArgumentException('Not supported');
- }
+ default:
+ throw new \InvalidArgumentException('Not supported');
+ }
- return $imageResource->getImageBlob();
- }
+ return $imageResource->getImageBlob();
+ }
}
diff --git a/src/Services/NetworkingService.php b/src/Services/NetworkingService.php
index 453cdd58..3ffefc14 100644
--- a/src/Services/NetworkingService.php
+++ b/src/Services/NetworkingService.php
@@ -5,98 +5,98 @@ use Szurubooru\Helpers\HttpHelper;
class NetworkingService
{
- private $httpHelper;
+ private $httpHelper;
- public function __construct(HttpHelper $httpHelper)
- {
- $this->httpHelper = $httpHelper;
- }
+ public function __construct(HttpHelper $httpHelper)
+ {
+ $this->httpHelper = $httpHelper;
+ }
- public function serveFile($fullPath, $customFileName = null)
- {
- if (!file_exists($fullPath))
- throw new \Exception('File "' . $fullPath . '" does not exist.');
+ public function serveFile($fullPath, $customFileName = null)
+ {
+ if (!file_exists($fullPath))
+ throw new \Exception('File "' . $fullPath . '" does not exist.');
- $daysToLive = 7;
- $secondsToLive = $daysToLive * 24 * 60 * 60;
- $lastModified = filemtime($fullPath);
- $eTag = md5($fullPath . $lastModified);
+ $daysToLive = 7;
+ $secondsToLive = $daysToLive * 24 * 60 * 60;
+ $lastModified = filemtime($fullPath);
+ $eTag = md5($fullPath . $lastModified);
- $ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
- ? $_SERVER['HTTP_IF_MODIFIED_SINCE']
- : false;
+ $ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
+ ? $_SERVER['HTTP_IF_MODIFIED_SINCE']
+ : false;
- $eTagHeader = isset($_SERVER['HTTP_IF_NONE_MATCH'])
- ? trim($_SERVER['HTTP_IF_NONE_MATCH'], "\" \t\r\n")
- : null;
+ $eTagHeader = isset($_SERVER['HTTP_IF_NONE_MATCH'])
+ ? trim($_SERVER['HTTP_IF_NONE_MATCH'], "\" \t\r\n")
+ : null;
- $this->httpHelper->setHeader('ETag', '"' . $eTag . '"');
- $this->httpHelper->setHeader('Last-Modified', gmdate('D, d M Y H:i:s \G\M\T', $lastModified));
- $this->httpHelper->setHeader('Pragma', 'public');
- $this->httpHelper->setHeader('Cache-Control', 'public, max-age=' . $secondsToLive);
- $this->httpHelper->setHeader('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + $secondsToLive));
- $this->httpHelper->setHeader('Content-Type', MimeHelper::getMimeTypeFromFile($fullPath));
+ $this->httpHelper->setHeader('ETag', '"' . $eTag . '"');
+ $this->httpHelper->setHeader('Last-Modified', gmdate('D, d M Y H:i:s \G\M\T', $lastModified));
+ $this->httpHelper->setHeader('Pragma', 'public');
+ $this->httpHelper->setHeader('Cache-Control', 'public, max-age=' . $secondsToLive);
+ $this->httpHelper->setHeader('Expires', gmdate('D, d M Y H:i:s \G\M\T', time() + $secondsToLive));
+ $this->httpHelper->setHeader('Content-Type', MimeHelper::getMimeTypeFromFile($fullPath));
- if ($customFileName)
- $this->httpHelper->setHeader('Content-Disposition', 'inline; filename="' . $customFileName . '"');
+ if ($customFileName)
+ $this->httpHelper->setHeader('Content-Disposition', 'inline; filename="' . $customFileName . '"');
- if (strtotime($ifModifiedSince) === $lastModified || $eTagHeader === $eTag)
- {
- $this->httpHelper->setResponseCode(304);
- }
- else
- {
- $this->httpHelper->setResponseCode(200);
- readfile($fullPath);
- }
- exit;
- }
+ if (strtotime($ifModifiedSince) === $lastModified || $eTagHeader === $eTag)
+ {
+ $this->httpHelper->setResponseCode(304);
+ }
+ else
+ {
+ $this->httpHelper->setResponseCode(200);
+ readfile($fullPath);
+ }
+ exit;
+ }
- public function download($url, $maxBytes = null)
- {
- set_time_limit(60);
- try
- {
- $srcHandle = fopen($url, 'rb');
- }
- catch (Exception $e)
- {
- throw new \Exception('Cannot open URL for reading: ' . $e->getMessage());
- }
+ public function download($url, $maxBytes = null)
+ {
+ set_time_limit(60);
+ try
+ {
+ $srcHandle = fopen($url, 'rb');
+ }
+ catch (Exception $e)
+ {
+ throw new \Exception('Cannot open URL for reading: ' . $e->getMessage());
+ }
- if (!$srcHandle)
- throw new \Exception('Cannot open URL for reading');
+ if (!$srcHandle)
+ throw new \Exception('Cannot open URL for reading');
- $result = '';
- try
- {
- while (!feof($srcHandle))
- {
- $buffer = fread($srcHandle, 4 * 1024);
- if ($maxBytes !== null && strlen($result) > $maxBytes)
- {
- throw new \Exception(
- 'File is too big (maximum size: %s)',
- TextHelper::useBytesUnits($maxBytes));
- }
- $result .= $buffer;
- }
- }
- finally
- {
- fclose($srcHandle);
- }
+ $result = '';
+ try
+ {
+ while (!feof($srcHandle))
+ {
+ $buffer = fread($srcHandle, 4 * 1024);
+ if ($maxBytes !== null && strlen($result) > $maxBytes)
+ {
+ throw new \Exception(
+ 'File is too big (maximum size: %s)',
+ TextHelper::useBytesUnits($maxBytes));
+ }
+ $result .= $buffer;
+ }
+ }
+ finally
+ {
+ fclose($srcHandle);
+ }
- return $result;
- }
+ return $result;
+ }
- public function redirect($destination)
- {
- $this->httpHelper->redirect($destination);
- }
+ public function redirect($destination)
+ {
+ $this->httpHelper->redirect($destination);
+ }
- public function nonCachedRedirect($destination)
- {
- $this->httpHelper->nonCachedRedirect($destination);
- }
+ public function nonCachedRedirect($destination)
+ {
+ $this->httpHelper->nonCachedRedirect($destination);
+ }
}
diff --git a/src/Services/PasswordService.php b/src/Services/PasswordService.php
index cc5cc250..3e40e598 100644
--- a/src/Services/PasswordService.php
+++ b/src/Services/PasswordService.php
@@ -4,52 +4,52 @@ use Szurubooru\Config;
class PasswordService
{
- private $config;
- private $alphabet;
- private $pattern;
+ private $config;
+ private $alphabet;
+ private $pattern;
- public function __construct(Config $config)
- {
- $this->config = $config;
- $this->alphabet =
- [
- 'c' => str_split('bcdfghjklmnpqrstvwxyz'),
- 'v' => str_split('aeiou'),
- 'n' => str_split('0123456789'),
- ];
- $this->pattern = str_split('cvcvnncvcv');
- }
+ public function __construct(Config $config)
+ {
+ $this->config = $config;
+ $this->alphabet =
+ [
+ 'c' => str_split('bcdfghjklmnpqrstvwxyz'),
+ 'v' => str_split('aeiou'),
+ 'n' => str_split('0123456789'),
+ ];
+ $this->pattern = str_split('cvcvnncvcv');
+ }
- public function getLegacyHash($password, $salt)
- {
- //hash used by old szurubooru version
- return sha1('1A2/$_4xVa' . $salt . $password);
- }
+ public function getLegacyHash($password, $salt)
+ {
+ //hash used by old szurubooru version
+ return sha1('1A2/$_4xVa' . $salt . $password);
+ }
- public function getHash($password, $salt)
- {
- return hash('sha256', $this->config->security->secret . $salt . $password);
- }
+ public function getHash($password, $salt)
+ {
+ return hash('sha256', $this->config->security->secret . $salt . $password);
+ }
- public function isHashValid($password, $salt, $expectedPasswordHash)
- {
- $hashes =
- [
- $this->getLegacyHash($password, $salt),
- $this->getHash($password, $salt),
- ];
- return in_array($expectedPasswordHash, $hashes);
- }
+ public function isHashValid($password, $salt, $expectedPasswordHash)
+ {
+ $hashes =
+ [
+ $this->getLegacyHash($password, $salt),
+ $this->getHash($password, $salt),
+ ];
+ return in_array($expectedPasswordHash, $hashes);
+ }
- public function getRandomPassword()
- {
- $password = '';
- foreach ($this->pattern as $token)
- {
- $subAlphabet = $this->alphabet[$token];
- $character = $subAlphabet[mt_rand(0, count($subAlphabet) - 1)];
- $password .= $character;
- }
- return $password;
- }
+ public function getRandomPassword()
+ {
+ $password = '';
+ foreach ($this->pattern as $token)
+ {
+ $subAlphabet = $this->alphabet[$token];
+ $character = $subAlphabet[mt_rand(0, count($subAlphabet) - 1)];
+ $password .= $character;
+ }
+ return $password;
+ }
}
diff --git a/src/Services/PostFeatureService.php b/src/Services/PostFeatureService.php
index 0a1835a9..55b67483 100644
--- a/src/Services/PostFeatureService.php
+++ b/src/Services/PostFeatureService.php
@@ -13,83 +13,83 @@ use Szurubooru\Validator;
class PostFeatureService
{
- private $transactionManager;
- private $postDao;
- private $userDao;
- private $globalParamDao;
- private $authService;
- private $timeService;
- private $postHistoryService;
+ private $transactionManager;
+ private $postDao;
+ private $userDao;
+ private $globalParamDao;
+ private $authService;
+ private $timeService;
+ private $postHistoryService;
- public function __construct(
- TransactionManager $transactionManager,
- PostDao $postDao,
- UserDao $userDao,
- GlobalParamDao $globalParamDao,
- AuthService $authService,
- TimeService $timeService,
- PostHistoryService $postHistoryService)
- {
- $this->transactionManager = $transactionManager;
- $this->postDao = $postDao;
- $this->userDao = $userDao;
- $this->globalParamDao = $globalParamDao;
- $this->authService = $authService;
- $this->timeService = $timeService;
- $this->postHistoryService = $postHistoryService;
- }
+ public function __construct(
+ TransactionManager $transactionManager,
+ PostDao $postDao,
+ UserDao $userDao,
+ GlobalParamDao $globalParamDao,
+ AuthService $authService,
+ TimeService $timeService,
+ PostHistoryService $postHistoryService)
+ {
+ $this->transactionManager = $transactionManager;
+ $this->postDao = $postDao;
+ $this->userDao = $userDao;
+ $this->globalParamDao = $globalParamDao;
+ $this->authService = $authService;
+ $this->timeService = $timeService;
+ $this->postHistoryService = $postHistoryService;
+ }
- public function getFeaturedPost()
- {
- $transactionFunc = function()
- {
- $globalParam = $this->globalParamDao->findByKey(GlobalParam::KEY_FEATURED_POST);
- if (!$globalParam)
- return null;
- return $this->postDao->findById($globalParam->getValue());
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFeaturedPost()
+ {
+ $transactionFunc = function()
+ {
+ $globalParam = $this->globalParamDao->findByKey(GlobalParam::KEY_FEATURED_POST);
+ if (!$globalParam)
+ return null;
+ return $this->postDao->findById($globalParam->getValue());
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getFeaturedPostUser()
- {
- $transactionFunc = function()
- {
- $globalParam = $this->globalParamDao->findByKey(GlobalParam::KEY_FEATURED_POST_USER);
- if (!$globalParam)
- return null;
- return $this->userDao->findById($globalParam->getValue());
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFeaturedPostUser()
+ {
+ $transactionFunc = function()
+ {
+ $globalParam = $this->globalParamDao->findByKey(GlobalParam::KEY_FEATURED_POST_USER);
+ if (!$globalParam)
+ return null;
+ return $this->userDao->findById($globalParam->getValue());
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function featurePost(Post $post)
- {
- $transactionFunc = function() use ($post)
- {
- $previousFeaturedPost = $this->getFeaturedPost();
+ public function featurePost(Post $post)
+ {
+ $transactionFunc = function() use ($post)
+ {
+ $previousFeaturedPost = $this->getFeaturedPost();
- if (($previousFeaturedPost === null) || ($previousFeaturedPost->getId() !== $post->getId()))
- {
- $post->setLastFeatureTime($this->timeService->getCurrentTime());
- $post->setFeatureCount($post->getFeatureCount() + 1);
- $this->postDao->save($post);
- }
+ if (($previousFeaturedPost === null) || ($previousFeaturedPost->getId() !== $post->getId()))
+ {
+ $post->setLastFeatureTime($this->timeService->getCurrentTime());
+ $post->setFeatureCount($post->getFeatureCount() + 1);
+ $this->postDao->save($post);
+ }
- $globalParam = new GlobalParam();
- $globalParam->setKey(GlobalParam::KEY_FEATURED_POST);
- $globalParam->setValue($post->getId());
- $this->globalParamDao->save($globalParam);
+ $globalParam = new GlobalParam();
+ $globalParam->setKey(GlobalParam::KEY_FEATURED_POST);
+ $globalParam->setValue($post->getId());
+ $this->globalParamDao->save($globalParam);
- $globalParam = new GlobalParam();
- $globalParam->setKey(GlobalParam::KEY_FEATURED_POST_USER);
- $globalParam->setValue($this->authService->getLoggedInUser()->getId());
- $this->globalParamDao->save($globalParam);
+ $globalParam = new GlobalParam();
+ $globalParam->setKey(GlobalParam::KEY_FEATURED_POST_USER);
+ $globalParam->setValue($this->authService->getLoggedInUser()->getId());
+ $this->globalParamDao->save($globalParam);
- if ($previousFeaturedPost)
- $this->postHistoryService->savePostChange($previousFeaturedPost);
- $this->postHistoryService->savePostChange($post);
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ if ($previousFeaturedPost)
+ $this->postHistoryService->savePostChange($previousFeaturedPost);
+ $this->postHistoryService->savePostChange($post);
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
}
diff --git a/src/Services/PostHistoryService.php b/src/Services/PostHistoryService.php
index 40832fa6..5bf0eb65 100644
--- a/src/Services/PostHistoryService.php
+++ b/src/Services/PostHistoryService.php
@@ -11,53 +11,53 @@ use Szurubooru\Services\PostSnapshotProvider;
class PostHistoryService
{
- private $transactionManager;
- private $historyService;
- private $postSnapshotProvider;
+ private $transactionManager;
+ private $historyService;
+ private $postSnapshotProvider;
- public function __construct(
- TransactionManager $transactionManager,
- HistoryService $historyService,
- PostSnapshotProvider $postSnapshotProvider)
- {
- $this->transactionManager = $transactionManager;
- $this->historyService = $historyService;
- $this->postSnapshotProvider = $postSnapshotProvider;
- }
+ public function __construct(
+ TransactionManager $transactionManager,
+ HistoryService $historyService,
+ PostSnapshotProvider $postSnapshotProvider)
+ {
+ $this->transactionManager = $transactionManager;
+ $this->historyService = $historyService;
+ $this->postSnapshotProvider = $postSnapshotProvider;
+ }
- public function getPostHistory(Post $post)
- {
- $transactionFunc = function() use ($post)
- {
- $filter = new SnapshotFilter();
+ public function getPostHistory(Post $post)
+ {
+ $transactionFunc = function() use ($post)
+ {
+ $filter = new SnapshotFilter();
- $requirement = new Requirement();
- $requirement->setType(SnapshotFilter::REQUIREMENT_PRIMARY_KEY);
- $requirement->setValue(new RequirementSingleValue($post->getId()));
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setType(SnapshotFilter::REQUIREMENT_PRIMARY_KEY);
+ $requirement->setValue(new RequirementSingleValue($post->getId()));
+ $filter->addRequirement($requirement);
- $requirement = new Requirement();
- $requirement->setType(SnapshotFilter::REQUIREMENT_TYPE);
- $requirement->setValue(new RequirementSingleValue(Snapshot::TYPE_POST));
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setType(SnapshotFilter::REQUIREMENT_TYPE);
+ $requirement->setValue(new RequirementSingleValue(Snapshot::TYPE_POST));
+ $filter->addRequirement($requirement);
- return $this->historyService->getFiltered($filter)->getEntities();
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ return $this->historyService->getFiltered($filter)->getEntities();
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function savePostCreation(Post $post)
- {
- $this->historyService->saveSnapshot($this->postSnapshotProvider->getCreationSnapshot($post));
- }
+ public function savePostCreation(Post $post)
+ {
+ $this->historyService->saveSnapshot($this->postSnapshotProvider->getCreationSnapshot($post));
+ }
- public function savePostChange(Post $post)
- {
- $this->historyService->saveSnapshot($this->postSnapshotProvider->getChangeSnapshot($post));
- }
+ public function savePostChange(Post $post)
+ {
+ $this->historyService->saveSnapshot($this->postSnapshotProvider->getChangeSnapshot($post));
+ }
- public function savePostDeletion(Post $post)
- {
- $this->historyService->saveSnapshot($this->postSnapshotProvider->getDeleteSnapshot($post));
- }
+ public function savePostDeletion(Post $post)
+ {
+ $this->historyService->saveSnapshot($this->postSnapshotProvider->getDeleteSnapshot($post));
+ }
}
diff --git a/src/Services/PostNotesService.php b/src/Services/PostNotesService.php
index 47c09151..516873db 100644
--- a/src/Services/PostNotesService.php
+++ b/src/Services/PostNotesService.php
@@ -10,90 +10,90 @@ use Szurubooru\Validator;
class PostNotesService
{
- private $validator;
- private $transactionManager;
- private $postNoteDao;
- private $postHistoryService;
+ private $validator;
+ private $transactionManager;
+ private $postNoteDao;
+ private $postHistoryService;
- public function __construct(
- Validator $validator,
- TransactionManager $transactionManager,
- PostNoteDao $postNoteDao,
- PostHistoryService $postHistoryService)
- {
- $this->validator = $validator;
- $this->transactionManager = $transactionManager;
- $this->postNoteDao = $postNoteDao;
- $this->postHistoryService = $postHistoryService;
- }
+ public function __construct(
+ Validator $validator,
+ TransactionManager $transactionManager,
+ PostNoteDao $postNoteDao,
+ PostHistoryService $postHistoryService)
+ {
+ $this->validator = $validator;
+ $this->transactionManager = $transactionManager;
+ $this->postNoteDao = $postNoteDao;
+ $this->postHistoryService = $postHistoryService;
+ }
- public function getById($postNoteId)
- {
- $transactionFunc = function() use ($postNoteId)
- {
- $postNote = $this->postNoteDao->findById($postNoteId);
- if (!$postNote)
- throw new \InvalidArgumentException('Post note with ID "' . $postNoteId . '" was not found.');
- return $postNote;
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getById($postNoteId)
+ {
+ $transactionFunc = function() use ($postNoteId)
+ {
+ $postNote = $this->postNoteDao->findById($postNoteId);
+ if (!$postNote)
+ throw new \InvalidArgumentException('Post note with ID "' . $postNoteId . '" was not found.');
+ return $postNote;
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getByPost(Post $post)
- {
- $transactionFunc = function() use ($post)
- {
- return $this->postNoteDao->findByPostId($post->getId());
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getByPost(Post $post)
+ {
+ $transactionFunc = function() use ($post)
+ {
+ return $this->postNoteDao->findByPostId($post->getId());
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function createPostNote(Post $post, PostNoteFormData $formData)
- {
- $transactionFunc = function() use ($post, $formData)
- {
- $postNote = new PostNote();
- $postNote->setPostId($post->getId());
+ public function createPostNote(Post $post, PostNoteFormData $formData)
+ {
+ $transactionFunc = function() use ($post, $formData)
+ {
+ $postNote = new PostNote();
+ $postNote->setPostId($post->getId());
- $this->updatePostNoteWithFormData($postNote, $formData);
- $this->postNoteDao->save($postNote);
+ $this->updatePostNoteWithFormData($postNote, $formData);
+ $this->postNoteDao->save($postNote);
- $this->postHistoryService->savePostChange($post);
- return $postNote;
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ $this->postHistoryService->savePostChange($post);
+ return $postNote;
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function updatePostNote(PostNote $postNote, PostNoteFormData $formData)
- {
- $transactionFunc = function() use ($postNote, $formData)
- {
- $this->updatePostNoteWithFormData($postNote, $formData);
- $this->postNoteDao->save($postNote);
+ public function updatePostNote(PostNote $postNote, PostNoteFormData $formData)
+ {
+ $transactionFunc = function() use ($postNote, $formData)
+ {
+ $this->updatePostNoteWithFormData($postNote, $formData);
+ $this->postNoteDao->save($postNote);
- $this->postHistoryService->savePostChange($postNote->getPost());
- return $postNote;
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ $this->postHistoryService->savePostChange($postNote->getPost());
+ return $postNote;
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function deletePostNote(PostNote $postNote)
- {
- $transactionFunc = function() use ($postNote)
- {
- $this->postNoteDao->deleteById($postNote->getId());
- $this->postHistoryService->savePostChange($postNote->getPost());
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ public function deletePostNote(PostNote $postNote)
+ {
+ $transactionFunc = function() use ($postNote)
+ {
+ $this->postNoteDao->deleteById($postNote->getId());
+ $this->postHistoryService->savePostChange($postNote->getPost());
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
- private function updatePostNoteWithFormData(PostNote $postNote, PostNoteFormData $formData)
- {
- $formData->validate($this->validator);
- $postNote->setLeft($formData->left);
- $postNote->setTop($formData->top);
- $postNote->setWidth($formData->width);
- $postNote->setHeight($formData->height);
- $postNote->setText($formData->text);
- }
+ private function updatePostNoteWithFormData(PostNote $postNote, PostNoteFormData $formData)
+ {
+ $formData->validate($this->validator);
+ $postNote->setLeft($formData->left);
+ $postNote->setTop($formData->top);
+ $postNote->setWidth($formData->width);
+ $postNote->setHeight($formData->height);
+ $postNote->setText($formData->text);
+ }
}
diff --git a/src/Services/PostService.php b/src/Services/PostService.php
index 7837bdc5..3a6d211e 100644
--- a/src/Services/PostService.php
+++ b/src/Services/PostService.php
@@ -27,388 +27,388 @@ use Szurubooru\Validator;
class PostService
{
- private $config;
- private $validator;
- private $transactionManager;
- private $postDao;
- private $globalParamDao;
- private $timeService;
- private $authService;
- private $networkingService;
- private $tagService;
- private $postHistoryService;
- private $imageConverter;
- private $imageManipulator;
+ private $config;
+ private $validator;
+ private $transactionManager;
+ private $postDao;
+ private $globalParamDao;
+ private $timeService;
+ private $authService;
+ private $networkingService;
+ private $tagService;
+ private $postHistoryService;
+ private $imageConverter;
+ private $imageManipulator;
- public function __construct(
- Config $config,
- Validator $validator,
- TransactionManager $transactionManager,
- PostDao $postDao,
- GlobalParamDao $globalParamDao,
- AuthService $authService,
- TimeService $timeService,
- NetworkingService $networkingService,
- TagService $tagService,
- PostHistoryService $postHistoryService,
- ImageConverter $imageConverter,
- ImageManipulator $imageManipulator)
- {
- $this->config = $config;
- $this->validator = $validator;
- $this->transactionManager = $transactionManager;
- $this->postDao = $postDao;
- $this->globalParamDao = $globalParamDao;
- $this->timeService = $timeService;
- $this->authService = $authService;
- $this->networkingService = $networkingService;
- $this->tagService = $tagService;
- $this->postHistoryService = $postHistoryService;
- $this->imageConverter = $imageConverter;
- $this->imageManipulator = $imageManipulator;
- }
+ public function __construct(
+ Config $config,
+ Validator $validator,
+ TransactionManager $transactionManager,
+ PostDao $postDao,
+ GlobalParamDao $globalParamDao,
+ AuthService $authService,
+ TimeService $timeService,
+ NetworkingService $networkingService,
+ TagService $tagService,
+ PostHistoryService $postHistoryService,
+ ImageConverter $imageConverter,
+ ImageManipulator $imageManipulator)
+ {
+ $this->config = $config;
+ $this->validator = $validator;
+ $this->transactionManager = $transactionManager;
+ $this->postDao = $postDao;
+ $this->globalParamDao = $globalParamDao;
+ $this->timeService = $timeService;
+ $this->authService = $authService;
+ $this->networkingService = $networkingService;
+ $this->tagService = $tagService;
+ $this->postHistoryService = $postHistoryService;
+ $this->imageConverter = $imageConverter;
+ $this->imageManipulator = $imageManipulator;
+ }
- public function getByNameOrId($postNameOrId)
- {
- $transactionFunc = function() use ($postNameOrId)
- {
- $post = $this->postDao->findByName($postNameOrId);
- if (!$post)
- $post = $this->postDao->findById($postNameOrId);
- if (!$post)
- throw new \InvalidArgumentException('Post with name "' . $postNameOrId . '" was not found.');
- return $post;
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getByNameOrId($postNameOrId)
+ {
+ $transactionFunc = function() use ($postNameOrId)
+ {
+ $post = $this->postDao->findByName($postNameOrId);
+ if (!$post)
+ $post = $this->postDao->findById($postNameOrId);
+ if (!$post)
+ throw new \InvalidArgumentException('Post with name "' . $postNameOrId . '" was not found.');
+ return $post;
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getByName($postName)
- {
- $transactionFunc = function() use ($postName)
- {
- $post = $this->postDao->findByName($postName);
- if (!$post)
- throw new \InvalidArgumentException('Post with name "' . $postName . '" was not found.');
- return $post;
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getByName($postName)
+ {
+ $transactionFunc = function() use ($postName)
+ {
+ $post = $this->postDao->findByName($postName);
+ if (!$post)
+ throw new \InvalidArgumentException('Post with name "' . $postName . '" was not found.');
+ return $post;
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getFiltered(PostFilter $filter)
- {
- $transactionFunc = function() use ($filter)
- {
- return $this->postDao->findFiltered($filter);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFiltered(PostFilter $filter)
+ {
+ $transactionFunc = function() use ($filter)
+ {
+ return $this->postDao->findFiltered($filter);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function createPost(UploadFormData $formData)
- {
- $transactionFunc = function() use ($formData)
- {
- $formData->validate($this->validator);
+ public function createPost(UploadFormData $formData)
+ {
+ $transactionFunc = function() use ($formData)
+ {
+ $formData->validate($this->validator);
- if ($formData->anonymous)
- $this->authService->loginAnonymous();
+ if ($formData->anonymous)
+ $this->authService->loginAnonymous();
- $post = new Post();
- $post->setUploadTime($this->timeService->getCurrentTime());
- $post->setLastEditTime($this->timeService->getCurrentTime());
- $post->setUser($this->authService->getLoggedInUser());
- $post->setOriginalFileName($formData->contentFileName);
- $post->setName($this->getUniqueRandomPostName());
+ $post = new Post();
+ $post->setUploadTime($this->timeService->getCurrentTime());
+ $post->setLastEditTime($this->timeService->getCurrentTime());
+ $post->setUser($this->authService->getLoggedInUser());
+ $post->setOriginalFileName($formData->contentFileName);
+ $post->setName($this->getUniqueRandomPostName());
- $this->updatePostSafety($post, $formData->safety);
- $this->updatePostSource($post, $formData->source);
- $this->updatePostTags($post, $formData->tags);
- $this->updatePostContentFromStringOrUrl($post, $formData->content, $formData->url);
+ $this->updatePostSafety($post, $formData->safety);
+ $this->updatePostSource($post, $formData->source);
+ $this->updatePostTags($post, $formData->tags);
+ $this->updatePostContentFromStringOrUrl($post, $formData->content, $formData->url);
- $savedPost = $this->postDao->save($post);
+ $savedPost = $this->postDao->save($post);
- $this->postHistoryService->savePostCreation($savedPost);
- return $savedPost;
- };
- $ret = $this->transactionManager->commit($transactionFunc);
- $this->tagService->exportJson();
- return $ret;
- }
+ $this->postHistoryService->savePostCreation($savedPost);
+ return $savedPost;
+ };
+ $ret = $this->transactionManager->commit($transactionFunc);
+ $this->tagService->exportJson();
+ return $ret;
+ }
- public function updatePost(Post $post, PostEditFormData $formData)
- {
- $transactionFunc = function() use ($post, $formData)
- {
- $this->validator->validate($formData);
+ public function updatePost(Post $post, PostEditFormData $formData)
+ {
+ $transactionFunc = function() use ($post, $formData)
+ {
+ $this->validator->validate($formData);
- if ($post->getLastEditTime() !== $formData->seenEditTime)
- throw new \DomainException('Someone has already edited this post in the meantime.');
+ if ($post->getLastEditTime() !== $formData->seenEditTime)
+ throw new \DomainException('Someone has already edited this post in the meantime.');
- $post->setLastEditTime($this->timeService->getCurrentTime());
+ $post->setLastEditTime($this->timeService->getCurrentTime());
- if ($formData->content !== null)
- $this->updatePostContentFromString($post, $formData->content);
+ if ($formData->content !== null)
+ $this->updatePostContentFromString($post, $formData->content);
- if ($formData->thumbnail !== null)
- $this->updatePostThumbnailFromString($post, $formData->thumbnail);
+ if ($formData->thumbnail !== null)
+ $this->updatePostThumbnailFromString($post, $formData->thumbnail);
- if ($formData->safety !== null)
- $this->updatePostSafety($post, $formData->safety);
+ if ($formData->safety !== null)
+ $this->updatePostSafety($post, $formData->safety);
- if ($formData->source !== null)
- $this->updatePostSource($post, $formData->source);
+ if ($formData->source !== null)
+ $this->updatePostSource($post, $formData->source);
- if ($formData->tags !== null)
- $this->updatePostTags($post, $formData->tags);
+ if ($formData->tags !== null)
+ $this->updatePostTags($post, $formData->tags);
- if ($formData->relations !== null)
- $this->updatePostRelations($post, $formData->relations);
+ if ($formData->relations !== null)
+ $this->updatePostRelations($post, $formData->relations);
- if (count($formData->flags) > 0)
- $this->updatePostFlags($post, $formData->flags);
+ if (count($formData->flags) > 0)
+ $this->updatePostFlags($post, $formData->flags);
- $this->postHistoryService->savePostChange($post);
- return $this->postDao->save($post);
- };
- $ret = $this->transactionManager->commit($transactionFunc);
- $this->tagService->exportJson();
- return $ret;
- }
+ $this->postHistoryService->savePostChange($post);
+ return $this->postDao->save($post);
+ };
+ $ret = $this->transactionManager->commit($transactionFunc);
+ $this->tagService->exportJson();
+ return $ret;
+ }
- private function updatePostSafety(Post $post, $newSafety)
- {
- $post->setSafety($newSafety);
- }
+ private function updatePostSafety(Post $post, $newSafety)
+ {
+ $post->setSafety($newSafety);
+ }
- private function updatePostSource(Post $post, $newSource)
- {
- $post->setSource($newSource);
- }
+ private function updatePostSource(Post $post, $newSource)
+ {
+ $post->setSource($newSource);
+ }
- private function updatePostContentFromStringOrUrl(Post $post, $content, $url)
- {
- if ($url)
- $this->updatePostContentFromUrl($post, $url);
- else if ($content)
- $this->updatePostContentFromString($post, $content);
- else
- throw new \DomainException('No content specified');
- }
+ private function updatePostContentFromStringOrUrl(Post $post, $content, $url)
+ {
+ if ($url)
+ $this->updatePostContentFromUrl($post, $url);
+ else if ($content)
+ $this->updatePostContentFromString($post, $content);
+ else
+ throw new \DomainException('No content specified');
+ }
- private function updatePostContentFromString(Post $post, $content)
- {
- if (!$content)
- throw new \DomainException('File cannot be empty.');
+ private function updatePostContentFromString(Post $post, $content)
+ {
+ if (!$content)
+ throw new \DomainException('File cannot be empty.');
- if (strlen($content) > $this->config->database->maxPostSize)
- throw new \DomainException('Upload is too big.');
+ if (strlen($content) > $this->config->database->maxPostSize)
+ throw new \DomainException('Upload is too big.');
- $mime = MimeHelper::getMimeTypeFromBuffer($content);
- $post->setContentMimeType($mime);
+ $mime = MimeHelper::getMimeTypeFromBuffer($content);
+ $post->setContentMimeType($mime);
- if (MimeHelper::isFlash($mime))
- {
- $post->setContentType(Post::POST_TYPE_FLASH);
- }
- elseif (MimeHelper::isImage($mime))
- {
- $post->setContentType(
- MimeHelper::isBufferAnimatedGif($content)
- ? Post::POST_TYPE_ANIMATED_IMAGE
- : Post::POST_TYPE_IMAGE);
- }
- elseif (MimeHelper::isVideo($mime))
- {
- $post->setContentType(Post::POST_TYPE_VIDEO);
- }
- else
- {
- throw new \DomainException('Unhandled file type: "' . $mime . '"');
- }
+ if (MimeHelper::isFlash($mime))
+ {
+ $post->setContentType(Post::POST_TYPE_FLASH);
+ }
+ elseif (MimeHelper::isImage($mime))
+ {
+ $post->setContentType(
+ MimeHelper::isBufferAnimatedGif($content)
+ ? Post::POST_TYPE_ANIMATED_IMAGE
+ : Post::POST_TYPE_IMAGE);
+ }
+ elseif (MimeHelper::isVideo($mime))
+ {
+ $post->setContentType(Post::POST_TYPE_VIDEO);
+ }
+ else
+ {
+ throw new \DomainException('Unhandled file type: "' . $mime . '"');
+ }
- $post->setContentChecksum(sha1($content));
- $this->assertNoPostWithThisContentChecksum($post);
+ $post->setContentChecksum(sha1($content));
+ $this->assertNoPostWithThisContentChecksum($post);
- $post->setContent($content);
+ $post->setContent($content);
- try
- {
- $image = $this->imageConverter->createImageFromBuffer($content);
- $post->setImageWidth($this->imageManipulator->getImageWidth($image));
- $post->setImageHeight($this->imageManipulator->getImageHeight($image));
- }
- catch (\Exception $e)
- {
- $post->setImageWidth(null);
- $post->setImageHeight(null);
- }
+ try
+ {
+ $image = $this->imageConverter->createImageFromBuffer($content);
+ $post->setImageWidth($this->imageManipulator->getImageWidth($image));
+ $post->setImageHeight($this->imageManipulator->getImageHeight($image));
+ }
+ catch (\Exception $e)
+ {
+ $post->setImageWidth(null);
+ $post->setImageHeight(null);
+ }
- $post->setOriginalFileSize(strlen($content));
- }
+ $post->setOriginalFileSize(strlen($content));
+ }
- private function updatePostContentFromUrl(Post $post, $url)
- {
- if (!preg_match('/^https?:\/\//', $url))
- throw new \InvalidArgumentException('Invalid URL "' . $url . '"');
+ private function updatePostContentFromUrl(Post $post, $url)
+ {
+ if (!preg_match('/^https?:\/\//', $url))
+ throw new \InvalidArgumentException('Invalid URL "' . $url . '"');
- $youtubeId = null;
- if (preg_match('/youtube.com\/watch.*?=([a-zA-Z0-9_-]+)/', $url, $matches))
- $youtubeId = $matches[1];
+ $youtubeId = null;
+ if (preg_match('/youtube.com\/watch.*?=([a-zA-Z0-9_-]+)/', $url, $matches))
+ $youtubeId = $matches[1];
- if ($youtubeId)
- {
- $post->setContentType(Post::POST_TYPE_YOUTUBE);
- $post->setImageWidth(null);
- $post->setImageHeight(null);
- $post->setContentChecksum($url);
- $post->setOriginalFileName($url);
- $post->setOriginalFileSize(null);
- $post->setContentChecksum($youtubeId);
+ if ($youtubeId)
+ {
+ $post->setContentType(Post::POST_TYPE_YOUTUBE);
+ $post->setImageWidth(null);
+ $post->setImageHeight(null);
+ $post->setContentChecksum($url);
+ $post->setOriginalFileName($url);
+ $post->setOriginalFileSize(null);
+ $post->setContentChecksum($youtubeId);
- $this->assertNoPostWithThisContentChecksum($post);
- $youtubeThumbnailUrl = 'http://img.youtube.com/vi/' . $youtubeId . '/mqdefault.jpg';
- $youtubeThumbnail = $this->networkingService->download($youtubeThumbnailUrl);
- $post->setThumbnailSourceContent($youtubeThumbnail);
- }
- else
- {
- $contents = $this->networkingService->download($url);
- $this->updatePostContentFromString($post, $contents);
- }
- }
+ $this->assertNoPostWithThisContentChecksum($post);
+ $youtubeThumbnailUrl = 'http://img.youtube.com/vi/' . $youtubeId . '/mqdefault.jpg';
+ $youtubeThumbnail = $this->networkingService->download($youtubeThumbnailUrl);
+ $post->setThumbnailSourceContent($youtubeThumbnail);
+ }
+ else
+ {
+ $contents = $this->networkingService->download($url);
+ $this->updatePostContentFromString($post, $contents);
+ }
+ }
- private function updatePostThumbnailFromString(Post $post, $newThumbnail)
- {
- if (strlen($newThumbnail) > $this->config->database->maxCustomThumbnailSize)
- throw new \DomainException('Thumbnail is too big.');
+ private function updatePostThumbnailFromString(Post $post, $newThumbnail)
+ {
+ if (strlen($newThumbnail) > $this->config->database->maxCustomThumbnailSize)
+ throw new \DomainException('Thumbnail is too big.');
- $post->setThumbnailSourceContent($newThumbnail);
- }
+ $post->setThumbnailSourceContent($newThumbnail);
+ }
- private function updatePostTags(Post $post, array $newTagNames)
- {
- $tags = [];
- foreach ($newTagNames as $tagName)
- {
- $tag = new Tag();
- $tag->setName($tagName);
- $tags[] = $tag;
- }
- $tags = $this->tagService->createTags($tags);
- foreach ($tags as $tag)
- {
- if ($tag->isBanned())
- throw new \DomainException('Cannot use banned tag "' . $tag->getName() . '"');
- }
- $post->setTags($tags);
- }
+ private function updatePostTags(Post $post, array $newTagNames)
+ {
+ $tags = [];
+ foreach ($newTagNames as $tagName)
+ {
+ $tag = new Tag();
+ $tag->setName($tagName);
+ $tags[] = $tag;
+ }
+ $tags = $this->tagService->createTags($tags);
+ foreach ($tags as $tag)
+ {
+ if ($tag->isBanned())
+ throw new \DomainException('Cannot use banned tag "' . $tag->getName() . '"');
+ }
+ $post->setTags($tags);
+ }
- private function updatePostRelations(Post $post, array $newRelatedPostIds)
- {
- $relatedPosts = $this->postDao->findByIds($newRelatedPostIds);
- foreach ($newRelatedPostIds as $postId)
- {
- if (!isset($relatedPosts[$postId]))
- throw new \DomainException('Post with id "' . $postId . '" was not found.');
- }
+ private function updatePostRelations(Post $post, array $newRelatedPostIds)
+ {
+ $relatedPosts = $this->postDao->findByIds($newRelatedPostIds);
+ foreach ($newRelatedPostIds as $postId)
+ {
+ if (!isset($relatedPosts[$postId]))
+ throw new \DomainException('Post with id "' . $postId . '" was not found.');
+ }
- $post->setRelatedPosts($relatedPosts);
- }
+ $post->setRelatedPosts($relatedPosts);
+ }
- private function updatePostFlags(Post $post, \StdClass $flags)
- {
- $value = 0;
- if (!empty($flags->loop))
- $value |= Post::FLAG_LOOP;
- $post->setFlags($value);
- }
+ private function updatePostFlags(Post $post, \StdClass $flags)
+ {
+ $value = 0;
+ if (!empty($flags->loop))
+ $value |= Post::FLAG_LOOP;
+ $post->setFlags($value);
+ }
- public function deletePost(Post $post)
- {
- $transactionFunc = function() use ($post)
- {
- $this->postHistoryService->savePostDeletion($post);
- $this->postDao->deleteById($post->getId());
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ public function deletePost(Post $post)
+ {
+ $transactionFunc = function() use ($post)
+ {
+ $this->postHistoryService->savePostDeletion($post);
+ $this->postDao->deleteById($post->getId());
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
- public function updatePostGlobals()
- {
- $transactionFunc = function()
- {
- $countParam = new GlobalParam();
- $countParam->setKey(GlobalParam::KEY_POST_COUNT);
- $countParam->setValue($this->postDao->getCount());
- $this->globalParamDao->save($countParam);
+ public function updatePostGlobals()
+ {
+ $transactionFunc = function()
+ {
+ $countParam = new GlobalParam();
+ $countParam->setKey(GlobalParam::KEY_POST_COUNT);
+ $countParam->setValue($this->postDao->getCount());
+ $this->globalParamDao->save($countParam);
- $fileSizeParam = new GlobalParam();
- $fileSizeParam->setKey(GlobalParam::KEY_POST_SIZE);
- $fileSizeParam->setValue($this->postDao->getTotalFileSize());
- $this->globalParamDao->save($fileSizeParam);
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ $fileSizeParam = new GlobalParam();
+ $fileSizeParam->setKey(GlobalParam::KEY_POST_SIZE);
+ $fileSizeParam->setValue($this->postDao->getTotalFileSize());
+ $this->globalParamDao->save($fileSizeParam);
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
- public function decorateFilterFromBrowsingSettings(PostFilter $filter)
- {
- $currentUser = $this->authService->getLoggedInUser();
- $userSettings = $currentUser->getBrowsingSettings();
- if (!$userSettings)
- return;
+ public function decorateFilterFromBrowsingSettings(PostFilter $filter)
+ {
+ $currentUser = $this->authService->getLoggedInUser();
+ $userSettings = $currentUser->getBrowsingSettings();
+ if (!$userSettings)
+ return;
- if (!empty($userSettings->listPosts) && !count($filter->getRequirementsByType(PostFilter::REQUIREMENT_SAFETY)))
- {
- $values = [];
- if (!TypeHelper::toBool($userSettings->listPosts->safe))
- $values[] = Post::POST_SAFETY_SAFE;
- if (!TypeHelper::toBool($userSettings->listPosts->sketchy))
- $values[] = Post::POST_SAFETY_SKETCHY;
- if (!TypeHelper::toBool($userSettings->listPosts->unsafe))
- $values[] = Post::POST_SAFETY_UNSAFE;
- if (count($values))
- {
- $requirementValue = new RequirementCompositeValue();
- $requirementValue->setValues($values);
- $requirement = new Requirement();
- $requirement->setType(PostFilter::REQUIREMENT_SAFETY);
- $requirement->setValue($requirementValue);
- $requirement->setNegated(true);
- $filter->addRequirement($requirement);
- }
- }
+ if (!empty($userSettings->listPosts) && !count($filter->getRequirementsByType(PostFilter::REQUIREMENT_SAFETY)))
+ {
+ $values = [];
+ if (!TypeHelper::toBool($userSettings->listPosts->safe))
+ $values[] = Post::POST_SAFETY_SAFE;
+ if (!TypeHelper::toBool($userSettings->listPosts->sketchy))
+ $values[] = Post::POST_SAFETY_SKETCHY;
+ if (!TypeHelper::toBool($userSettings->listPosts->unsafe))
+ $values[] = Post::POST_SAFETY_UNSAFE;
+ if (count($values))
+ {
+ $requirementValue = new RequirementCompositeValue();
+ $requirementValue->setValues($values);
+ $requirement = new Requirement();
+ $requirement->setType(PostFilter::REQUIREMENT_SAFETY);
+ $requirement->setValue($requirementValue);
+ $requirement->setNegated(true);
+ $filter->addRequirement($requirement);
+ }
+ }
- if (!empty($userSettings->hideDownvoted) && !count($filter->getRequirementsByType(PostFilter::REQUIREMENT_USER_SCORE)))
- {
- $requirementValue = new RequirementCompositeValue();
- $requirementValue->setValues([$currentUser->getName(), -1]);
- $requirement = new Requirement();
- $requirement->setType(PostFilter::REQUIREMENT_USER_SCORE);
- $requirement->setValue($requirementValue);
- $requirement->setNegated(true);
- $filter->addRequirement($requirement);
- }
- }
+ if (!empty($userSettings->hideDownvoted) && !count($filter->getRequirementsByType(PostFilter::REQUIREMENT_USER_SCORE)))
+ {
+ $requirementValue = new RequirementCompositeValue();
+ $requirementValue->setValues([$currentUser->getName(), -1]);
+ $requirement = new Requirement();
+ $requirement->setType(PostFilter::REQUIREMENT_USER_SCORE);
+ $requirement->setValue($requirementValue);
+ $requirement->setNegated(true);
+ $filter->addRequirement($requirement);
+ }
+ }
- private function assertNoPostWithThisContentChecksum(Post $parent)
- {
- $checksumToCheck = $parent->getContentChecksum();
- $postWithThisChecksum = $this->postDao->findByContentChecksum($checksumToCheck);
- if ($postWithThisChecksum && $postWithThisChecksum->getId() !== $parent->getId())
- throw new \DomainException('Duplicate post: ' . $postWithThisChecksum->getIdMarkdown());
- }
+ private function assertNoPostWithThisContentChecksum(Post $parent)
+ {
+ $checksumToCheck = $parent->getContentChecksum();
+ $postWithThisChecksum = $this->postDao->findByContentChecksum($checksumToCheck);
+ if ($postWithThisChecksum && $postWithThisChecksum->getId() !== $parent->getId())
+ throw new \DomainException('Duplicate post: ' . $postWithThisChecksum->getIdMarkdown());
+ }
- private function getRandomPostName()
- {
- return sha1(microtime(true) . mt_rand() . uniqid());
- }
+ private function getRandomPostName()
+ {
+ return sha1(microtime(true) . mt_rand() . uniqid());
+ }
- private function getUniqueRandomPostName()
- {
- while (true)
- {
- $name = $this->getRandomPostName();
- if (!$this->postDao->findByName($name))
- return $name;
- }
- }
+ private function getUniqueRandomPostName()
+ {
+ while (true)
+ {
+ $name = $this->getRandomPostName();
+ if (!$this->postDao->findByName($name))
+ return $name;
+ }
+ }
}
diff --git a/src/Services/PostSnapshotProvider.php b/src/Services/PostSnapshotProvider.php
index 6f024bae..7e030a9b 100644
--- a/src/Services/PostSnapshotProvider.php
+++ b/src/Services/PostSnapshotProvider.php
@@ -12,106 +12,106 @@ use Szurubooru\Helpers\EnumHelper;
class PostSnapshotProvider implements ISnapshotProvider
{
- private $globalParamDao;
- private $postNoteDao;
+ private $globalParamDao;
+ private $postNoteDao;
- public function __construct(
- GlobalParamDao $globalParamDao,
- PostNoteDao $postNoteDao)
- {
- $this->globalParamDao = $globalParamDao;
- $this->postNoteDao = $postNoteDao;
- }
+ public function __construct(
+ GlobalParamDao $globalParamDao,
+ PostNoteDao $postNoteDao)
+ {
+ $this->globalParamDao = $globalParamDao;
+ $this->postNoteDao = $postNoteDao;
+ }
- public function getCreationSnapshot(Entity $post)
- {
- $snapshot = $this->getPostSnapshot($post);
- $snapshot->setOperation(Snapshot::OPERATION_CREATION);
- $snapshot->setData($this->getFullData($post));
- return $snapshot;
- }
+ public function getCreationSnapshot(Entity $post)
+ {
+ $snapshot = $this->getPostSnapshot($post);
+ $snapshot->setOperation(Snapshot::OPERATION_CREATION);
+ $snapshot->setData($this->getFullData($post));
+ return $snapshot;
+ }
- public function getChangeSnapshot(Entity $post)
- {
- $snapshot = $this->getPostSnapshot($post);
- $snapshot->setOperation(Snapshot::OPERATION_CHANGE);
- $snapshot->setData($this->getFullData($post));
- return $snapshot;
- }
+ public function getChangeSnapshot(Entity $post)
+ {
+ $snapshot = $this->getPostSnapshot($post);
+ $snapshot->setOperation(Snapshot::OPERATION_CHANGE);
+ $snapshot->setData($this->getFullData($post));
+ return $snapshot;
+ }
- public function getDeleteSnapshot(Entity $post)
- {
- $snapshot = $this->getPostSnapshot($post);
- $snapshot->setData([]);
- $snapshot->setOperation(Snapshot::OPERATION_DELETE);
- return $snapshot;
- }
+ public function getDeleteSnapshot(Entity $post)
+ {
+ $snapshot = $this->getPostSnapshot($post);
+ $snapshot->setData([]);
+ $snapshot->setOperation(Snapshot::OPERATION_DELETE);
+ return $snapshot;
+ }
- private function getPostSnapshot(Post $post)
- {
- $snapshot = new Snapshot();
- $snapshot->setType(Snapshot::TYPE_POST);
- $snapshot->setPrimaryKey($post->getId());
- return $snapshot;
- }
+ private function getPostSnapshot(Post $post)
+ {
+ $snapshot = new Snapshot();
+ $snapshot->setType(Snapshot::TYPE_POST);
+ $snapshot->setPrimaryKey($post->getId());
+ return $snapshot;
+ }
- private function getFullData(Post $post)
- {
- static $featuredPostParam = null;
- if ($featuredPostParam === null)
- $featuredPostParam = $this->globalParamDao->findByKey(GlobalParam::KEY_FEATURED_POST);
- $isFeatured = ($featuredPostParam && intval($featuredPostParam->getValue()) === $post->getId());
+ private function getFullData(Post $post)
+ {
+ static $featuredPostParam = null;
+ if ($featuredPostParam === null)
+ $featuredPostParam = $this->globalParamDao->findByKey(GlobalParam::KEY_FEATURED_POST);
+ $isFeatured = ($featuredPostParam && intval($featuredPostParam->getValue()) === $post->getId());
- $flags = [];
- if ($post->getFlags() & Post::FLAG_LOOP)
- $flags[] = 'loop';
+ $flags = [];
+ if ($post->getFlags() & Post::FLAG_LOOP)
+ $flags[] = 'loop';
- $data =
- [
- 'source' => $post->getSource(),
- 'safety' => EnumHelper::postSafetyToString($post->getSafety()),
- 'contentChecksum' => $post->getContentChecksum(),
- 'featured' => $isFeatured,
+ $data =
+ [
+ 'source' => $post->getSource(),
+ 'safety' => EnumHelper::postSafetyToString($post->getSafety()),
+ 'contentChecksum' => $post->getContentChecksum(),
+ 'featured' => $isFeatured,
- 'notes' => array_values(array_map(function (PostNote $note)
- {
- return [
- 'x' => round(floatval($note->getLeft()), 2),
- 'y' => round(floatval($note->getTop()), 2),
- 'w' => round(floatval($note->getWidth()), 2),
- 'h' => round(floatval($note->getHeight()), 2),
- 'text' => trim($note->getText()),
- ];
- },
- $this->postNoteDao->findByPostId($post->getId()))),
+ 'notes' => array_values(array_map(function (PostNote $note)
+ {
+ return [
+ 'x' => round(floatval($note->getLeft()), 2),
+ 'y' => round(floatval($note->getTop()), 2),
+ 'w' => round(floatval($note->getWidth()), 2),
+ 'h' => round(floatval($note->getHeight()), 2),
+ 'text' => trim($note->getText()),
+ ];
+ },
+ $this->postNoteDao->findByPostId($post->getId()))),
- 'tags' =>
- array_values(array_map(
- function (Tag $tag)
- {
- return $tag->getName();
- },
- $post->getTags())),
+ 'tags' =>
+ array_values(array_map(
+ function (Tag $tag)
+ {
+ return $tag->getName();
+ },
+ $post->getTags())),
- 'relations' =>
- array_values(array_map(
- function (Post $post)
- {
- return $post->getId();
- },
- $post->getRelatedPosts())),
+ 'relations' =>
+ array_values(array_map(
+ function (Post $post)
+ {
+ return $post->getId();
+ },
+ $post->getRelatedPosts())),
- 'flags' => $flags,
- ];
+ 'flags' => $flags,
+ ];
- sort($data['tags']);
- sort($data['relations']);
- usort($data['notes'],
- function ($note1, $note2)
- {
- return $note1['x'] - $note2['x'];
- });
+ sort($data['tags']);
+ sort($data['relations']);
+ usort($data['notes'],
+ function ($note1, $note2)
+ {
+ return $note1['x'] - $note2['x'];
+ });
- return $data;
- }
+ return $data;
+ }
}
diff --git a/src/Services/PostThumbnailService.php b/src/Services/PostThumbnailService.php
index a8174208..4d5514a9 100644
--- a/src/Services/PostThumbnailService.php
+++ b/src/Services/PostThumbnailService.php
@@ -6,23 +6,23 @@ use Szurubooru\Services\ThumbnailService;
class PostThumbnailService
{
- private $thumbnailService;
- private $fileDao;
+ private $thumbnailService;
+ private $fileDao;
- public function __construct(
- PublicFileDao $fileDao,
- ThumbnailService $thumbnailService)
- {
- $this->fileDao = $fileDao;
- $this->thumbnailService = $thumbnailService;
- }
+ public function __construct(
+ PublicFileDao $fileDao,
+ ThumbnailService $thumbnailService)
+ {
+ $this->fileDao = $fileDao;
+ $this->thumbnailService = $thumbnailService;
+ }
- public function generateIfNeeded(Post $post, $width, $height)
- {
- $sourceName = $post->getThumbnailSourceContentPath();
- if (!$this->fileDao->exists($sourceName))
- $sourceName = $post->getContentPath();
+ public function generateIfNeeded(Post $post, $width, $height)
+ {
+ $sourceName = $post->getThumbnailSourceContentPath();
+ if (!$this->fileDao->exists($sourceName))
+ $sourceName = $post->getContentPath();
- return $this->thumbnailService->generateIfNeeded($sourceName, $width, $height);
- }
+ return $this->thumbnailService->generateIfNeeded($sourceName, $width, $height);
+ }
}
diff --git a/src/Services/PrivilegeService.php b/src/Services/PrivilegeService.php
index 744301a0..3927d439 100644
--- a/src/Services/PrivilegeService.php
+++ b/src/Services/PrivilegeService.php
@@ -7,88 +7,88 @@ use Szurubooru\Services\AuthService;
class PrivilegeService
{
- private $authService;
- private $privilegeMap;
+ private $authService;
+ private $privilegeMap;
- public function __construct(
- Config $config,
- AuthService $authService)
- {
- $this->authService = $authService;
+ public function __construct(
+ Config $config,
+ AuthService $authService)
+ {
+ $this->authService = $authService;
- if (isset($config->security->privileges))
- {
- foreach ($config->security->privileges as $privilegeName => $allowedAccessRanks)
- {
- $allowedAccessRanks = array_filter(preg_split('/[;,\s]+/', $allowedAccessRanks));
- foreach ($allowedAccessRanks as $allowedAccessRank)
- {
- if (!isset($this->privilegeMap[$allowedAccessRank]))
- $this->privilegeMap[$allowedAccessRank] = [];
- $this->privilegeMap[$allowedAccessRank][] = $privilegeName;
- }
- }
- }
- }
+ if (isset($config->security->privileges))
+ {
+ foreach ($config->security->privileges as $privilegeName => $allowedAccessRanks)
+ {
+ $allowedAccessRanks = array_filter(preg_split('/[;,\s]+/', $allowedAccessRanks));
+ foreach ($allowedAccessRanks as $allowedAccessRank)
+ {
+ if (!isset($this->privilegeMap[$allowedAccessRank]))
+ $this->privilegeMap[$allowedAccessRank] = [];
+ $this->privilegeMap[$allowedAccessRank][] = $privilegeName;
+ }
+ }
+ }
+ }
- public function getCurrentPrivileges()
- {
- $currentAccessRank = $this->authService->getLoggedInUser()->getAccessRank();
- $currentAccessRankName = EnumHelper::accessRankToString($currentAccessRank);
- if (!isset($this->privilegeMap[$currentAccessRankName]))
- return [];
- return $this->privilegeMap[$currentAccessRankName];
- }
+ public function getCurrentPrivileges()
+ {
+ $currentAccessRank = $this->authService->getLoggedInUser()->getAccessRank();
+ $currentAccessRankName = EnumHelper::accessRankToString($currentAccessRank);
+ if (!isset($this->privilegeMap[$currentAccessRankName]))
+ return [];
+ return $this->privilegeMap[$currentAccessRankName];
+ }
- public function hasPrivilege($privilege)
- {
- return in_array($privilege, $this->getCurrentPrivileges());
- }
+ public function hasPrivilege($privilege)
+ {
+ return in_array($privilege, $this->getCurrentPrivileges());
+ }
- public function assertPrivilege($privilege)
- {
- if (!$this->hasPrivilege($privilege))
- $this->fail($privilege);
- }
+ public function assertPrivilege($privilege)
+ {
+ if (!$this->hasPrivilege($privilege))
+ $this->fail($privilege);
+ }
- public function assertLoggedIn($userIdentifier = null)
- {
- if ($userIdentifier)
- {
- if (!$this->isLoggedIn($userIdentifier))
- $this->fail('not logged in');
- }
- else
- {
- if (!$this->authService->isLoggedIn())
- $this->fail('not logged in');
- }
- }
+ public function assertLoggedIn($userIdentifier = null)
+ {
+ if ($userIdentifier)
+ {
+ if (!$this->isLoggedIn($userIdentifier))
+ $this->fail('not logged in');
+ }
+ else
+ {
+ if (!$this->authService->isLoggedIn())
+ $this->fail('not logged in');
+ }
+ }
- public function isLoggedIn($userIdentifier)
- {
- $loggedInUser = $this->authService->getLoggedInUser();
- if ($userIdentifier instanceof User)
- {
- return $loggedInUser->getId() && ($loggedInUser->getId() === $userIdentifier->getId());
- }
- elseif (is_string($userIdentifier))
- {
- if ($loggedInUser->getEmail())
- {
- if ($loggedInUser->getEmail() === $userIdentifier)
- return true;
- }
- return $loggedInUser->getName() === $userIdentifier;
- }
- else
- {
- throw new \InvalidArgumentException('Invalid user identifier.');
- }
- }
+ public function isLoggedIn($userIdentifier)
+ {
+ $loggedInUser = $this->authService->getLoggedInUser();
+ if ($userIdentifier instanceof User)
+ {
+ return $loggedInUser->getId() && ($loggedInUser->getId() === $userIdentifier->getId());
+ }
+ elseif (is_string($userIdentifier))
+ {
+ if ($loggedInUser->getEmail())
+ {
+ if ($loggedInUser->getEmail() === $userIdentifier)
+ return true;
+ }
+ return $loggedInUser->getName() === $userIdentifier;
+ }
+ else
+ {
+ throw new \InvalidArgumentException('Invalid user identifier.');
+ }
+ }
- private function fail($reason)
- {
- throw new \DomainException('Unprivileged operation' . ($reason ? ' (' . $reason . ')' : ''));
- }
+ private function fail($reason)
+ {
+ throw new \DomainException('Unprivileged operation' . ($reason ? ' (' . $reason . ')' : ''));
+ }
}
diff --git a/src/Services/ScoreService.php b/src/Services/ScoreService.php
index df8ed3ca..1ffe8cd4 100644
--- a/src/Services/ScoreService.php
+++ b/src/Services/ScoreService.php
@@ -11,64 +11,64 @@ use Szurubooru\Services\TimeService;
class ScoreService
{
- private $scoreDao;
- private $favoritesDao;
- private $userDao;
- private $transactionManager;
- private $timeService;
+ private $scoreDao;
+ private $favoritesDao;
+ private $userDao;
+ private $transactionManager;
+ private $timeService;
- public function __construct(
- ScoreDao $scoreDao,
- FavoritesDao $favoritesDao,
- UserDao $userDao,
- TransactionManager $transactionManager,
- TimeService $timeService)
- {
- $this->scoreDao = $scoreDao;
- $this->favoritesDao = $favoritesDao;
- $this->userDao = $userDao;
- $this->transactionManager = $transactionManager;
- $this->timeService = $timeService;
- }
+ public function __construct(
+ ScoreDao $scoreDao,
+ FavoritesDao $favoritesDao,
+ UserDao $userDao,
+ TransactionManager $transactionManager,
+ TimeService $timeService)
+ {
+ $this->scoreDao = $scoreDao;
+ $this->favoritesDao = $favoritesDao;
+ $this->userDao = $userDao;
+ $this->transactionManager = $transactionManager;
+ $this->timeService = $timeService;
+ }
- public function getScoreValue(Entity $entity)
- {
- $transactionFunc = function() use ($entity)
- {
- return $this->scoreDao->getScoreValue($entity);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getScoreValue(Entity $entity)
+ {
+ $transactionFunc = function() use ($entity)
+ {
+ return $this->scoreDao->getScoreValue($entity);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getUserScore(User $user, Entity $entity)
- {
- $transactionFunc = function() use ($user, $entity)
- {
- return $this->scoreDao->getUserScore($user, $entity);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getUserScore(User $user, Entity $entity)
+ {
+ $transactionFunc = function() use ($user, $entity)
+ {
+ return $this->scoreDao->getUserScore($user, $entity);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getUserScoreValue(User $user, Entity $entity)
- {
- $score = $this->getUserScore($user, $entity);
- if (!$score)
- return 0;
- return $score->getScore();
- }
+ public function getUserScoreValue(User $user, Entity $entity)
+ {
+ $score = $this->getUserScore($user, $entity);
+ if (!$score)
+ return 0;
+ return $score->getScore();
+ }
- public function setUserScore(User $user, Entity $entity, $scoreValue)
- {
- if ($scoreValue !== 1 && $scoreValue !== 0 && $scoreValue !== -1)
- throw new \DomainException('Bad score');
+ public function setUserScore(User $user, Entity $entity, $scoreValue)
+ {
+ if ($scoreValue !== 1 && $scoreValue !== 0 && $scoreValue !== -1)
+ throw new \DomainException('Bad score');
- $transactionFunc = function() use ($user, $entity, $scoreValue)
- {
- if (($scoreValue !== 1) && ($entity instanceof Post))
- $this->favoritesDao->delete($user, $entity);
+ $transactionFunc = function() use ($user, $entity, $scoreValue)
+ {
+ if (($scoreValue !== 1) && ($entity instanceof Post))
+ $this->favoritesDao->delete($user, $entity);
- return $this->scoreDao->setUserScore($user, $entity, $scoreValue);
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ return $this->scoreDao->setUserScore($user, $entity, $scoreValue);
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
}
diff --git a/src/Services/TagHistoryService.php b/src/Services/TagHistoryService.php
index 262a80df..8a331649 100644
--- a/src/Services/TagHistoryService.php
+++ b/src/Services/TagHistoryService.php
@@ -11,54 +11,54 @@ use Szurubooru\Services\TagSnapshotProvider;
class TagHistoryService
{
- private $transactionManager;
- private $historyService;
- private $tagSnapshotProvider;
+ private $transactionManager;
+ private $historyService;
+ private $tagSnapshotProvider;
- public function __construct(
- TransactionManager $transactionManager,
- HistoryService $historyService,
- TagSnapshotProvider $tagSnapshotProvider)
- {
- $this->transactionManager = $transactionManager;
- $this->historyService = $historyService;
- $this->tagSnapshotProvider = $tagSnapshotProvider;
- }
+ public function __construct(
+ TransactionManager $transactionManager,
+ HistoryService $historyService,
+ TagSnapshotProvider $tagSnapshotProvider)
+ {
+ $this->transactionManager = $transactionManager;
+ $this->historyService = $historyService;
+ $this->tagSnapshotProvider = $tagSnapshotProvider;
+ }
- public function getTagHistory(Tag $tag)
- {
- $transactionFunc = function() use ($tag)
- {
- $filter = new SnapshotFilter();
+ public function getTagHistory(Tag $tag)
+ {
+ $transactionFunc = function() use ($tag)
+ {
+ $filter = new SnapshotFilter();
- $requirement = new Requirement();
- $requirement->setType(SnapshotFilter::REQUIREMENT_PRIMARY_KEY);
- $requirement->setValue(new RequirementSingleValue($tag->getId()));
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setType(SnapshotFilter::REQUIREMENT_PRIMARY_KEY);
+ $requirement->setValue(new RequirementSingleValue($tag->getId()));
+ $filter->addRequirement($requirement);
- $requirement = new Requirement();
- $requirement->setType(SnapshotFilter::REQUIREMENT_TYPE);
- $requirement->setValue(new RequirementSingleValue(Snapshot::TYPE_TAG));
- $filter->addRequirement($requirement);
+ $requirement = new Requirement();
+ $requirement->setType(SnapshotFilter::REQUIREMENT_TYPE);
+ $requirement->setValue(new RequirementSingleValue(Snapshot::TYPE_TAG));
+ $filter->addRequirement($requirement);
- return $this->historyService->getFiltered($filter)->getEntities();
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ return $this->historyService->getFiltered($filter)->getEntities();
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function saveTagCreation(Tag $tag)
- {
- $this->historyService->saveSnapshot($this->tagSnapshotProvider->getCreationSnapshot($tag));
- }
+ public function saveTagCreation(Tag $tag)
+ {
+ $this->historyService->saveSnapshot($this->tagSnapshotProvider->getCreationSnapshot($tag));
+ }
- public function saveTagChange(Tag $tag)
- {
- $this->historyService->saveSnapshot($this->tagSnapshotProvider->getChangeSnapshot($tag));
- }
+ public function saveTagChange(Tag $tag)
+ {
+ $this->historyService->saveSnapshot($this->tagSnapshotProvider->getChangeSnapshot($tag));
+ }
- public function saveTagDeletion(Tag $tag)
- {
- $this->historyService->saveSnapshot($this->tagSnapshotProvider->getDeleteSnapshot($tag));
- }
+ public function saveTagDeletion(Tag $tag)
+ {
+ $this->historyService->saveSnapshot($this->tagSnapshotProvider->getDeleteSnapshot($tag));
+ }
}
diff --git a/src/Services/TagService.php b/src/Services/TagService.php
index 68251b75..d454c443 100644
--- a/src/Services/TagService.php
+++ b/src/Services/TagService.php
@@ -12,233 +12,233 @@ use Szurubooru\Validator;
class TagService
{
- private $validator;
- private $transactionManager;
- private $postDao;
- private $tagDao;
- private $fileDao;
- private $timeService;
- private $postHistoryService;
- private $tagHistoryService;
+ private $validator;
+ private $transactionManager;
+ private $postDao;
+ private $tagDao;
+ private $fileDao;
+ private $timeService;
+ private $postHistoryService;
+ private $tagHistoryService;
- public function __construct(
- Validator $validator,
- TransactionManager $transactionManager,
- PostDao $postDao,
- TagDao $tagDao,
- PublicFileDao $fileDao,
- PostHistoryService $postHistoryService,
- TagHistoryService $tagHistoryService,
- TimeService $timeService)
- {
- $this->validator = $validator;
- $this->transactionManager = $transactionManager;
- $this->postDao = $postDao;
- $this->tagDao = $tagDao;
- $this->fileDao = $fileDao;
- $this->postHistoryService = $postHistoryService;
- $this->tagHistoryService = $tagHistoryService;
- $this->timeService = $timeService;
- }
+ public function __construct(
+ Validator $validator,
+ TransactionManager $transactionManager,
+ PostDao $postDao,
+ TagDao $tagDao,
+ PublicFileDao $fileDao,
+ PostHistoryService $postHistoryService,
+ TagHistoryService $tagHistoryService,
+ TimeService $timeService)
+ {
+ $this->validator = $validator;
+ $this->transactionManager = $transactionManager;
+ $this->postDao = $postDao;
+ $this->tagDao = $tagDao;
+ $this->fileDao = $fileDao;
+ $this->postHistoryService = $postHistoryService;
+ $this->tagHistoryService = $tagHistoryService;
+ $this->timeService = $timeService;
+ }
- public function getByName($tagName)
- {
- $transactionFunc = function() use ($tagName)
- {
- $tag = $this->tagDao->findByName($tagName);
- if (!$tag)
- throw new \InvalidArgumentException('Tag with name "' . $tagName . '" was not found.');
- return $tag;
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getByName($tagName)
+ {
+ $transactionFunc = function() use ($tagName)
+ {
+ $tag = $this->tagDao->findByName($tagName);
+ if (!$tag)
+ throw new \InvalidArgumentException('Tag with name "' . $tagName . '" was not found.');
+ return $tag;
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getFiltered(TagFilter $filter)
- {
- $transactionFunc = function() use ($filter)
- {
- return $this->tagDao->findFiltered($filter);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getFiltered(TagFilter $filter)
+ {
+ $transactionFunc = function() use ($filter)
+ {
+ return $this->tagDao->findFiltered($filter);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function getSiblings($tagName)
- {
- $transactionFunc = function() use ($tagName)
- {
- return $this->tagDao->findSiblings($tagName);
- };
- return $this->transactionManager->rollback($transactionFunc);
- }
+ public function getSiblings($tagName)
+ {
+ $transactionFunc = function() use ($tagName)
+ {
+ return $this->tagDao->findSiblings($tagName);
+ };
+ return $this->transactionManager->rollback($transactionFunc);
+ }
- public function exportJson()
- {
- $exported = $this->tagDao->export();
- $json = json_encode($exported);
- $this->fileDao->save('tags.json', $json);
- }
+ public function exportJson()
+ {
+ $exported = $this->tagDao->export();
+ $json = json_encode($exported);
+ $this->fileDao->save('tags.json', $json);
+ }
- public function createTags(array $tags)
- {
- $transactionFunc = function() use ($tags)
- {
- $tagNameGetter = function($tag)
- {
- return strtolower(is_string($tag) ? $tag : $tag->getName());
- };
+ public function createTags(array $tags)
+ {
+ $transactionFunc = function() use ($tags)
+ {
+ $tagNameGetter = function($tag)
+ {
+ return strtolower(is_string($tag) ? $tag : $tag->getName());
+ };
- $tagsNotToCreate = [];
- $tagNames = array_map($tagNameGetter, $tags);
- $tagNames = array_filter(array_unique($tagNames));
- foreach ($this->tagDao->findByNames($tagNames) as $tag)
- $tagsNotToCreate[$tagNameGetter($tag)] = $tag;
+ $tagsNotToCreate = [];
+ $tagNames = array_map($tagNameGetter, $tags);
+ $tagNames = array_filter(array_unique($tagNames));
+ foreach ($this->tagDao->findByNames($tagNames) as $tag)
+ $tagsNotToCreate[$tagNameGetter($tag)] = $tag;
- $tagsToCreate = [];
- foreach ($tags as $key => $tag)
- {
- if (isset($tagsNotToCreate[$tagNameGetter($tag)]))
- continue;
+ $tagsToCreate = [];
+ foreach ($tags as $key => $tag)
+ {
+ if (isset($tagsNotToCreate[$tagNameGetter($tag)]))
+ continue;
- if (is_string($tag))
- {
- $tagName = $tag;
- $tag = new Tag();
- $tag->setName($tagName);
- }
- $tag->setCreationTime($this->timeService->getCurrentTime());
- $tagsToCreate[$tagNameGetter($tag)] = $tag;
- }
+ if (is_string($tag))
+ {
+ $tagName = $tag;
+ $tag = new Tag();
+ $tag->setName($tagName);
+ }
+ $tag->setCreationTime($this->timeService->getCurrentTime());
+ $tagsToCreate[$tagNameGetter($tag)] = $tag;
+ }
- $createdTags = [];
- foreach ($this->tagDao->batchSave($tagsToCreate) as $tag)
- {
- $createdTags[$tagNameGetter($tag)] = $tag;
- $this->tagHistoryService->saveTagCreation($tag);
- }
+ $createdTags = [];
+ foreach ($this->tagDao->batchSave($tagsToCreate) as $tag)
+ {
+ $createdTags[$tagNameGetter($tag)] = $tag;
+ $this->tagHistoryService->saveTagCreation($tag);
+ }
- $result = [];
- foreach ($tags as $key => $tag)
- {
- $result[$key] =
- isset($tagsToCreate[$tagNameGetter($tag)])
- ? $createdTags[$tagNameGetter($tag)]
- : $tagsNotToCreate[$tagNameGetter($tag)];
- }
- return $result;
- };
- return $this->transactionManager->commit($transactionFunc);
- }
+ $result = [];
+ foreach ($tags as $key => $tag)
+ {
+ $result[$key] =
+ isset($tagsToCreate[$tagNameGetter($tag)])
+ ? $createdTags[$tagNameGetter($tag)]
+ : $tagsNotToCreate[$tagNameGetter($tag)];
+ }
+ return $result;
+ };
+ return $this->transactionManager->commit($transactionFunc);
+ }
- public function updateTag(Tag $tag, TagEditFormData $formData)
- {
- $oldName = $tag->getName();
+ public function updateTag(Tag $tag, TagEditFormData $formData)
+ {
+ $oldName = $tag->getName();
- $transactionFunc = function() use ($tag, $formData)
- {
- $this->validator->validate($formData);
+ $transactionFunc = function() use ($tag, $formData)
+ {
+ $this->validator->validate($formData);
- if ($formData->name !== null)
- $this->updateTagName($tag, $formData->name);
+ if ($formData->name !== null)
+ $this->updateTagName($tag, $formData->name);
- if ($formData->category !== null)
- $this->updateTagCategory($tag, $formData->category);
+ if ($formData->category !== null)
+ $this->updateTagCategory($tag, $formData->category);
- if ($formData->banned !== $tag->isBanned())
- $tag->setBanned(boolval($formData->banned));
+ if ($formData->banned !== $tag->isBanned())
+ $tag->setBanned(boolval($formData->banned));
- if ($formData->implications !== null)
- $this->updateImplications($tag, $formData->implications);
+ if ($formData->implications !== null)
+ $this->updateImplications($tag, $formData->implications);
- if ($formData->suggestions !== null)
- $this->updateSuggestions($tag, $formData->suggestions);
+ if ($formData->suggestions !== null)
+ $this->updateSuggestions($tag, $formData->suggestions);
- $this->tagHistoryService->saveTagChange($tag);
- return $this->tagDao->save($tag);
- };
- $ret = $this->transactionManager->commit($transactionFunc);
+ $this->tagHistoryService->saveTagChange($tag);
+ return $this->tagDao->save($tag);
+ };
+ $ret = $this->transactionManager->commit($transactionFunc);
- if ($oldName !== $tag->getName())
- {
- $transactionFunc = function() use ($tag)
- {
- $posts = $this->postDao->findByTagName($tag->getName());
- foreach ($posts as $post)
- $this->postHistoryService->savePostChange($post);
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ if ($oldName !== $tag->getName())
+ {
+ $transactionFunc = function() use ($tag)
+ {
+ $posts = $this->postDao->findByTagName($tag->getName());
+ foreach ($posts as $post)
+ $this->postHistoryService->savePostChange($post);
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
- $this->exportJson();
- return $ret;
- }
+ $this->exportJson();
+ return $ret;
+ }
- public function deleteTag(Tag $tag)
- {
- if ($tag->getUsages() !== 0)
- throw new \DomainException('Only tags with no usages can be deleted.');
+ public function deleteTag(Tag $tag)
+ {
+ if ($tag->getUsages() !== 0)
+ throw new \DomainException('Only tags with no usages can be deleted.');
- $transactionFunc = function() use ($tag)
- {
- $this->tagDao->deleteById($tag->getId());
- $this->tagHistoryService->saveTagDeletion($tag);
- };
+ $transactionFunc = function() use ($tag)
+ {
+ $this->tagDao->deleteById($tag->getId());
+ $this->tagHistoryService->saveTagDeletion($tag);
+ };
- $this->transactionManager->commit($transactionFunc);
- }
+ $this->transactionManager->commit($transactionFunc);
+ }
- public function mergeTag(Tag $sourceTag, Tag $targetTag)
- {
- $transactionFunc = function() use ($sourceTag, $targetTag)
- {
- $posts = $this->postDao->findByTagName($sourceTag->getName());
- foreach ($posts as $post)
- {
- $newTags = $post->getTags();
- $newTags[] = $targetTag;
+ public function mergeTag(Tag $sourceTag, Tag $targetTag)
+ {
+ $transactionFunc = function() use ($sourceTag, $targetTag)
+ {
+ $posts = $this->postDao->findByTagName($sourceTag->getName());
+ foreach ($posts as $post)
+ {
+ $newTags = $post->getTags();
+ $newTags[] = $targetTag;
- $newTags = array_filter(
- $newTags,
- function(Tag $tag) use ($sourceTag)
- {
- return $tag->getId() !== $sourceTag->getId();
- });
+ $newTags = array_filter(
+ $newTags,
+ function(Tag $tag) use ($sourceTag)
+ {
+ return $tag->getId() !== $sourceTag->getId();
+ });
- $post->setTags($newTags);
- $this->postDao->save($post);
- $this->postHistoryService->savePostChange($post);
- }
+ $post->setTags($newTags);
+ $this->postDao->save($post);
+ $this->postHistoryService->savePostChange($post);
+ }
- $this->tagHistoryService->saveTagDeletion($sourceTag);
- $this->tagDao->deleteById($sourceTag->getId());
- };
- $this->transactionManager->commit($transactionFunc);
- }
+ $this->tagHistoryService->saveTagDeletion($sourceTag);
+ $this->tagDao->deleteById($sourceTag->getId());
+ };
+ $this->transactionManager->commit($transactionFunc);
+ }
- private function updateTagName(Tag $tag, $newName)
- {
- $otherTag = $this->tagDao->findByName($newName);
- if ($otherTag && $otherTag->getId() !== $tag->getId())
- throw new \DomainException('Tag with this name already exists.');
- $tag->setName($newName);
- }
+ private function updateTagName(Tag $tag, $newName)
+ {
+ $otherTag = $this->tagDao->findByName($newName);
+ if ($otherTag && $otherTag->getId() !== $tag->getId())
+ throw new \DomainException('Tag with this name already exists.');
+ $tag->setName($newName);
+ }
- private function updateTagCategory(Tag $tag, $newCategory)
- {
- if ($newCategory === 'default')
- $tag->setCategory($newCategory);
- else
- $tag->setCategory($newCategory);
- }
+ private function updateTagCategory(Tag $tag, $newCategory)
+ {
+ if ($newCategory === 'default')
+ $tag->setCategory($newCategory);
+ else
+ $tag->setCategory($newCategory);
+ }
- private function updateImplications(Tag $tag, array $relatedNames)
- {
- $relatedNames = array_udiff($relatedNames, [$tag->getName()], 'strcasecmp');
- $tag->setImpliedTags($this->createTags($relatedNames));
- }
+ private function updateImplications(Tag $tag, array $relatedNames)
+ {
+ $relatedNames = array_udiff($relatedNames, [$tag->getName()], 'strcasecmp');
+ $tag->setImpliedTags($this->createTags($relatedNames));
+ }
- private function updateSuggestions(Tag $tag, array $relatedNames)
- {
- $relatedNames = array_udiff($relatedNames, [$tag->getName()], 'strcasecmp');
- $tag->setSuggestedTags($this->createTags($relatedNames));
- }
+ private function updateSuggestions(Tag $tag, array $relatedNames)
+ {
+ $relatedNames = array_udiff($relatedNames, [$tag->getName()], 'strcasecmp');
+ $tag->setSuggestedTags($this->createTags($relatedNames));
+ }
}
diff --git a/src/Services/TagSnapshotProvider.php b/src/Services/TagSnapshotProvider.php
index f33cca92..09871fb5 100644
--- a/src/Services/TagSnapshotProvider.php
+++ b/src/Services/TagSnapshotProvider.php
@@ -6,59 +6,59 @@ use Szurubooru\Entities\Tag;
class TagSnapshotProvider implements ISnapshotProvider
{
- public function getCreationSnapshot(Entity $tag)
- {
- $snapshot = $this->getTagSnapshot($tag);
- $snapshot->setOperation(Snapshot::OPERATION_CREATION);
- $snapshot->setData($this->getFullData($tag));
- return $snapshot;
- }
+ public function getCreationSnapshot(Entity $tag)
+ {
+ $snapshot = $this->getTagSnapshot($tag);
+ $snapshot->setOperation(Snapshot::OPERATION_CREATION);
+ $snapshot->setData($this->getFullData($tag));
+ return $snapshot;
+ }
- public function getChangeSnapshot(Entity $tag)
- {
- $snapshot = $this->getTagSnapshot($tag);
- $snapshot->setOperation(Snapshot::OPERATION_CHANGE);
- $snapshot->setData($this->getFullData($tag));
- return $snapshot;
- }
+ public function getChangeSnapshot(Entity $tag)
+ {
+ $snapshot = $this->getTagSnapshot($tag);
+ $snapshot->setOperation(Snapshot::OPERATION_CHANGE);
+ $snapshot->setData($this->getFullData($tag));
+ return $snapshot;
+ }
- public function getDeleteSnapshot(Entity $tag)
- {
- $snapshot = $this->getTagSnapshot($tag);
- $snapshot->setData(['name' => $tag->getName()]);
- $snapshot->setOperation(Snapshot::OPERATION_DELETE);
- return $snapshot;
- }
+ public function getDeleteSnapshot(Entity $tag)
+ {
+ $snapshot = $this->getTagSnapshot($tag);
+ $snapshot->setData(['name' => $tag->getName()]);
+ $snapshot->setOperation(Snapshot::OPERATION_DELETE);
+ return $snapshot;
+ }
- private function getTagSnapshot(Tag $tag)
- {
- $snapshot = new Snapshot();
- $snapshot->setType(Snapshot::TYPE_TAG);
- $snapshot->setPrimaryKey($tag->getId());
- return $snapshot;
- }
+ private function getTagSnapshot(Tag $tag)
+ {
+ $snapshot = new Snapshot();
+ $snapshot->setType(Snapshot::TYPE_TAG);
+ $snapshot->setPrimaryKey($tag->getId());
+ return $snapshot;
+ }
- private function getFullData(Tag $tag)
- {
- $data =
- [
- 'name' => $tag->getName(),
- 'banned' => $tag->isBanned(),
- 'category' => $tag->getCategory(),
+ private function getFullData(Tag $tag)
+ {
+ $data =
+ [
+ 'name' => $tag->getName(),
+ 'banned' => $tag->isBanned(),
+ 'category' => $tag->getCategory(),
- 'implications' => array_values(array_map(function (Tag $impliedTag)
- {
- return $impliedTag->getName();
- }, $tag->getImpliedTags())),
+ 'implications' => array_values(array_map(function (Tag $impliedTag)
+ {
+ return $impliedTag->getName();
+ }, $tag->getImpliedTags())),
- 'suggestions' => array_values(array_map(function (Tag $suggestedTag)
- {
- return $suggestedTag->getName();
- }, $tag->getSuggestedTags())),
- ];
+ 'suggestions' => array_values(array_map(function (Tag $suggestedTag)
+ {
+ return $suggestedTag->getName();
+ }, $tag->getSuggestedTags())),
+ ];
- sort($data['implications']);
- sort($data['suggestions']);
- return $data;
- }
+ sort($data['implications']);
+ sort($data['suggestions']);
+ return $data;
+ }
}
diff --git a/src/Services/ThumbnailGenerator.php b/src/Services/ThumbnailGenerator.php
index f948a11e..37568458 100644
--- a/src/Services/ThumbnailGenerator.php
+++ b/src/Services/ThumbnailGenerator.php
@@ -4,76 +4,76 @@ use Szurubooru\Services\ImageManipulation\ImageManipulator;
class ThumbnailGenerator
{
- const CROP_OUTSIDE = 0;
- const CROP_INSIDE = 1;
+ const CROP_OUTSIDE = 0;
+ const CROP_INSIDE = 1;
- private $imageManipulator;
- private $imageConverter;
+ private $imageManipulator;
+ private $imageConverter;
- public function __construct(ImageManipulator $imageManipulator, ImageConverter $imageConverter)
- {
- $this->imageManipulator = $imageManipulator;
- $this->imageConverter = $imageConverter;
- }
+ public function __construct(ImageManipulator $imageManipulator, ImageConverter $imageConverter)
+ {
+ $this->imageManipulator = $imageManipulator;
+ $this->imageConverter = $imageConverter;
+ }
- public function generate($source, $width, $height, $cropStyle, $format)
- {
- $image = $this->imageConverter->createImageFromBuffer($source);
- if (!$image)
- throw new \Exception('Error while loading supplied image');
+ public function generate($source, $width, $height, $cropStyle, $format)
+ {
+ $image = $this->imageConverter->createImageFromBuffer($source);
+ if (!$image)
+ throw new \Exception('Error while loading supplied image');
- $srcWidth = $this->imageManipulator->getImageWidth($image);
- $srcHeight = $this->imageManipulator->getImageHeight($image);
+ $srcWidth = $this->imageManipulator->getImageWidth($image);
+ $srcHeight = $this->imageManipulator->getImageHeight($image);
- switch ($cropStyle)
- {
- case ThumbnailGenerator::CROP_OUTSIDE:
- $this->cropOutside($image, $srcWidth, $srcHeight, $width, $height);
- break;
+ switch ($cropStyle)
+ {
+ case ThumbnailGenerator::CROP_OUTSIDE:
+ $this->cropOutside($image, $srcWidth, $srcHeight, $width, $height);
+ break;
- case ThumbnailGenerator::CROP_INSIDE:
- $this->cropInside($image, $srcWidth, $srcHeight, $width, $height);
- break;
+ case ThumbnailGenerator::CROP_INSIDE:
+ $this->cropInside($image, $srcWidth, $srcHeight, $width, $height);
+ break;
- default:
- throw new \InvalidArgumentException('Unknown thumbnail crop style');
- }
+ default:
+ throw new \InvalidArgumentException('Unknown thumbnail crop style');
+ }
- return $this->imageManipulator->saveToBuffer($image, $format);
- }
+ return $this->imageManipulator->saveToBuffer($image, $format);
+ }
- private function cropOutside(&$image, $srcWidth, $srcHeight, $dstWidth, $dstHeight)
- {
- if (($dstHeight / $dstWidth) > ($srcHeight / $srcWidth))
- {
- $cropHeight = $dstHeight;
- $cropWidth = $dstHeight * $srcWidth / $srcHeight;
- }
- else
- {
- $cropWidth = $dstWidth;
- $cropHeight = $dstWidth * $srcHeight / $srcWidth;
- }
- $cropX = ($cropWidth - $dstWidth) >> 1;
- $cropY = ($cropHeight - $dstHeight) >> 1;
+ private function cropOutside(&$image, $srcWidth, $srcHeight, $dstWidth, $dstHeight)
+ {
+ if (($dstHeight / $dstWidth) > ($srcHeight / $srcWidth))
+ {
+ $cropHeight = $dstHeight;
+ $cropWidth = $dstHeight * $srcWidth / $srcHeight;
+ }
+ else
+ {
+ $cropWidth = $dstWidth;
+ $cropHeight = $dstWidth * $srcHeight / $srcWidth;
+ }
+ $cropX = ($cropWidth - $dstWidth) >> 1;
+ $cropY = ($cropHeight - $dstHeight) >> 1;
- $this->imageManipulator->resizeImage($image, $cropWidth, $cropHeight);
- $this->imageManipulator->cropImage($image, $dstWidth, $dstHeight, $cropX, $cropY);
- }
+ $this->imageManipulator->resizeImage($image, $cropWidth, $cropHeight);
+ $this->imageManipulator->cropImage($image, $dstWidth, $dstHeight, $cropX, $cropY);
+ }
- private function cropInside(&$image, $srcWidth, $srcHeight, $dstWidth, $dstHeight)
- {
- if (($dstHeight / $dstWidth) < ($srcHeight / $srcWidth))
- {
- $cropHeight = $dstHeight;
- $cropWidth = $dstHeight * $srcWidth / $srcHeight;
- }
- else
- {
- $cropWidth = $dstWidth;
- $cropHeight = $dstWidth * $srcHeight / $srcWidth;
- }
+ private function cropInside(&$image, $srcWidth, $srcHeight, $dstWidth, $dstHeight)
+ {
+ if (($dstHeight / $dstWidth) < ($srcHeight / $srcWidth))
+ {
+ $cropHeight = $dstHeight;
+ $cropWidth = $dstHeight * $srcWidth / $srcHeight;
+ }
+ else
+ {
+ $cropWidth = $dstWidth;
+ $cropHeight = $dstWidth * $srcHeight / $srcWidth;
+ }
- $this->imageManipulator->resizeImage($image, $cropWidth, $cropHeight);
- }
+ $this->imageManipulator->resizeImage($image, $cropWidth, $cropHeight);
+ }
}
diff --git a/src/Services/ThumbnailService.php b/src/Services/ThumbnailService.php
index ba6d422d..f9d9ea9a 100644
--- a/src/Services/ThumbnailService.php
+++ b/src/Services/ThumbnailService.php
@@ -8,131 +8,131 @@ use Szurubooru\Services\ThumbnailGenerator;
class ThumbnailService
{
- const PROGRAM_NAME_JPEGOPTIM = 'jpegoptim';
- const PROGRAM_NAME_OPTIPNG = 'optipng';
+ const PROGRAM_NAME_JPEGOPTIM = 'jpegoptim';
+ const PROGRAM_NAME_OPTIPNG = 'optipng';
- private $config;
- private $fileDao;
- private $thumbnailGenerator;
+ private $config;
+ private $fileDao;
+ private $thumbnailGenerator;
- public function __construct(
- Config $config,
- PublicFileDao $fileDao,
- ThumbnailGenerator $thumbnailGenerator)
- {
- $this->config = $config;
- $this->fileDao = $fileDao;
- $this->thumbnailGenerator = $thumbnailGenerator;
- }
+ public function __construct(
+ Config $config,
+ PublicFileDao $fileDao,
+ ThumbnailGenerator $thumbnailGenerator)
+ {
+ $this->config = $config;
+ $this->fileDao = $fileDao;
+ $this->thumbnailGenerator = $thumbnailGenerator;
+ }
- public function deleteUsedThumbnails($sourceName)
- {
- foreach ($this->getUsedThumbnailSizes() as $size)
- {
- list ($width, $height) = $size;
- $target = $this->getTargetName($sourceName, $width, $height);
- $this->fileDao->delete($target);
- }
- }
+ public function deleteUsedThumbnails($sourceName)
+ {
+ foreach ($this->getUsedThumbnailSizes() as $size)
+ {
+ list ($width, $height) = $size;
+ $target = $this->getTargetName($sourceName, $width, $height);
+ $this->fileDao->delete($target);
+ }
+ }
- public function generateIfNeeded($sourceName, $width, $height)
- {
- $targetName = $this->getTargetName($sourceName, $width, $height);
+ public function generateIfNeeded($sourceName, $width, $height)
+ {
+ $targetName = $this->getTargetName($sourceName, $width, $height);
- if (!$this->fileDao->exists($targetName))
- return $this->generate($sourceName, $width, $height);
+ if (!$this->fileDao->exists($targetName))
+ return $this->generate($sourceName, $width, $height);
- return $targetName;
- }
+ return $targetName;
+ }
- public function generate($sourceName, $width, $height)
- {
- switch ($this->config->misc->thumbnailCropStyle)
- {
- case 'outside':
- $cropStyle = ThumbnailGenerator::CROP_OUTSIDE;
- break;
+ public function generate($sourceName, $width, $height)
+ {
+ switch ($this->config->misc->thumbnailCropStyle)
+ {
+ case 'outside':
+ $cropStyle = ThumbnailGenerator::CROP_OUTSIDE;
+ break;
- case 'inside':
- $cropStyle = humbnailGenerator::CROP_INSIDE;
- break;
+ case 'inside':
+ $cropStyle = humbnailGenerator::CROP_INSIDE;
+ break;
- default:
- throw new \InvalidArgumentException('Invalid thumbnail crop style');
- }
+ default:
+ throw new \InvalidArgumentException('Invalid thumbnail crop style');
+ }
- $source = $this->fileDao->load($sourceName);
- if ($source)
- {
- $format = $this->getFormat();
- $thumbnailContent = $this->thumbnailGenerator->generate($source, $width, $height, $cropStyle, $format);
- if ($thumbnailContent)
- {
- $targetName = $this->getTargetName($sourceName, $width, $height);
- $this->fileDao->save($targetName, $thumbnailContent);
- $this->optimize($targetName, $format);
- return $targetName;
- }
- }
+ $source = $this->fileDao->load($sourceName);
+ if ($source)
+ {
+ $format = $this->getFormat();
+ $thumbnailContent = $this->thumbnailGenerator->generate($source, $width, $height, $cropStyle, $format);
+ if ($thumbnailContent)
+ {
+ $targetName = $this->getTargetName($sourceName, $width, $height);
+ $this->fileDao->save($targetName, $thumbnailContent);
+ $this->optimize($targetName, $format);
+ return $targetName;
+ }
+ }
- return $this->getBlankThumbnailName();
- }
+ return $this->getBlankThumbnailName();
+ }
- public function getUsedThumbnailSizes()
- {
- foreach (glob($this->fileDao->getFullPath('thumbnails') . DIRECTORY_SEPARATOR . '*x*') as $fn)
- {
- if (!is_dir($fn))
- continue;
+ public function getUsedThumbnailSizes()
+ {
+ foreach (glob($this->fileDao->getFullPath('thumbnails') . DIRECTORY_SEPARATOR . '*x*') as $fn)
+ {
+ if (!is_dir($fn))
+ continue;
- preg_match('/(?P