diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 000000000000..ffab5d513e0d --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,100 @@ +notPath('bootstrap/cache') + ->notPath('storage') + ->notPath('vendor') + ->in(__DIR__) + ->name('*.php') + ->notName('*.blade.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return PhpCsFixer\Config::create() + ->setRules(array( + '@PSR2' => true, + 'binary_operator_spaces' => true, + 'blank_line_after_namespace' => true, + 'blank_line_after_opening_tag' => true, + 'blank_line_before_return' => true, + 'braces' => true, + 'cast_spaces' => true, + 'class_definition' => true, + 'elseif' => true, + 'encoding' => true, + 'full_opening_tag' => true, + 'function_declaration' => true, + 'function_typehint_space' => true, + 'hash_to_slash_comment' => true, + 'heredoc_to_nowdoc' => true, + 'include' => true, + 'lowercase_cast' => true, + 'lowercase_constants' => true, + 'lowercase_keywords' => true, + 'method_argument_space' => true, + 'method_separation' => true, + 'native_function_casing' => true, + 'new_with_braces' => true, + 'no_alias_functions' => true, + 'no_blank_lines_after_class_opening' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_closing_tag' => true, + 'no_empty_phpdoc' => true, + 'no_extra_consecutive_blank_lines' => true, + 'no_leading_import_slash' => true, + 'no_leading_namespace_whitespace' => true, + 'no_multiline_whitespace_around_double_arrow' => true, + 'no_multiline_whitespace_before_semicolons' => true, + 'no_short_bool_cast' => true, + 'no_singleline_whitespace_before_semicolons' => true, + 'no_spaces_after_function_name' => true, + 'no_spaces_inside_parenthesis' => true, + 'no_trailing_comma_in_list_call' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_trailing_whitespace' => true, + 'no_trailing_whitespace_in_comment' => true, + 'no_unneeded_control_parentheses' => true, + 'no_unreachable_default_argument_value' => true, + 'no_unused_imports' => true, + 'no_useless_return' => true, + 'no_whitespace_before_comma_in_array' => true, + 'not_operator_with_successor_space' => true, + 'object_operator_without_whitespace' => true, + 'ordered_imports' => true, + 'phpdoc_align' => true, + 'phpdoc_indent' => true, + 'phpdoc_inline_tag' => true, + 'phpdoc_no_access' => true, + 'phpdoc_no_package' => true, + 'phpdoc_order' => true, + 'phpdoc_scalar' => true, + 'phpdoc_separation' => true, + 'phpdoc_summary' => true, + 'phpdoc_to_comment' => true, + 'phpdoc_trim' => true, + 'phpdoc_types' => true, + 'phpdoc_var_without_name' => true, + //'psr4' => true, + 'self_accessor' => true, + 'short_scalar_cast' => true, + //'simplified_null_return' => true, + 'single_blank_line_at_eof' => true, + 'single_blank_line_before_namespace' => true, + 'single_import_per_statement' => true, + 'single_line_after_imports' => true, + 'single_quote' => true, + 'space_after_semicolon' => true, + 'standardize_not_equals' => true, + 'switch_case_semicolon_to_colon' => true, + 'switch_case_space' => true, + 'ternary_operator_spaces' => true, + 'trailing_comma_in_multiline_array' => true, + 'trim_array_spaces' => true, + 'unary_operator_spaces' => true, + 'visibility_required' => true, + 'whitespace_after_comma_in_array' => true, + //'strict_param' => true, + 'array_syntax' => array('syntax' => 'short'), + )) + ->setFinder($finder) +; diff --git a/app/Commands/Command.php b/app/Commands/Command.php index fa514df086de..3b33ca89d1b8 100644 --- a/app/Commands/Command.php +++ b/app/Commands/Command.php @@ -1,4 +1,6 @@ -logMessage(date('Y-m-d') . ' Running CheckData...'); - if (!$this->option('client_id')) { + if (! $this->option('client_id')) { $this->checkPaidToDate(); $this->checkBlankInvoiceHistory(); } $this->checkBalances(); - if (!$this->option('client_id')) { + if (! $this->option('client_id')) { $this->checkAccountData(); } @@ -115,33 +115,33 @@ class CheckData extends Command ENTITY_CONTACT, ENTITY_PAYMENT, ENTITY_INVITATION, - ENTITY_USER + ENTITY_USER, ], 'invoices' => [ ENTITY_CLIENT, - ENTITY_USER + ENTITY_USER, ], 'payments' => [ ENTITY_INVOICE, ENTITY_CLIENT, ENTITY_USER, ENTITY_INVITATION, - ENTITY_CONTACT + ENTITY_CONTACT, ], 'tasks' => [ ENTITY_INVOICE, ENTITY_CLIENT, - ENTITY_USER + ENTITY_USER, ], 'credits' => [ ENTITY_CLIENT, - ENTITY_USER + ENTITY_USER, ], 'expenses' => [ ENTITY_CLIENT, ENTITY_VENDOR, ENTITY_INVOICE, - ENTITY_USER + ENTITY_USER, ], 'products' => [ ENTITY_USER, @@ -152,7 +152,7 @@ class CheckData extends Command 'projects' => [ ENTITY_USER, ENTITY_CLIENT, - ] + ], ]; foreach ($tables as $table => $entityTypes) { @@ -259,7 +259,7 @@ class CheckData extends Command ->first(['invoices.amount', 'invoices.is_recurring', 'invoices.invoice_type_id', 'invoices.deleted_at', 'invoices.id', 'invoices.is_deleted']); // Check if this invoice was once set as recurring invoice - if ($invoice && !$invoice->is_recurring && DB::table('invoices') + if ($invoice && ! $invoice->is_recurring && DB::table('invoices') ->where('recurring_invoice_id', '=', $activity->invoice_id) ->first(['invoices.id'])) { $invoice->is_recurring = 1; @@ -273,7 +273,6 @@ class CheckData extends Command } } - if ($activity->activity_type_id == ACTIVITY_TYPE_CREATE_INVOICE || $activity->activity_type_id == ACTIVITY_TYPE_CREATE_QUOTE) { @@ -294,12 +293,12 @@ class CheckData extends Command // **Fix for ninja invoices which didn't have the invoice_type_id value set if ($noAdjustment && $client->account_id == 20432) { - $this->logMessage("No adjustment for ninja invoice"); + $this->logMessage('No adjustment for ninja invoice'); $foundProblem = true; $clientFix += $invoice->amount; $activityFix = $invoice->amount; // **Fix for allowing converting a recurring invoice to a normal one without updating the balance** - } elseif ($noAdjustment && $invoice->invoice_type_id == INVOICE_TYPE_STANDARD && !$invoice->is_recurring) { + } elseif ($noAdjustment && $invoice->invoice_type_id == INVOICE_TYPE_STANDARD && ! $invoice->is_recurring) { $this->logMessage("No adjustment for new invoice:{$activity->invoice_id} amount:{$invoice->amount} invoiceTypeId:{$invoice->invoice_type_id} isRecurring:{$invoice->is_recurring}"); $foundProblem = true; $clientFix += $invoice->amount; @@ -323,7 +322,7 @@ class CheckData extends Command } } elseif ($activity->activity_type_id == ACTIVITY_TYPE_ARCHIVE_INVOICE) { // **Fix for updating balance when archiving an invoice** - if ($activity->adjustment != 0 && !$invoice->is_recurring) { + if ($activity->adjustment != 0 && ! $invoice->is_recurring) { $this->logMessage("Incorrect adjustment for archiving invoice adjustment:{$activity->adjustment}"); $foundProblem = true; $activityFix = 0; @@ -362,7 +361,7 @@ class CheckData extends Command if ($activityFix !== false || $clientFix !== false) { $data = [ - 'balance' => $activity->balance + $clientFix + 'balance' => $activity->balance + $clientFix, ]; if ($activityFix !== false) { @@ -385,8 +384,8 @@ class CheckData extends Command $this->logMessage("** Creating 'recovered update' activity **"); if ($this->option('fix') == 'true') { DB::table('activities')->insert([ - 'created_at' => new Carbon, - 'updated_at' => new Carbon, + 'created_at' => new Carbon(), + 'updated_at' => new Carbon(), 'account_id' => $client->account_id, 'client_id' => $client->id, 'adjustment' => $client->actual_balance - $activity->balance, diff --git a/app/Console/Commands/CreateTestData.php b/app/Console/Commands/CreateTestData.php index 244f0b93fbd7..7e339643e182 100644 --- a/app/Console/Commands/CreateTestData.php +++ b/app/Console/Commands/CreateTestData.php @@ -1,17 +1,19 @@ -count; $i++) { + for ($i = 0; $i < $this->count; $i++) { $data = [ 'name' => $this->faker->name, 'address1' => $this->faker->streetAddress, @@ -91,7 +94,7 @@ class CreateTestData extends Command 'last_name' => $this->faker->lastName, 'email' => $this->faker->safeEmail, 'phone' => $this->faker->phoneNumber, - ]] + ]], ]; $client = $this->clientRepo->save($data); @@ -106,7 +109,7 @@ class CreateTestData extends Command */ private function createInvoices($client) { - for ($i=0; $i<$this->count; $i++) { + for ($i = 0; $i < $this->count; $i++) { $data = [ 'client_id' => $client->id, 'invoice_date_sql' => date_create()->modify(rand(-100, 100) . ' days')->format('Y-m-d'), @@ -115,8 +118,8 @@ class CreateTestData extends Command 'product_key' => $this->faker->word, 'qty' => $this->faker->randomDigit + 1, 'cost' => $this->faker->randomFloat(2, 1, 10), - 'notes' => $this->faker->text($this->faker->numberBetween(50, 300)) - ]] + 'notes' => $this->faker->text($this->faker->numberBetween(50, 300)), + ]], ]; $invoice = $this->invoiceRepo->save($data); @@ -146,7 +149,7 @@ class CreateTestData extends Command private function createVendors() { - for ($i=0; $i<$this->count; $i++) { + for ($i = 0; $i < $this->count; $i++) { $data = [ 'name' => $this->faker->name, 'address1' => $this->faker->streetAddress, @@ -159,7 +162,7 @@ class CreateTestData extends Command 'last_name' => $this->faker->lastName, 'email' => $this->faker->safeEmail, 'phone' => $this->faker->phoneNumber, - ]] + ]], ]; $vendor = $this->vendorRepo->save($data); @@ -174,7 +177,7 @@ class CreateTestData extends Command */ private function createExpense($vendor) { - for ($i=0; $i<$this->count; $i++) { + for ($i = 0; $i < $this->count; $i++) { $data = [ 'vendor_id' => $vendor->id, 'amount' => $this->faker->randomFloat(2, 1, 10), diff --git a/app/Console/Commands/GenerateResources.php b/app/Console/Commands/GenerateResources.php index 9826f3c70b07..17e139188caf 100644 --- a/app/Console/Commands/GenerateResources.php +++ b/app/Console/Commands/GenerateResources.php @@ -1,10 +1,12 @@ -laravel['modules']->findOrFail($this->getModuleName()); $path = str_replace('/', '\\', config('modules.paths.generator.' . $this->argument('class'))); return (new Stub('/' . $this->argument('prefix') . $this->argument('class') . '.stub', [ - 'NAMESPACE' => $this->getClassNamespace($module) . "\\" . $path, + 'NAMESPACE' => $this->getClassNamespace($module) . '\\' . $path, 'LOWER_NAME' => $module->getLowerName(), 'CLASS' => $this->getClass(), 'STUDLY_NAME' => Str::studly($module->getLowerName()), @@ -88,6 +87,7 @@ class MakeClass extends GeneratorCommand if ($this->option('filename')) { return $this->option('filename'); } + return studly_case($this->argument('prefix')) . studly_case($this->argument('name')) . Str::studly($this->argument('class')); } diff --git a/app/Console/Commands/MakeModule.php b/app/Console/Commands/MakeModule.php index 572134815e39..88291b78c50f 100644 --- a/app/Console/Commands/MakeModule.php +++ b/app/Console/Commands/MakeModule.php @@ -48,7 +48,7 @@ class MakeModule extends Command $fillable = array_map(function ($item) { return explode(':', $item)[0]; }, $fillable); - $fillable = join(',', $fillable); + $fillable = implode(',', $fillable); $this->info("Creating module: {$name}..."); @@ -77,21 +77,21 @@ class MakeModule extends Command Artisan::call('module:dump'); - $this->info("Done"); + $this->info('Done'); } protected function getArguments() { return [ ['name', InputArgument::REQUIRED, 'The name of the module.'], - ['fields', InputArgument::OPTIONAL, 'The fields of the module.'] + ['fields', InputArgument::OPTIONAL, 'The fields of the module.'], ]; } protected function getOptions() { - return array( - array('migrate', null, InputOption::VALUE_OPTIONAL, 'The model attributes.', null), - ); + return [ + ['migrate', null, InputOption::VALUE_OPTIONAL, 'The model attributes.', null], + ]; } } diff --git a/app/Console/Commands/PruneData.php b/app/Console/Commands/PruneData.php index 3a1a892e0840..33d2bd64c0a9 100644 --- a/app/Console/Commands/PruneData.php +++ b/app/Console/Commands/PruneData.php @@ -1,10 +1,12 @@ -info(date('Y-m-d') . ' Running ResetData...'); - if (!Utils::isNinjaDev()) { + if (! Utils::isNinjaDev()) { return; } diff --git a/app/Console/Commands/ResetInvoiceSchemaCounter.php b/app/Console/Commands/ResetInvoiceSchemaCounter.php index 645c1d09e71b..be221c4d6390 100644 --- a/app/Console/Commands/ResetInvoiceSchemaCounter.php +++ b/app/Console/Commands/ResetInvoiceSchemaCounter.php @@ -64,7 +64,7 @@ class ResetInvoiceSchemaCounter extends Command if (Carbon::now()->year > $invoiceYear || $force) { $accounts->transform(function ($a) { - /** @var Account $a */ + /* @var Account $a */ $a->invoice_number_counter = 1; $a->update(); }); diff --git a/app/Console/Commands/SendRecurringInvoices.php b/app/Console/Commands/SendRecurringInvoices.php index 0e69b232f85d..88b317df5a69 100644 --- a/app/Console/Commands/SendRecurringInvoices.php +++ b/app/Console/Commands/SendRecurringInvoices.php @@ -1,14 +1,16 @@ -account->loadLocalizationSettings($recurInvoice->client); $invoice = $this->invoiceRepo->createRecurringInvoice($recurInvoice); - if ($invoice && !$invoice->isPaid()) { + if ($invoice && ! $invoice->isPaid()) { $this->info('Sending Invoice'); $this->mailer->sendInvoice($invoice); } diff --git a/app/Console/Commands/SendReminders.php b/app/Console/Commands/SendReminders.php index bdb239deff70..87151db01897 100644 --- a/app/Console/Commands/SendReminders.php +++ b/app/Console/Commands/SendReminders.php @@ -1,13 +1,15 @@ -hasFeature(FEATURE_EMAIL_TEMPLATES_REMINDERS)) { + if (! $account->hasFeature(FEATURE_EMAIL_TEMPLATES_REMINDERS)) { continue; } diff --git a/app/Console/Commands/SendRenewalInvoices.php b/app/Console/Commands/SendRenewalInvoices.php index 30403ce4fd7e..edfc2471b31d 100644 --- a/app/Console/Commands/SendRenewalInvoices.php +++ b/app/Console/Commands/SendRenewalInvoices.php @@ -1,13 +1,15 @@ -info(count($companies).' companies found renewing in 10 days'); foreach ($companies as $company) { - if (!count($company->accounts)) { + if (! count($company->accounts)) { continue; } @@ -74,7 +76,7 @@ class SendRenewalInvoices extends Command $plan['price'] = min($company->pending_plan_price, Utils::getPlanPrice($plan)); } - if ($plan['plan'] == PLAN_FREE || !$plan['plan'] || !$plan['term'] || !$plan['price']) { + if ($plan['plan'] == PLAN_FREE || ! $plan['plan'] || ! $plan['term'] || ! $plan['price']) { continue; } diff --git a/app/Console/Commands/TestOFX.php b/app/Console/Commands/TestOFX.php index a7f9bd5615b8..08246c5f7c1b 100644 --- a/app/Console/Commands/TestOFX.php +++ b/app/Console/Commands/TestOFX.php @@ -1,10 +1,12 @@ - ['card' => 'images/credit_cards/Test-MasterCard-Icon.png', 'text' => 'Master Card'], 4 => ['card' => 'images/credit_cards/Test-AmericanExpress-Icon.png', 'text' => 'American Express'], 8 => ['card' => 'images/credit_cards/Test-Diners-Icon.png', 'text' => 'Diners'], - 16 => ['card' => 'images/credit_cards/Test-Discover-Icon.png', 'text' => 'Discover'] + 16 => ['card' => 'images/credit_cards/Test-Discover-Icon.png', 'text' => 'Discover'], ]; define('CREDIT_CARDS', serialize($creditCards)); @@ -539,7 +537,6 @@ if (!defined('APP_NAME')) { ]; define('CACHED_TABLES', serialize($cachedTables)); - // TODO remove these translation functions function uctrans($text) { @@ -556,6 +553,7 @@ if (!defined('APP_NAME')) { } else { $string = trans($text); $english = trans($text, [], 'en'); + return $string != $english ? $string : ''; } } diff --git a/app/Constants/Domain.php b/app/Constants/Domain.php index afdcbf90c52e..d8a0ff9b043f 100644 --- a/app/Constants/Domain.php +++ b/app/Constants/Domain.php @@ -1,4 +1,6 @@ -back() ->withInput($request->except('password', '_token')) ->with([ - 'warning' => trans('texts.token_expired') + 'warning' => trans('texts.token_expired'), ]); } } @@ -90,7 +94,7 @@ class Handler extends ExceptionHandler if ($request->header('X-Ninja-Token') != '') { //API request which has hit a route which does not exist - $error['error'] = ['message'=>'Route does not exist']; + $error['error'] = ['message' => 'Route does not exist']; $error = json_encode($error, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); @@ -103,7 +107,7 @@ class Handler extends ExceptionHandler if ($request->header('X-Ninja-Token') != '') { //API request which produces 500 error - $error['error'] = ['message'=>'Internal Server Error']; + $error['error'] = ['message' => 'Internal Server Error']; $error = json_encode($error, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); @@ -116,9 +120,9 @@ class Handler extends ExceptionHandler // In production, except for maintenance mode, we'll show a custom error screen if (Utils::isNinjaProd() - && !Utils::isDownForMaintenance() - && !($e instanceof HttpResponseException) - && !($e instanceof ValidationException)) { + && ! Utils::isDownForMaintenance() + && ! ($e instanceof HttpResponseException) + && ! ($e instanceof ValidationException)) { $data = [ 'error' => get_class($e), 'hideHeader' => true, diff --git a/app/Handlers/InvoiceEventHandler.php b/app/Handlers/InvoiceEventHandler.php index 7e4e6e714f8f..74c410880da4 100644 --- a/app/Handlers/InvoiceEventHandler.php +++ b/app/Handlers/InvoiceEventHandler.php @@ -1,7 +1,9 @@ -api_secret)) { return Response::make(RESULT_SUCCESS, 200, $headers); } else { - return $this->errorResponse(['message'=>'API Secret does not match .env variable'], 400); + return $this->errorResponse(['message' => 'API Secret does not match .env variable'], 400); } } @@ -55,7 +57,8 @@ class AccountApiController extends BaseAPIController return $this->processLogin($request); } else { sleep(ERROR_DELAY); - return $this->errorResponse(['message'=>'Invalid credentials'], 401); + + return $this->errorResponse(['message' => 'Invalid credentials'], 401); } } @@ -119,8 +122,7 @@ class AccountApiController extends BaseAPIController //scan if this user has a token already registered (tokens can change, so we need to use the users email as key) $devices = json_decode($account->devices, true); - - for ($x=0; $xusername) { $devices[$x]['token'] = $request->token; //update $account->devices = json_encode($devices); @@ -158,10 +160,10 @@ class AccountApiController extends BaseAPIController $devices = json_decode($account->devices, true); if (count($devices) < 1) { - return $this->errorResponse(['message'=>'No registered devices.'], 400); + return $this->errorResponse(['message' => 'No registered devices.'], 400); } - for ($x=0; $xusername) { $newDevice = [ 'token' => $devices[$x]['token'], @@ -202,9 +204,11 @@ class AccountApiController extends BaseAPIController if ($user) { Auth::login($user); + return $this->processLogin($request); } else { sleep(ERROR_DELAY); + return $this->errorResponse(['message' => 'Invalid credentials'], 401); } } diff --git a/app/Http/Controllers/AccountController.php b/app/Http/Controllers/AccountController.php index 25c6718ca5fe..708c994979c2 100644 --- a/app/Http/Controllers/AccountController.php +++ b/app/Http/Controllers/AccountController.php @@ -1,49 +1,51 @@ - 0 && !$prevUserId)) { + if (! Utils::isNinja() && (Account::count() > 0 && ! $prevUserId)) { return Redirect::to('/login'); } - if ($guestKey && !$prevUserId) { + if ($guestKey && ! $prevUserId) { $user = User::where('password', '=', $guestKey)->first(); if ($user && $user->registered) { @@ -139,7 +141,7 @@ class AccountController extends BaseController } } - if (!$user) { + if (! $user) { $account = $this->accountRepo->create(); $user = $account->users()->first(); @@ -184,7 +186,7 @@ class AccountController extends BaseController $newPlan['price'] = Utils::getPlanPrice($newPlan); $credit = 0; - if (!empty($planDetails['started']) && $plan == PLAN_FREE) { + if (! empty($planDetails['started']) && $plan == PLAN_FREE) { // Downgrade $refund_deadline = clone $planDetails['started']; $refund_deadline->modify('+30 days'); @@ -203,7 +205,7 @@ class AccountController extends BaseController } $hasPaid = false; - if (!empty($planDetails['paid']) && $plan != PLAN_FREE) { + if (! empty($planDetails['paid']) && $plan != PLAN_FREE) { $hasPaid = true; $time_used = $planDetails['paid']->diff(date_create()); $days_used = $time_used->days; @@ -243,10 +245,10 @@ class AccountController extends BaseController } } - /** * @param $entityType * @param $visible + * * @return mixed */ public function setEntityFilter($entityType, $filter = '') @@ -267,8 +269,8 @@ class AccountController extends BaseController } } - Session::put("entity_state_filter:{$entityType}", join(',', $stateFilter)); - Session::put("entity_status_filter:{$entityType}", join(',', $statusFilter)); + Session::put("entity_state_filter:{$entityType}", implode(',', $stateFilter)); + Session::put("entity_status_filter:{$entityType}", implode(',', $statusFilter)); return RESULT_SUCCESS; } @@ -285,6 +287,7 @@ class AccountController extends BaseController /** * @param bool $section + * * @return \Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse */ public function showSection($section = false) @@ -293,7 +296,7 @@ class AccountController extends BaseController return Redirect::to('/settings/user_details'); } - if (!$section) { + if (! $section) { return Redirect::to('/settings/'.ACCOUNT_COMPANY_DETAILS, 301); } @@ -362,7 +365,7 @@ class AccountController extends BaseController $account = Auth::user()->account; $recurringHours = []; - for ($i = 0; $i<24; $i++) { + for ($i = 0; $i < 24; $i++) { if ($account->military_time) { $format = 'H:i'; } else { @@ -488,17 +491,17 @@ class AccountController extends BaseController return Redirect::to('gateways/create'); } else { $tokenBillingOptions = []; - for ($i=1; $i<=4; $i++) { + for ($i = 1; $i <= 4; $i++) { $tokenBillingOptions[$i] = trans("texts.token_billing_{$i}"); } return View::make('accounts.payments', [ - 'showAdd' => $count < count(Gateway::$alternate) + 1, - 'title' => trans('texts.online_payments'), + 'showAdd' => $count < count(Gateway::$alternate) + 1, + 'title' => trans('texts.online_payments'), 'tokenBillingOptions' => $tokenBillingOptions, - 'currency' => Utils::getFromCache(Session::get(SESSION_CURRENCY, DEFAULT_CURRENCY), + 'currency' => Utils::getFromCache(Session::get(SESSION_CURRENCY, DEFAULT_CURRENCY), 'currencies'), - 'account' => $account, + 'account' => $account, ]); } } @@ -546,6 +549,7 @@ class AccountController extends BaseController /** * @param $section + * * @return \Illuminate\Contracts\View\View */ private function showInvoiceDesign($section) @@ -608,7 +612,7 @@ class AccountController extends BaseController } if ($section == ACCOUNT_CUSTOMIZE_DESIGN) { - $data['customDesign'] = ($account->custom_design && !$design) ? $account->custom_design : $design; + $data['customDesign'] = ($account->custom_design && ! $design) ? $account->custom_design : $design; // sample invoice to help determine variables $invoice = Invoice::scope() @@ -651,7 +655,7 @@ class AccountController extends BaseController GATEWAY_TYPE_BANK_TRANSFER, GATEWAY_TYPE_PAYPAL, GATEWAY_TYPE_BITCOIN, - GATEWAY_TYPE_DWOLLA + GATEWAY_TYPE_DWOLLA, ]; $options = []; foreach ($types as $type) { @@ -702,34 +706,35 @@ class AccountController extends BaseController /** * @param $section + * * @return \Illuminate\Http\RedirectResponse */ public function doSection($section) { if ($section === ACCOUNT_LOCALIZATION) { - return AccountController::saveLocalization(); + return self::saveLocalization(); } elseif ($section == ACCOUNT_PAYMENTS) { return self::saveOnlinePayments(); } elseif ($section === ACCOUNT_NOTIFICATIONS) { - return AccountController::saveNotifications(); + return self::saveNotifications(); } elseif ($section === ACCOUNT_EXPORT) { - return AccountController::export(); + return self::export(); } elseif ($section === ACCOUNT_INVOICE_SETTINGS) { - return AccountController::saveInvoiceSettings(); + return self::saveInvoiceSettings(); } elseif ($section === ACCOUNT_INVOICE_DESIGN) { - return AccountController::saveInvoiceDesign(); + return self::saveInvoiceDesign(); } elseif ($section === ACCOUNT_CUSTOMIZE_DESIGN) { - return AccountController::saveCustomizeDesign(); + return self::saveCustomizeDesign(); } elseif ($section === ACCOUNT_TEMPLATES_AND_REMINDERS) { - return AccountController::saveEmailTemplates(); + return self::saveEmailTemplates(); } elseif ($section === ACCOUNT_PRODUCTS) { - return AccountController::saveProducts(); + return self::saveProducts(); } elseif ($section === ACCOUNT_TAX_RATES) { - return AccountController::saveTaxRates(); + return self::saveTaxRates(); } elseif ($section === ACCOUNT_PAYMENT_TERMS) { - return AccountController::savePaymetTerms(); + return self::savePaymetTerms(); } elseif ($section === ACCOUNT_MANAGEMENT) { - return AccountController::saveAccountManagement(); + return self::saveAccountManagement(); } } @@ -752,6 +757,7 @@ class AccountController extends BaseController if ($font->google_font) { return false; } + return $font->id == $account->header_font_id || $font->id == $account->body_font_id; }); if ($account->live_preview && count($fonts)) { @@ -934,7 +940,7 @@ class AccountController extends BaseController $account->recurring_hour = Input::get('recurring_hour'); } - if (!$account->share_counter) { + if (! $account->share_counter) { $account->quote_number_counter = Input::get('quote_number_counter'); } @@ -948,7 +954,7 @@ class AccountController extends BaseController } } - if (!$account->share_counter + if (! $account->share_counter && $account->invoice_number_prefix == $account->quote_number_prefix && $account->invoice_number_pattern == $account->quote_number_pattern) { Session::flash('error', trans('texts.invalid_counter')); @@ -1018,6 +1024,7 @@ class AccountController extends BaseController /** * @param UpdateAccountRequest $request + * * @return \Illuminate\Http\RedirectResponse */ public function updateDetails(UpdateAccountRequest $request) @@ -1035,13 +1042,13 @@ class AccountController extends BaseController } $extension = strtolower($uploaded->getClientOriginalExtension()); - if (empty(Document::$types[$extension]) && !empty(Document::$extraExtensions[$extension])) { + if (empty(Document::$types[$extension]) && ! empty(Document::$extraExtensions[$extension])) { $documentType = Document::$extraExtensions[$extension]; } else { $documentType = $extension; } - if (!in_array($documentType, ['jpeg', 'png', 'gif'])) { + if (! in_array($documentType, ['jpeg', 'png', 'gif'])) { Session::flash('warning', 'Unsupported file type'); } else { $documentTypeData = Document::$types[$documentType]; @@ -1049,7 +1056,7 @@ class AccountController extends BaseController $filePath = $uploaded->path(); $size = filesize($filePath); - if ($size/1000 > MAX_DOCUMENT_SIZE) { + if ($size / 1000 > MAX_DOCUMENT_SIZE) { Session::flash('warning', 'File too large'); } else { if ($documentType != 'gif') { @@ -1070,7 +1077,7 @@ class AccountController extends BaseController $account->logo_size = strlen($imageStr); } else { $stream = fopen($filePath, 'r'); - $disk->getDriver()->putStream($account->logo, $stream, ['mimetype'=>$documentTypeData['mime']]); + $disk->getDriver()->putStream($account->logo, $stream, ['mimetype' => $documentTypeData['mime']]); fclose($stream); } } else { @@ -1134,7 +1141,7 @@ class AccountController extends BaseController } if (Utils::isNinja()) { - if (Input::get('referral_code') && !$user->referral_code) { + if (Input::get('referral_code') && ! $user->referral_code) { $user->referral_code = $this->accountRepo->getReferralCode(); } } @@ -1307,7 +1314,7 @@ class AccountController extends BaseController $affiliate = Affiliate::where('affiliate_key', '=', SELF_HOST_AFFILIATE_KEY)->first(); $email = trim(Input::get('email')); - if (!$email || $email == TEST_USERNAME) { + if (! $email || $email == TEST_USERNAME) { return RESULT_FAILURE; } @@ -1380,6 +1387,7 @@ class AccountController extends BaseController /** * @param $section * @param bool $subSection + * * @return \Illuminate\Http\RedirectResponse */ public function redirectLegacy($section, $subSection = false) @@ -1395,7 +1403,7 @@ class AccountController extends BaseController } } - if (!in_array($section, array_merge(Account::$basicSettings, Account::$advancedSettings))) { + if (! in_array($section, array_merge(Account::$basicSettings, Account::$advancedSettings))) { $section = ACCOUNT_COMPANY_DETAILS; } @@ -1404,6 +1412,7 @@ class AccountController extends BaseController /** * @param TemplateService $templateService + * * @return \Illuminate\Http\Response */ public function previewEmail(TemplateService $templateService) @@ -1429,7 +1438,7 @@ class AccountController extends BaseController 'invitation' => $invitation, 'link' => $invitation->getLink(), 'client' => $invoice->client, - 'amount' => $invoice->amount + 'amount' => $invoice->amount, ]; // create the email view diff --git a/app/Http/Controllers/AccountGatewayController.php b/app/Http/Controllers/AccountGatewayController.php index ec6552e93de4..8266593dafe1 100644 --- a/app/Http/Controllers/AccountGatewayController.php +++ b/app/Http/Controllers/AccountGatewayController.php @@ -1,19 +1,21 @@ -accepted_credit_cards : 0; $user = Auth::user(); - $account =$user->account; + $account = $user->account; $creditCardsArray = unserialize(CREDIT_CARDS); $creditCards = []; @@ -148,11 +149,10 @@ class AccountGatewayController extends BaseController 'config' => false, 'gateways' => $gateways, 'creditCardTypes' => $creditCards, - 'countGateways' => count($currentGateways) + 'countGateways' => count($currentGateways), ]; } - public function bulk() { $action = Input::get('bulk_action'); @@ -165,8 +165,7 @@ class AccountGatewayController extends BaseController } /** - * Stores new account - * + * Stores new account. */ public function save($accountGatewayPublicId = false) { @@ -190,7 +189,7 @@ class AccountGatewayController extends BaseController if ($gatewayId != GATEWAY_WEPAY) { foreach ($fields as $field => $details) { - if (!in_array($field, $optional)) { + if (! in_array($field, $optional)) { if (strtolower($gateway->name) == 'beanstream') { if (in_array($field, ['merchant_id', 'passCode'])) { $rules[$gateway->id . '_' . $field] = 'required'; @@ -224,6 +223,7 @@ class AccountGatewayController extends BaseController ->first(); if ($accountGateway) { Session::flash('error', trans('texts.gateway_exists')); + return Redirect::to("gateways/{$accountGateway->public_id}/edit"); } @@ -231,7 +231,7 @@ class AccountGatewayController extends BaseController $accountGateway->gateway_id = $gatewayId; if ($gatewayId == GATEWAY_WEPAY) { - if (!$this->setupWePay($accountGateway, $wepayResponse)) { + if (! $this->setupWePay($accountGateway, $wepayResponse)) { return $wepayResponse; } $oldConfig = $accountGateway->getConfig(); @@ -247,7 +247,7 @@ class AccountGatewayController extends BaseController if ($oldConfig && $value && $value === str_repeat('*', strlen($value))) { $value = $oldConfig->$field; } - if (!$value && ($field == 'testMode' || $field == 'developerMode')) { + if (! $value && ($field == 'testMode' || $field == 'developerMode')) { // do nothing } elseif ($gatewayId == GATEWAY_CUSTOM) { $config->$field = strip_tags($value); @@ -321,11 +321,13 @@ class AccountGatewayController extends BaseController if ($accountGatewayPublicId) { $message = trans('texts.updated_gateway'); Session::flash('message', $message); + return Redirect::to("gateways/{$accountGateway->public_id}/edit"); } else { $message = trans('texts.created_gateway'); Session::flash('message', $message); - return Redirect::to("/settings/online_payments"); + + return Redirect::to('/settings/online_payments'); } } } @@ -350,8 +352,8 @@ class AccountGatewayController extends BaseController $wepay = Utils::setupWePay($accountGateway); $update_uri_data = $wepay->request('account/get_update_uri', [ - 'account_id' => $accountGateway->getConfig()->accountId, - 'mode' => 'iframe', + 'account_id' => $accountGateway->getConfig()->accountId, + 'mode' => 'iframe', 'redirect_uri' => URL::to('/gateways'), ]); @@ -407,11 +409,11 @@ class AccountGatewayController extends BaseController $wepay = new WePay($accessToken); $accountDetails = [ - 'name' => Input::get('company_name'), - 'description' => trans('texts.wepay_account_description'), + 'name' => Input::get('company_name'), + 'description' => trans('texts.wepay_account_description'), 'theme_object' => json_decode(WEPAY_THEME), 'callback_uri' => $accountGateway->getWebhookUrl(), - 'rbits' => $account->present()->rBits, + 'rbits' => $account->present()->rBits, ]; if (WEPAY_ENABLE_CANADA) { @@ -457,20 +459,22 @@ class AccountGatewayController extends BaseController ]); $response = Redirect::to($updateUri->uri); + return true; } $response = Redirect::to("gateways/{$accountGateway->public_id}/edit"); + return true; } catch (\WePayException $e) { Session::flash('error', $e->getMessage()); $response = Redirect::to('gateways/create') ->withInput(); + return false; } } - public function resendConfirmation($publicId = false) { $accountGateway = AccountGateway::scope($publicId)->firstOrFail(); diff --git a/app/Http/Controllers/ActivityController.php b/app/Http/Controllers/ActivityController.php index bd84d3ff9a1f..578746a1836e 100644 --- a/app/Http/Controllers/ActivityController.php +++ b/app/Http/Controllers/ActivityController.php @@ -1,4 +1,6 @@ -withInput(); } @@ -113,7 +115,6 @@ class AppController extends BaseController $config .= "{$key}={$val}\n"; } - // Write Config Settings $fp = fopen(base_path().'/.env', 'w'); fwrite($fp, $config); @@ -141,12 +142,13 @@ class AppController extends BaseController return Redirect::to('/'); } - if (!Auth::check() && Utils::isDatabaseSetup() && Account::count() > 0) { + if (! Auth::check() && Utils::isDatabaseSetup() && Account::count() > 0) { return Redirect::to('/'); } if (! $canUpdateEnv = @fopen(base_path().'/.env', 'w')) { Session::flash('error', 'Warning: Permission denied to write to .env config file, try running sudo chown www-data:www-data /path/to/ninja/.env'); + return Redirect::to('/settings/system_settings'); } @@ -193,6 +195,7 @@ class AppController extends BaseController fclose($fp); Session::flash('message', trans('texts.updated_settings')); + return Redirect::to('/settings/system_settings'); } @@ -241,7 +244,7 @@ class AppController extends BaseController public function install() { - if (!Utils::isNinjaProd() && !Utils::isDatabaseSetup()) { + if (! Utils::isNinjaProd() && ! Utils::isDatabaseSetup()) { try { set_time_limit(60 * 5); // shouldn't take this long but just in case Artisan::call('migrate', ['--force' => true]); @@ -251,6 +254,7 @@ class AppController extends BaseController Artisan::call('optimize', ['--force' => true]); } catch (Exception $e) { Utils::logError($e); + return Response::make($e->getMessage(), 500); } } @@ -260,7 +264,7 @@ class AppController extends BaseController public function update() { - if (!Utils::isNinjaProd()) { + if (! Utils::isNinjaProd()) { try { set_time_limit(60 * 5); Artisan::call('clear-compiled'); @@ -290,6 +294,7 @@ class AppController extends BaseController Session::flash('warning', $message); } catch (Exception $e) { Utils::logError($e); + return Response::make($e->getMessage(), 500); } } @@ -301,12 +306,14 @@ class AppController extends BaseController { $messageId = Input::get('MessageID'); $error = Input::get('Name') . ': ' . Input::get('Description'); + return $this->emailService->markBounced($messageId, $error) ? RESULT_SUCCESS : RESULT_FAILURE; } public function emailOpened() { $messageId = Input::get('MessageID'); + return $this->emailService->markOpened($messageId) ? RESULT_SUCCESS : RESULT_FAILURE; return RESULT_SUCCESS; @@ -316,6 +323,7 @@ class AppController extends BaseController { if (! hash_equals(Input::get('password'), env('RESELLER_PASSWORD'))) { sleep(3); + return ''; } @@ -329,7 +337,7 @@ class AppController extends BaseController 'clients.public_id as client_id', 'payments.public_id as payment_id', 'payments.payment_date', - 'payments.amount' + 'payments.amount', ]); } else { $data = DB::table('users')->count(); diff --git a/app/Http/Controllers/Auth/AuthController.php b/app/Http/Controllers/Auth/AuthController.php index 84922822ce9b..10976a249997 100644 --- a/app/Http/Controllers/Auth/AuthController.php +++ b/app/Http/Controllers/Auth/AuthController.php @@ -1,20 +1,21 @@ -accountRepo->unlinkUserFromOauth(Auth::user()); Session::flash('message', trans('texts.updated_settings')); + return redirect()->to('/settings/' . ACCOUNT_USER_DETAILS); } @@ -113,7 +117,7 @@ class AuthController extends Controller */ public function getLoginWrapper() { - if (!Utils::isNinja() && !User::count()) { + if (! Utils::isNinja() && ! User::count()) { return redirect()->to('invoice_now'); } @@ -132,6 +136,7 @@ class AuthController extends Controller if ($user && $user->failed_logins >= MAX_FAILED_LOGINS) { Session::flash('error', trans('texts.invalid_credentials')); + return redirect()->to('login'); } @@ -167,7 +172,7 @@ class AuthController extends Controller */ public function getLogoutWrapper() { - if (Auth::check() && !Auth::user()->registered) { + if (Auth::check() && ! Auth::user()->registered) { $account = Auth::user()->account; $this->accountRepo->unlinkAccount($account); diff --git a/app/Http/Controllers/Auth/PasswordController.php b/app/Http/Controllers/Auth/PasswordController.php index a5ceba3e660d..42fa1c76d90d 100644 --- a/app/Http/Controllers/Auth/PasswordController.php +++ b/app/Http/Controllers/Auth/PasswordController.php @@ -1,11 +1,12 @@ - null, 'bankAccount' => null, - 'transactions' => json_encode([$data]) + 'transactions' => json_encode([$data]), ]; return View::make('accounts.bank_account', $data); diff --git a/app/Http/Controllers/BaseAPIController.php b/app/Http/Controllers/BaseAPIController.php index c872d8206a1c..0a07f8b0b5bd 100644 --- a/app/Http/Controllers/BaseAPIController.php +++ b/app/Http/Controllers/BaseAPIController.php @@ -1,17 +1,19 @@ -manager->createData($resource)->toArray(); } @@ -159,7 +162,7 @@ class BaseAPIController extends Controller } else { $meta = isset($response['meta']) ? $response['meta'] : null; $response = [ - $index => $response + $index => $response, ]; if ($meta) { diff --git a/app/Http/Controllers/BaseController.php b/app/Http/Controllers/BaseController.php index 5ca6f2c8018a..90e85c312f78 100644 --- a/app/Http/Controllers/BaseController.php +++ b/app/Http/Controllers/BaseController.php @@ -1,9 +1,11 @@ - Input::get('name'), - 'business_phone_number' => Input::get('phone'), - 'email' => Input::get('email'), - 'personal_fico_score' => intval(Input::get('fico_score')), - 'business_annual_revenue' => intval(Input::get('annual_revenue')), + $data = [ + 'personal_user_full_name' => Input::get('name'), + 'business_phone_number' => Input::get('phone'), + 'email' => Input::get('email'), + 'personal_fico_score' => intval(Input::get('fico_score')), + 'business_annual_revenue' => intval(Input::get('annual_revenue')), 'business_monthly_average_bank_balance' => intval(Input::get('average_bank_balance')), - 'business_inception_date' => date('Y-m-d', strtotime(Input::get('business_inception'))), - 'partner_internal_business_id' => 'ninja_account_' . $user->account_id, - ); + 'business_inception_date' => date('Y-m-d', strtotime(Input::get('business_inception'))), + 'partner_internal_business_id' => 'ninja_account_' . $user->account_id, + ]; if (! empty(Input::get('quote_type_factoring'))) { $data['invoice_factoring_offer'] = true; - $data['desired_credit_line'] = intval(Input::get('desired_credit_limit')['invoice_factoring']); + $data['desired_credit_line'] = intval(Input::get('desired_credit_limit')['invoice_factoring']); } if (! empty(Input::get('quote_type_loc'))) { - $data['line_of_credit_offer'] = true; + $data['line_of_credit_offer'] = true; $data['desired_credit_line_for_loc'] = intval(Input::get('desired_credit_limit')['line_of_credit']); } - $api_client = new \GuzzleHttp\Client(); try { $response = $api_client->request('POST', - 'https://app.bluevine.com/api/v1/user/register_external?' . http_build_query(array( + 'https://app.bluevine.com/api/v1/user/register_external?' . http_build_query([ 'external_register_token' => env('BLUEVINE_PARTNER_TOKEN'), - 'c' => env('BLUEVINE_PARTNER_UNIQUE_ID'), - 'signup_parent_url' => URL::to('/bluevine/completed'), - )), array( - 'json' => $data - ) + 'c' => env('BLUEVINE_PARTNER_UNIQUE_ID'), + 'signup_parent_url' => URL::to('/bluevine/completed'), + ]), [ + 'json' => $data, + ] ); } catch (\GuzzleHttp\Exception\RequestException $ex) { if ($ex->getCode() == 403) { @@ -53,12 +52,12 @@ class BlueVineController extends BaseController $response_data = json_decode($response_body); return response()->json([ - 'error' => true, - 'message' => $response_data->reason + 'error' => true, + 'message' => $response_data->reason, ]); } else { return response()->json([ - 'error' => true + 'error' => true, ]); } } diff --git a/app/Http/Controllers/BotController.php b/app/Http/Controllers/BotController.php index 3cb9049fe21e..02267924f23a 100644 --- a/app/Http/Controllers/BotController.php +++ b/app/Http/Controllers/BotController.php @@ -2,18 +2,18 @@ namespace App\Http\Controllers; -use Auth; -use DB; -use Utils; -use Cache; -use Input; -use Exception; -use App\Libraries\Skype\SkypeResponse; use App\Libraries\CurlUtils; -use App\Models\User; +use App\Libraries\Skype\SkypeResponse; use App\Models\SecurityCode; +use App\Models\User; use App\Ninja\Intents\BaseIntent; use App\Ninja\Mailers\UserMailer; +use Auth; +use Cache; +use DB; +use Exception; +use Input; +use Utils; class BotController extends Controller { @@ -42,6 +42,7 @@ class BotController extends Controller } elseif ($input['action'] === 'remove') { $this->removeBot($botUserId); $this->saveState($token, false); + return RESULT_SUCCESS; } } else { @@ -130,7 +131,7 @@ class BotController extends Controller $url = sprintf('%s/botstate/skype/conversations/%s', MSBOT_STATE_URL, '29:1C-OsU7OWBEDOYJhQUsDkYHmycOwOq9QOg5FVTwRX9ts'); $headers = [ - 'Authorization: Bearer ' . $token + 'Authorization: Bearer ' . $token, ]; $response = CurlUtils::get($url, $headers); @@ -165,7 +166,6 @@ class BotController extends Controller $data = '{ eTag: "*", data: "' . addslashes(json_encode($data)) . '" }'; - CurlUtils::post($url, $data, $headers); } @@ -237,6 +237,7 @@ class BotController extends Controller if (! hash_equals($code->code, $input)) { $code->attempts += 1; $code->save(); + return false; } @@ -298,7 +299,7 @@ class BotController extends Controller } // 7 show result - return ($token_valid == 1); + return $token_valid == 1; } private function base64_url_decode($arg) @@ -310,15 +311,16 @@ class BotController extends Controller case 0: break; case 2: - $res .= "=="; + $res .= '=='; break; case 3: - $res .= "="; + $res .= '='; break; default: break; } $res = base64_decode($res); + return $res; } } diff --git a/app/Http/Controllers/ClientApiController.php b/app/Http/Controllers/ClientApiController.php index 54d400e502c1..d04e3eb11fc5 100644 --- a/app/Http/Controllers/ClientApiController.php +++ b/app/Http/Controllers/ClientApiController.php @@ -1,12 +1,14 @@ -itemResponse($request->entity()); } - - - /** * @SWG\Post( * path="/clients", @@ -127,7 +125,6 @@ class ClientApiController extends BaseAPIController * ) * ) */ - public function update(UpdateClientRequest $request, $publicId) { if ($request->action) { @@ -143,7 +140,6 @@ class ClientApiController extends BaseAPIController return $this->itemResponse($client); } - /** * @SWG\Delete( * path="/clients/{client_id}", @@ -165,7 +161,6 @@ class ClientApiController extends BaseAPIController * ) * ) */ - public function destroy(UpdateClientRequest $request) { $client = $request->entity(); diff --git a/app/Http/Controllers/ClientAuth/AuthController.php b/app/Http/Controllers/ClientAuth/AuthController.php index fee6eeab838f..0bf8d303feed 100644 --- a/app/Http/Controllers/ClientAuth/AuthController.php +++ b/app/Http/Controllers/ClientAuth/AuthController.php @@ -1,11 +1,13 @@ -first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { $account = $contact->account; $data['account'] = $account; @@ -45,7 +47,7 @@ class AuthController extends Controller /** * Get the needed authorization credentials from the request. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request * * @return array */ @@ -57,7 +59,7 @@ class AuthController extends Controller $contactKey = session('contact_key'); if ($contactKey) { $contact = Contact::where('contact_key', '=', $contactKey)->first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { $credentials['id'] = $contact->id; } } @@ -68,7 +70,7 @@ class AuthController extends Controller /** * Validate the user login request. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request * * @return void */ diff --git a/app/Http/Controllers/ClientAuth/PasswordController.php b/app/Http/Controllers/ClientAuth/PasswordController.php index f1b5624a1a15..e721a9533281 100644 --- a/app/Http/Controllers/ClientAuth/PasswordController.php +++ b/app/Http/Controllers/ClientAuth/PasswordController.php @@ -1,17 +1,18 @@ -first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { $account = $contact->account; $data['account'] = $account; $data['clientFontUrl'] = $account->getFontsUrl(); @@ -66,7 +67,7 @@ class PasswordController extends Controller /** * Send a reset link to the given user. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response */ @@ -78,7 +79,7 @@ class PasswordController extends Controller $contactKey = session('contact_key'); if ($contactKey) { $contact = Contact::where('contact_key', '=', $contactKey)->first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { $contactId = $contact->id; } } @@ -102,9 +103,10 @@ class PasswordController extends Controller * * If no token is present, display the link request form. * - * @param \Illuminate\Http\Request $request - * @param string|null $key - * @param string|null $token + * @param \Illuminate\Http\Request $request + * @param string|null $key + * @param string|null $token + * * @return \Illuminate\Http\Response */ public function showResetForm(Request $request, $key = null, $token = null) @@ -116,19 +118,19 @@ class PasswordController extends Controller $data = compact('token'); if ($key) { $contact = Contact::where('contact_key', '=', $key)->first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { $account = $contact->account; $data['contact_key'] = $contact->contact_key; } else { // Maybe it's an invitation key $invitation = Invitation::where('invitation_key', '=', $key)->first(); - if ($invitation && !$invitation->is_deleted) { + if ($invitation && ! $invitation->is_deleted) { $account = $invitation->account; $data['contact_key'] = $invitation->contact->contact_key; } } - if (!empty($account)) { + if (! empty($account)) { $data['account'] = $account; $data['clientFontUrl'] = $account->getFontsUrl(); } else { @@ -139,15 +141,15 @@ class PasswordController extends Controller return view('clientauth.reset')->with($data); } - /** * Display the password reset view for the given token. * * If no token is present, display the link request form. * - * @param \Illuminate\Http\Request $request - * @param string|null $key - * @param string|null $token + * @param \Illuminate\Http\Request $request + * @param string|null $key + * @param string|null $token + * * @return \Illuminate\Http\Response */ public function getReset(Request $request, $key = null, $token = null) @@ -158,7 +160,8 @@ class PasswordController extends Controller /** * Reset the given user's password. * - * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Request $request + * * @return \Illuminate\Http\Response */ public function reset(Request $request) @@ -174,7 +177,7 @@ class PasswordController extends Controller $contactKey = session('contact_key'); if ($contactKey) { $contact = Contact::where('contact_key', '=', $contactKey)->first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { $credentials['id'] = $contact->id; } } diff --git a/app/Http/Controllers/ClientController.php b/app/Http/Controllers/ClientController.php index 32f35727ec2c..54a9d5a81710 100644 --- a/app/Http/Controllers/ClientController.php +++ b/app/Http/Controllers/ClientController.php @@ -1,24 +1,26 @@ - trans('texts.new_quote'), 'url' => URL::to('/quotes/create/'.$client->public_id)]; } - if (!empty($actionLinks)) { + if (! empty($actionLinks)) { $actionLinks[] = \DropdownButton::DIVIDER; } @@ -153,7 +156,8 @@ class ClientController extends BaseController /** * Show the form for editing the specified resource. * - * @param int $id + * @param int $id + * * @return Response */ public function edit(ClientRequest $request) @@ -194,7 +198,8 @@ class ClientController extends BaseController /** * Update the specified resource in storage. * - * @param int $id + * @param int $id + * * @return Response */ public function update(UpdateClientRequest $request) diff --git a/app/Http/Controllers/ClientPortalController.php b/app/Http/Controllers/ClientPortalController.php index e3564d4f9460..a18edc445c1a 100644 --- a/app/Http/Controllers/ClientPortalController.php +++ b/app/Http/Controllers/ClientPortalController.php @@ -1,32 +1,34 @@ -invoiceRepo->findInvoiceByInvitation($invitationKey)) { + if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { return $this->returnError(); } @@ -54,7 +56,7 @@ class ClientPortalController extends BaseController $client = $invoice->client; $account = $invoice->account; - if (!$account->checkSubdomain(Request::server('HTTP_HOST'))) { + if (! $account->checkSubdomain(Request::server('HTTP_HOST'))) { return response()->view('error', [ 'error' => trans('texts.invoice_not_found'), 'hideHeader' => true, @@ -65,8 +67,8 @@ class ClientPortalController extends BaseController $account->loadLocalizationSettings($client); - if (!Input::has('phantomjs') && !Input::has('silent') && !Session::has($invitationKey) - && (!Auth::check() || Auth::user()->account_id != $invoice->account_id)) { + if (! Input::has('phantomjs') && ! Input::has('silent') && ! Session::has($invitationKey) + && (! Auth::check() || Auth::user()->account_id != $invoice->account_id)) { if ($invoice->isType(INVOICE_TYPE_QUOTE)) { event(new QuoteInvitationWasViewed($invoice, $invitation)); } else { @@ -75,7 +77,7 @@ class ClientPortalController extends BaseController } Session::put($invitationKey, true); // track this invitation has been seen - Session::put('contact_key', $invitation->contact->contact_key);// track current contact + Session::put('contact_key', $invitation->contact->contact_key); // track current contact $invoice->invoice_date = Utils::fromSqlDate($invoice->invoice_date); $invoice->due_date = Utils::fromSqlDate($invoice->due_date); @@ -111,7 +113,7 @@ class ClientPortalController extends BaseController $paymentURL = $paymentTypes[0]['url']; if ($paymentTypes[0]['gatewayTypeId'] == GATEWAY_TYPE_CUSTOM) { // do nothing - } elseif (!$account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) { + } elseif (! $account->isGatewayConfigured(GATEWAY_PAYPAL_EXPRESS)) { $paymentURL = URL::to($paymentURL); } } @@ -184,7 +186,7 @@ class ClientPortalController extends BaseController public function download($invitationKey) { - if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { + if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { return response()->view('error', [ 'error' => trans('texts.invoice_not_found'), 'hideHeader' => true, @@ -205,7 +207,7 @@ class ClientPortalController extends BaseController public function sign($invitationKey) { - if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { + if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { return RESULT_FAILURE; } @@ -223,11 +225,11 @@ class ClientPortalController extends BaseController public function dashboard($contactKey = false) { if ($contactKey) { - if (!$contact = Contact::where('contact_key', '=', $contactKey)->first()) { + if (! $contact = Contact::where('contact_key', '=', $contactKey)->first()) { return $this->returnError(); } - Session::put('contact_key', $contactKey);// track current contact - } elseif (!$contact = $this->getContact()) { + Session::put('contact_key', $contactKey); // track current contact + } elseif (! $contact = $this->getContact()) { return $this->returnError(); } @@ -238,9 +240,9 @@ class ClientPortalController extends BaseController $color = $account->primary_color ? $account->primary_color : '#0b4d78'; $customer = false; - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); - } elseif (!$account->enable_client_portal_dashboard) { + } elseif (! $account->enable_client_portal_dashboard) { return redirect()->to('/client/invoices/'); } @@ -264,7 +266,7 @@ class ClientPortalController extends BaseController public function activityDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } @@ -302,14 +304,14 @@ class ClientPortalController extends BaseController public function recurringInvoiceIndex() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $account = $contact->account; $account->loadLocalizationSettings($contact->client); - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); } @@ -330,14 +332,14 @@ class ClientPortalController extends BaseController public function invoiceIndex() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $account = $contact->account; $account->loadLocalizationSettings($contact->client); - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); } @@ -358,7 +360,7 @@ class ClientPortalController extends BaseController public function invoiceDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return ''; } @@ -367,24 +369,23 @@ class ClientPortalController extends BaseController public function recurringInvoiceDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return ''; } return $this->invoiceRepo->getClientRecurringDatatable($contact->id); } - public function paymentIndex() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $account = $contact->account; $account->loadLocalizationSettings($contact->client); - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); } @@ -396,7 +397,7 @@ class ClientPortalController extends BaseController 'clientFontUrl' => $account->getFontsUrl(), 'entityType' => ENTITY_PAYMENT, 'title' => trans('texts.payments'), - 'columns' => Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'status']) + 'columns' => Utils::trans(['invoice', 'transaction_reference', 'method', 'payment_amount', 'payment_date', 'status']), ]; return response()->view('public_list', $data); @@ -404,7 +405,7 @@ class ClientPortalController extends BaseController public function paymentDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $payments = $this->paymentRepo->findForContact($contact->id, Input::get('sSearch')); @@ -417,7 +418,7 @@ class ClientPortalController extends BaseController return $model->transaction_reference ? $model->transaction_reference : ''.trans('texts.manual_entry').''; }) ->addColumn('payment_type', function ($model) { - return ($model->payment_type && !$model->last4) ? $model->payment_type : ($model->account_gateway_id ? 'Online payment' : ''); + return ($model->payment_type && ! $model->last4) ? $model->payment_type : ($model->account_gateway_id ? 'Online payment' : ''); }) ->addColumn('amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); @@ -456,19 +457,20 @@ class ClientPortalController extends BaseController $class = 'default'; break; } + return "

$label

"; } public function quoteIndex() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $account = $contact->account; $account->loadLocalizationSettings($contact->client); - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); } @@ -486,10 +488,9 @@ class ClientPortalController extends BaseController return response()->view('public_list', $data); } - public function quoteDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return false; } @@ -498,14 +499,14 @@ class ClientPortalController extends BaseController public function creditIndex() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $account = $contact->account; $account->loadLocalizationSettings($contact->client); - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); } @@ -525,7 +526,7 @@ class ClientPortalController extends BaseController public function creditDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return false; } @@ -534,14 +535,14 @@ class ClientPortalController extends BaseController public function documentIndex() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $account = $contact->account; $account->loadLocalizationSettings($contact->client); - if (!$account->enable_client_portal) { + if (! $account->enable_client_portal) { return $this->returnError(); } @@ -559,10 +560,9 @@ class ClientPortalController extends BaseController return response()->view('public_list', $data); } - public function documentDatatable() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return false; } @@ -582,13 +582,13 @@ class ClientPortalController extends BaseController { $contactKey = session('contact_key'); - if (!$contactKey) { + if (! $contactKey) { return false; } $contact = Contact::where('contact_key', '=', $contactKey)->first(); - if (!$contact || $contact->is_deleted) { + if (! $contact || $contact->is_deleted) { return false; } @@ -597,33 +597,32 @@ class ClientPortalController extends BaseController public function getDocumentVFSJS($publicId, $name) { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } $document = Document::scope($publicId, $contact->account_id)->first(); - - if (!$document->isPDFEmbeddable()) { - return Response::view('error', ['error'=>'Image does not exist!'], 404); + if (! $document->isPDFEmbeddable()) { + return Response::view('error', ['error' => 'Image does not exist!'], 404); } $authorized = false; if ($document->expense && $document->expense->client_id == $contact->client_id) { $authorized = true; - } elseif ($document->invoice && $document->invoice->client_id ==$contact->client_id) { + } elseif ($document->invoice && $document->invoice->client_id == $contact->client_id) { $authorized = true; } - if (!$authorized) { - return Response::view('error', ['error'=>'Not authorized'], 403); + if (! $authorized) { + return Response::view('error', ['error' => 'Not authorized'], 403); } - if (substr($name, -3)=='.js') { + if (substr($name, -3) == '.js') { $name = substr($name, 0, -3); } - $content = $document->preview?$document->getRawPreview():$document->getRaw(); + $content = $document->preview ? $document->getRawPreview() : $document->getRaw(); $content = 'ninjaAddVFSDoc('.json_encode(intval($publicId).'/'.strval($name)).',"'.base64_encode($content).'")'; $response = Response::make($content, 200); $response->header('content-type', 'text/javascript'); @@ -637,7 +636,7 @@ class ClientPortalController extends BaseController return function_exists('gmp_init'); } - protected function getInvoiceZipDocuments($invoice, &$size=0) + protected function getInvoiceZipDocuments($invoice, &$size = 0) { $documents = $invoice->documents; @@ -655,13 +654,13 @@ class ClientPortalController extends BaseController break; } - if (!empty($toZip[$document->name])) { + if (! empty($toZip[$document->name])) { // This name is taken if ($toZip[$document->name]->hash != $document->hash) { // 2 different files with the same name $nameInfo = pathinfo($document->name); - for ($i = 1;; $i++) { + for ($i = 1; ; $i++) { $name = $nameInfo['filename'].' ('.$i.').'.$nameInfo['extension']; if (empty($toZip[$name])) { @@ -685,26 +684,27 @@ class ClientPortalController extends BaseController public function getInvoiceDocumentsZip($invitationKey) { - if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { + if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { return $this->returnError(); } - Session::put('contact_key', $invitation->contact->contact_key);// track current contact + Session::put('contact_key', $invitation->contact->contact_key); // track current contact $invoice = $invitation->invoice; $toZip = $this->getInvoiceZipDocuments($invoice); - if (!count($toZip)) { - return Response::view('error', ['error'=>'No documents small enough'], 404); + if (! count($toZip)) { + return Response::view('error', ['error' => 'No documents small enough'], 404); } $zip = new ZipArchive($invitation->account->name.' Invoice '.$invoice->invoice_number.'.zip'); + return Response::stream(function () use ($toZip, $zip) { - foreach ($toZip as $name=>$document) { + foreach ($toZip as $name => $document) { $fileStream = $document->getStream(); if ($fileStream) { - $zip->init_file_stream_transfer($name, $document->size, ['time'=>$document->created_at->timestamp]); + $zip->init_file_stream_transfer($name, $document->size, ['time' => $document->created_at->timestamp]); while ($buffer = fread($fileStream, 256000)) { $zip->stream_file_part($buffer); } @@ -720,11 +720,11 @@ class ClientPortalController extends BaseController public function getDocument($invitationKey, $publicId) { - if (!$invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { + if (! $invitation = $this->invoiceRepo->findInvoiceByInvitation($invitationKey)) { return $this->returnError(); } - Session::put('contact_key', $invitation->contact->contact_key);// track current contact + Session::put('contact_key', $invitation->contact->contact_key); // track current contact $clientId = $invitation->invoice->client_id; $document = Document::scope($publicId, $invitation->account_id)->firstOrFail(); @@ -736,8 +736,8 @@ class ClientPortalController extends BaseController $authorized = true; } - if (!$authorized) { - return Response::view('error', ['error'=>'Not authorized'], 403); + if (! $authorized) { + return Response::view('error', ['error' => 'Not authorized'], 403); } return DocumentController::getDownloadResponse($document); @@ -745,7 +745,7 @@ class ClientPortalController extends BaseController public function paymentMethods() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } @@ -777,7 +777,7 @@ class ClientPortalController extends BaseController $amount1 = Input::get('verification1'); $amount2 = Input::get('verification2'); - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } @@ -793,12 +793,12 @@ class ClientPortalController extends BaseController Session::flash('message', trans('texts.payment_method_verified')); } - return redirect()->to($account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/'); + return redirect()->to($account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/'); } public function removePaymentMethod($publicId) { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } @@ -817,12 +817,12 @@ class ClientPortalController extends BaseController Session::flash('error', $exception->getMessage()); } - return redirect()->to($client->account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/'); + return redirect()->to($client->account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/'); } public function setDefaultPaymentMethod() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } @@ -831,7 +831,7 @@ class ClientPortalController extends BaseController $validator = Validator::make(Input::all(), ['source' => 'required']); if ($validator->fails()) { - return Redirect::to($client->account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/'); + return Redirect::to($client->account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/'); } $paymentDriver = $account->paymentDriver(false, GATEWAY_TYPE_TOKEN); @@ -845,7 +845,7 @@ class ClientPortalController extends BaseController Session::flash('message', trans('texts.payment_method_set_as_default')); - return redirect()->to($client->account->enable_client_portal_dashboard?'/client/dashboard':'/client/payment_methods/'); + return redirect()->to($client->account->enable_client_portal_dashboard ? '/client/dashboard' : '/client/payment_methods/'); } private function paymentMethodError($type, $error, $accountGateway = false, $exception = false) @@ -862,7 +862,7 @@ class ClientPortalController extends BaseController public function setAutoBill() { - if (!$contact = $this->getContact()) { + if (! $contact = $this->getContact()) { return $this->returnError(); } diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index b0c144732f6a..8c55a50d0469 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -1,11 +1,13 @@ -credit_date = Utils::fromSqlDate($credit->credit_date); - $data = array( + $data = [ 'client' => $credit->client, 'clientPublicId' => $credit->client->public_id, 'credit' => $credit, @@ -78,7 +80,7 @@ class CreditController extends BaseController 'url' => 'credits/'.$publicId, 'title' => 'Edit Credit', 'clients' => null, - ); + ]; return View::make('credits.edit', $data); } diff --git a/app/Http/Controllers/DashboardApiController.php b/app/Http/Controllers/DashboardApiController.php index 3c2179656dc0..d87ea271392a 100644 --- a/app/Http/Controllers/DashboardApiController.php +++ b/app/Http/Controllers/DashboardApiController.php @@ -1,8 +1,10 @@ -type, Document::$types)) { return DocumentController::getDownloadResponse($document); } else { - return $this->errorResponse(['error'=>'Invalid mime type'], 400); + return $this->errorResponse(['error' => 'Invalid mime type'], 400); } } diff --git a/app/Http/Controllers/DocumentController.php b/app/Http/Controllers/DocumentController.php index 9ec6365f7e97..28a544cb3dc5 100644 --- a/app/Http/Controllers/DocumentController.php +++ b/app/Http/Controllers/DocumentController.php @@ -1,13 +1,15 @@ - Document::$types[$document->type]['mime'], - 'Content-Length' => $document->size, + 'Content-Type' => Document::$types[$document->type]['mime'], + 'Content-Length' => $document->size, ]; $response = Response::stream(function () use ($stream) { @@ -57,7 +59,7 @@ class DocumentController extends BaseController $document = $request->entity(); if (empty($document->preview)) { - return Response::view('error', ['error'=>'Preview does not exist!'], 404); + return Response::view('error', ['error' => 'Preview does not exist!'], 404); } $direct_url = $document->getDirectPreviewUrl(); @@ -76,15 +78,15 @@ class DocumentController extends BaseController { $document = $request->entity(); - if (substr($name, -3)=='.js') { + if (substr($name, -3) == '.js') { $name = substr($name, 0, -3); } - if (!$document->isPDFEmbeddable()) { - return Response::view('error', ['error'=>'Image does not exist!'], 404); + if (! $document->isPDFEmbeddable()) { + return Response::view('error', ['error' => 'Image does not exist!'], 404); } - $content = $document->preview?$document->getRawPreview():$document->getRaw(); + $content = $document->preview ? $document->getRawPreview() : $document->getRaw(); $content = 'ninjaAddVFSDoc('.json_encode(intval($publicId).'/'.strval($name)).',"'.base64_encode($content).'")'; $response = Response::make($content, 200); $response->header('content-type', 'text/javascript'); @@ -100,13 +102,13 @@ class DocumentController extends BaseController if (is_string($result)) { return Response::json([ 'error' => $result, - 'code' => 400 + 'code' => 400, ], 400); } else { return Response::json([ 'error' => false, 'document' => $doc_array, - 'code' => 200 + 'code' => 200, ], 200); } } diff --git a/app/Http/Controllers/ExpenseApiController.php b/app/Http/Controllers/ExpenseApiController.php index 997be9a09d8a..8bf670348cd6 100644 --- a/app/Http/Controllers/ExpenseApiController.php +++ b/app/Http/Controllers/ExpenseApiController.php @@ -1,11 +1,13 @@ -itemResponse($category); } - /** * @SWG\Put( * path="/expense_categories/{expense_category_id}", diff --git a/app/Http/Controllers/ExpenseCategoryController.php b/app/Http/Controllers/ExpenseCategoryController.php index 07fe898d8118..6dcbd83b4c32 100644 --- a/app/Http/Controllers/ExpenseCategoryController.php +++ b/app/Http/Controllers/ExpenseCategoryController.php @@ -1,14 +1,16 @@ -trashed()) { + if (! $expense->trashed()) { $actions[] = ['url' => 'javascript:submitAction("archive")', 'label' => trans('texts.archive_expense')]; $actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans('texts.delete_expense')]; } else { @@ -143,7 +145,8 @@ class ExpenseController extends BaseController /** * Update the specified resource in storage. * - * @param int $id + * @param int $id + * * @return Response */ public function update(UpdateExpenseRequest $request) @@ -178,7 +181,7 @@ class ExpenseController extends BaseController public function bulk() { $action = Input::get('action'); - $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids'); + $ids = Input::get('public_id') ? Input::get('public_id') : Input::get('ids'); switch ($action) { case 'invoice': @@ -190,23 +193,26 @@ class ExpenseController extends BaseController // Validate that either all expenses do not have a client or if there is a client, it is the same client foreach ($expenses as $expense) { if ($expense->client) { - if (!$clientPublicId) { + if (! $clientPublicId) { $clientPublicId = $expense->client->public_id; } elseif ($clientPublicId != $expense->client->public_id) { Session::flash('error', trans('texts.expense_error_multiple_clients')); + return Redirect::to('expenses'); } } - if (!$currencyId) { + if (! $currencyId) { $currencyId = $expense->invoice_currency_id; } elseif ($currencyId != $expense->invoice_currency_id && $expense->invoice_currency_id) { Session::flash('error', trans('texts.expense_error_multiple_currencies')); + return Redirect::to('expenses'); } if ($expense->invoice_id) { Session::flash('error', trans('texts.expense_error_invoiced')); + return Redirect::to('expenses'); } } @@ -217,6 +223,7 @@ class ExpenseController extends BaseController ->with('expenses', $ids); } else { $invoiceId = Input::get('invoice_id'); + return Redirect::to("invoices/{$invoiceId}/edit") ->with('expenseCurrencyId', $currencyId) ->with('expenses', $ids); @@ -224,7 +231,7 @@ class ExpenseController extends BaseController break; default: - $count = $this->expenseService->bulk($ids, $action); + $count = $this->expenseService->bulk($ids, $action); } if ($count > 0) { diff --git a/app/Http/Controllers/ExportController.php b/app/Http/Controllers/ExportController.php index 4db38263d909..9a8e54f59d17 100644 --- a/app/Http/Controllers/ExportController.php +++ b/app/Http/Controllers/ExportController.php @@ -1,25 +1,27 @@ -parseIncludes('clients.invoices.payments') ->createData($resource) ->toArray(); @@ -163,7 +165,7 @@ class ExportController extends BaseController $data = [ 'account' => $account, 'title' => 'Invoice Ninja v' . NINJA_VERSION . ' - ' . $account->formatDateTime($account->getDateTime()), - 'multiUser' => $account->users->count() > 1 + 'multiUser' => $account->users->count() > 1, ]; if ($request->input('include') === 'all' || $request->input('clients')) { diff --git a/app/Http/Controllers/HomeController.php b/app/Http/Controllers/HomeController.php index 0d4c8b744569..7970e0fa4b94 100644 --- a/app/Http/Controllers/HomeController.php +++ b/app/Http/Controllers/HomeController.php @@ -1,19 +1,21 @@ -with('sign_up', Input::get('sign_up')); } else { return View::make('public.invoice_now'); @@ -85,6 +88,7 @@ class HomeController extends BaseController /** * @param $userType * @param $version + * * @return \Illuminate\Http\JsonResponse */ public function newsFeed($userType, $version) diff --git a/app/Http/Controllers/ImportController.php b/app/Http/Controllers/ImportController.php index 83bd79c225b2..6fde46cd1613 100644 --- a/app/Http/Controllers/ImportController.php +++ b/app/Http/Controllers/ImportController.php @@ -1,12 +1,14 @@ -importService->mapCSV($files); + return View::make('accounts.import_map', ['data' => $data]); } elseif ($source === IMPORT_JSON) { $results = $this->importService->importJSON($files[IMPORT_JSON]); + return $this->showResult($results); } else { $results = $this->importService->importFiles($source, $files); + return $this->showResult($results); } } catch (Exception $exception) { Utils::logError($exception); Session::flash('error', $exception->getMessage()); + return Redirect::to('/settings/' . ACCOUNT_IMPORT_EXPORT); } } @@ -61,10 +68,12 @@ class ImportController extends BaseController try { $results = $this->importService->importCSV($map, $headers); + return $this->showResult($results); } catch (Exception $exception) { Utils::logError($exception); Session::flash('error', $exception->getMessage()); + return Redirect::to('/settings/' . ACCOUNT_IMPORT_EXPORT); } } diff --git a/app/Http/Controllers/IntegrationController.php b/app/Http/Controllers/IntegrationController.php index cb1a905f3775..1437a215e8a6 100644 --- a/app/Http/Controllers/IntegrationController.php +++ b/app/Http/Controllers/IntegrationController.php @@ -1,13 +1,15 @@ -account_id) ->where('event_id', '=', $eventId)->first(); - if (!$subscription) { + if (! $subscription) { $subscription = new Subscription(); $subscription->account_id = Auth::user()->account_id; $subscription->event_id = $eventId; @@ -34,7 +36,7 @@ class IntegrationController extends Controller $subscription->target_url = trim(Input::get('target_url')); $subscription->save(); - if (!$subscription->id) { + if (! $subscription->id) { return Response::json('Failed to create subscription', 500); } diff --git a/app/Http/Controllers/InvoiceApiController.php b/app/Http/Controllers/InvoiceApiController.php index 0f68d5b6be74..21d3a940ea22 100644 --- a/app/Http/Controllers/InvoiceApiController.php +++ b/app/Http/Controllers/InvoiceApiController.php @@ -1,24 +1,26 @@ -listResponse($invoices); } - /** - * @SWG\Get( - * path="/invoices/{invoice_id}", - * summary="Individual Invoice", - * tags={"invoice"}, - * @SWG\Response( - * response=200, - * description="A single invoice", - * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ - + /** + * @SWG\Get( + * path="/invoices/{invoice_id}", + * summary="Individual Invoice", + * tags={"invoice"}, + * @SWG\Response( + * response=200, + * description="A single invoice", + * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function show(InvoiceRequest $request) { return $this->itemResponse($request->entity()); @@ -117,10 +118,11 @@ class InvoiceApiController extends BaseAPIController $query->where('email', '=', $email); })->first(); - if (!$client) { - $validator = Validator::make(['email'=>$email], ['email' => 'email']); + if (! $client) { + $validator = Validator::make(['email' => $email], ['email' => 'email']); if ($validator->fails()) { $messages = $validator->messages(); + return $messages->first(); } @@ -178,7 +180,7 @@ class InvoiceApiController extends BaseAPIController $payment = $this->paymentRepo->save([ 'invoice_id' => $invoice->id, 'client_id' => $client->id, - 'amount' => $data['paid'] + 'amount' => $data['paid'], ]); } } @@ -223,22 +225,22 @@ class InvoiceApiController extends BaseAPIController 'custom_value2' => 0, 'custom_taxes1' => false, 'custom_taxes2' => false, - 'partial' => 0 + 'partial' => 0, ]; - if (!isset($data['invoice_status_id']) || $data['invoice_status_id'] == 0) { + if (! isset($data['invoice_status_id']) || $data['invoice_status_id'] == 0) { $data['invoice_status_id'] = INVOICE_STATUS_DRAFT; } - if (!isset($data['invoice_date'])) { + if (! isset($data['invoice_date'])) { $fields['invoice_date_sql'] = date_create()->format('Y-m-d'); } - if (!isset($data['due_date'])) { + if (! isset($data['due_date'])) { $fields['due_date_sql'] = false; } foreach ($fields as $key => $val) { - if (!isset($data[$key])) { + if (! isset($data[$key])) { $data[$key] = $val; } } @@ -263,7 +265,7 @@ class InvoiceApiController extends BaseAPIController private function prepareItem($item) { // if only the product key is set we'll load the cost and notes - if (!empty($item['product_key']) && empty($item['cost']) && empty($item['notes'])) { + if (! empty($item['product_key']) && empty($item['cost']) && empty($item['notes'])) { $product = Product::findProductByKey($item['product_key']); if ($product) { if (empty($item['cost'])) { @@ -279,11 +281,11 @@ class InvoiceApiController extends BaseAPIController 'cost' => 0, 'product_key' => '', 'notes' => '', - 'qty' => 1 + 'qty' => 1, ]; foreach ($fields as $key => $val) { - if (!isset($item[$key])) { + if (! isset($item[$key])) { $item[$key] = $val; } } @@ -299,35 +301,37 @@ class InvoiceApiController extends BaseAPIController $response = json_encode(RESULT_SUCCESS, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); + return Response::make($response, 200, $headers); } - /** - * @SWG\Put( - * path="/invoices", - * tags={"invoice"}, - * summary="Update an invoice", - * @SWG\Parameter( - * in="body", - * name="body", - * @SWG\Schema(ref="#/definitions/Invoice") - * ), - * @SWG\Response( - * response=200, - * description="Update invoice", - * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ + /** + * @SWG\Put( + * path="/invoices", + * tags={"invoice"}, + * summary="Update an invoice", + * @SWG\Parameter( + * in="body", + * name="body", + * @SWG\Schema(ref="#/definitions/Invoice") + * ), + * @SWG\Response( + * response=200, + * description="Update invoice", + * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function update(UpdateInvoiceAPIRequest $request, $publicId) { if ($request->action == ACTION_CONVERT) { $quote = $request->entity(); $invoice = $this->invoiceRepo->cloneInvoice($quote, $quote->id); + return $this->itemResponse($invoice); } elseif ($request->action) { return $this->handleAction($request); @@ -344,28 +348,27 @@ class InvoiceApiController extends BaseAPIController return $this->itemResponse($invoice); } - /** - * @SWG\Delete( - * path="/invoices", - * tags={"invoice"}, - * summary="Delete an invoice", - * @SWG\Parameter( - * in="body", - * name="body", - * @SWG\Schema(ref="#/definitions/Invoice") - * ), - * @SWG\Response( - * response=200, - * description="Delete invoice", - * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ - + /** + * @SWG\Delete( + * path="/invoices", + * tags={"invoice"}, + * summary="Delete an invoice", + * @SWG\Parameter( + * in="body", + * name="body", + * @SWG\Schema(ref="#/definitions/Invoice") + * ), + * @SWG\Response( + * response=200, + * description="Delete invoice", + * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Invoice")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function destroy(UpdateInvoiceAPIRequest $request) { $invoice = $request->entity(); diff --git a/app/Http/Controllers/InvoiceController.php b/app/Http/Controllers/InvoiceController.php index 7dafc98576b8..c87cffef345d 100644 --- a/app/Http/Controllers/InvoiceController.php +++ b/app/Http/Controllers/InvoiceController.php @@ -1,34 +1,36 @@ -invoice_date = Utils::fromSqlDate($invoice->invoice_date); - $invoice->recurring_due_date = $invoice->due_date;// Keep in SQL form + $invoice->recurring_due_date = $invoice->due_date; // Keep in SQL form $invoice->due_date = Utils::fromSqlDate($invoice->due_date); $invoice->start_date = Utils::fromSqlDate($invoice->start_date); $invoice->end_date = Utils::fromSqlDate($invoice->end_date); @@ -124,7 +126,7 @@ class InvoiceController extends BaseController $lastSent = ($invoice->is_recurring && $invoice->last_sent_date) ? $invoice->recurring_invoices->last() : null; - if (!Auth::user()->hasPermission('view_all')) { + if (! Auth::user()->hasPermission('view_all')) { $clients = $clients->where('clients.user_id', '=', Auth::user()->id); } @@ -139,10 +141,10 @@ class InvoiceController extends BaseController 'title' => trans("texts.edit_{$entityType}"), 'client' => $invoice->client, 'isRecurring' => $invoice->is_recurring, - 'lastSent' => $lastSent]; + 'lastSent' => $lastSent, ]; $data = array_merge($data, self::getViewModel($invoice)); - if ($invoice->isSent() && $invoice->getAutoBillEnabled() && !$invoice->isPaid()) { + if ($invoice->isSent() && $invoice->getAutoBillEnabled() && ! $invoice->isPaid()) { $data['autoBillChangeWarning'] = $invoice->client->autoBillLater(); } @@ -193,7 +195,7 @@ class InvoiceController extends BaseController $invoice->public_id = 0; $clients = Client::scope()->with('contacts', 'country')->orderBy('name'); - if (!Auth::user()->hasPermission('view_all')) { + if (! Auth::user()->hasPermission('view_all')) { $clients = $clients->where('clients.user_id', '=', Auth::user()->id); } @@ -246,7 +248,7 @@ class InvoiceController extends BaseController trans('texts.use_client_terms') => ['value' => '', 'class' => 'monthly weekly'], ]; - $ends = ['th','st','nd','rd','th','th','th','th','th','th']; + $ends = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']; for ($i = 1; $i < 31; $i++) { if ($i >= 11 && $i <= 13) { $ordinal = $i. 'th'; @@ -255,13 +257,12 @@ class InvoiceController extends BaseController } $dayStr = str_pad($i, 2, '0', STR_PAD_LEFT); - $str = trans('texts.day_of_month', ['ordinal'=>$ordinal]); + $str = trans('texts.day_of_month', ['ordinal' => $ordinal]); $recurringDueDates[$str] = ['value' => "1998-01-$dayStr", 'data-num' => $i, 'class' => 'monthly']; } $recurringDueDates[trans('texts.last_day_of_month')] = ['value' => '1998-01-31', 'data-num' => 31, 'class' => 'monthly']; - $daysOfWeek = [ trans('texts.sunday'), trans('texts.monday'), @@ -271,11 +272,11 @@ class InvoiceController extends BaseController trans('texts.friday'), trans('texts.saturday'), ]; - foreach (['1st','2nd','3rd','4th'] as $i=>$ordinal) { - foreach ($daysOfWeek as $j=>$dayOfWeek) { + foreach (['1st', '2nd', '3rd', '4th'] as $i => $ordinal) { + foreach ($daysOfWeek as $j => $dayOfWeek) { $str = trans('texts.day_of_week_after', ['ordinal' => $ordinal, 'day' => $dayOfWeek]); - $day = $i * 7 + $j + 1; + $day = $i * 7 + $j + 1; $dayStr = str_pad($day, 2, '0', STR_PAD_LEFT); $recurringDueDates[$str] = ['value' => "1998-02-$dayStr", 'data-num' => $day, 'class' => 'weekly']; } @@ -288,7 +289,7 @@ class InvoiceController extends BaseController $defaultTax = false; foreach ($rates as $rate) { - $name = $rate->name . ' ' . ($rate->rate+0) . '%'; + $name = $rate->name . ' ' . ($rate->rate + 0) . '%'; if ($rate->is_inclusive) { $name .= ' - ' . trans('texts.inclusive'); } @@ -367,7 +368,8 @@ class InvoiceController extends BaseController /** * Update the specified resource in storage. * - * @param int $id + * @param int $id + * * @return Response */ public function update(UpdateInvoiceRequest $request) @@ -394,15 +396,15 @@ class InvoiceController extends BaseController return url($invoice->getRoute()); } - private function emailInvoice($invoice, $pdfUpload) { $entityType = $invoice->getEntityType(); $pdfUpload = Utils::decodePDF($pdfUpload); - if (!Auth::user()->confirmed) { + if (! Auth::user()->confirmed) { $errorMessage = trans(Auth::user()->registered ? 'texts.confirmation_required' : 'texts.registration_required'); Session::flash('error', $errorMessage); + return Redirect::to('invoices/'.$invoice->public_id.'/edit'); } @@ -425,10 +427,11 @@ class InvoiceController extends BaseController private function emailRecurringInvoice(&$invoice) { - if (!$invoice->shouldSendToday()) { + if (! $invoice->shouldSendToday()) { if ($date = $invoice->getNextSendDate()) { $date = $invoice->account->formatDate($date); $date .= ' ' . DEFAULT_SEND_RECURRING_HOUR . ':00 am ' . $invoice->account->getTimezone(); + return trans('texts.recurring_too_soon', ['date' => $date]); } else { return trans('texts.no_longer_running'); @@ -451,7 +454,8 @@ class InvoiceController extends BaseController /** * Display the specified resource. * - * @param int $id + * @param int $id + * * @return Response */ public function show($publicId) @@ -464,7 +468,8 @@ class InvoiceController extends BaseController /** * Remove the specified resource from storage. * - * @param int $id + * @param int $id + * * @return Response */ public function bulk($entityType = ENTITY_INVOICE) diff --git a/app/Http/Controllers/NinjaController.php b/app/Http/Controllers/NinjaController.php index b22e6b4d302b..3dce07391e98 100644 --- a/app/Http/Controllers/NinjaController.php +++ b/app/Http/Controllers/NinjaController.php @@ -1,20 +1,22 @@ - $input['city'], 'shippingState' => $input['state'], 'shippingPostcode' => $input['postal_code'], - 'shippingCountry' => $country->iso_3166_2 + 'shippingCountry' => $country->iso_3166_2, ]; $card = new CreditCard($data); @@ -79,7 +81,7 @@ class NinjaController extends BaseController 'card' => $card, 'currency' => 'USD', 'returnUrl' => URL::to('license_complete'), - 'cancelUrl' => URL::to('/') + 'cancelUrl' => URL::to('/'), ]; } @@ -100,11 +102,11 @@ class NinjaController extends BaseController if (Input::has('product_id')) { Session::set('product_id', Input::get('product_id')); - } elseif (!Session::has('product_id')) { + } elseif (! Session::has('product_id')) { Session::set('product_id', PRODUCT_ONE_CLICK_INSTALL); } - if (!Session::get('affiliate_id')) { + if (! Session::get('affiliate_id')) { return Utils::fatalError(); } @@ -190,8 +192,9 @@ class NinjaController extends BaseController $ref = $response->getTransactionReference(); - if (!$response->isSuccessful() || !$ref) { + if (! $response->isSuccessful() || ! $ref) { $this->error('License', $response->getMessage(), $accountGateway); + return redirect()->to('license')->withInput(); } } @@ -227,6 +230,7 @@ class NinjaController extends BaseController return View::make('public.license', $data); } catch (\Exception $e) { $this->error('License-Uncaught', false, $accountGateway, $e); + return redirect()->to('license')->withInput(); } } diff --git a/app/Http/Controllers/OnlinePaymentController.php b/app/Http/Controllers/OnlinePaymentController.php index b77f495d3057..4e22b008e049 100644 --- a/app/Http/Controllers/OnlinePaymentController.php +++ b/app/Http/Controllers/OnlinePaymentController.php @@ -1,30 +1,32 @@ -completeOffsitePurchase(Input::all())) { Session::flash('message', trans('texts.applied_payment')); } + return $this->completePurchase($invitation, true); } catch (Exception $exception) { return $this->error($paymentDriver, $exception); @@ -169,6 +175,7 @@ class OnlinePaymentController extends BaseController { if ($redirectUrl = session('redirect_url:' . $invitation->invitation_key)) { $separator = strpos($redirectUrl, '?') === false ? '?' : '&'; + return redirect()->to($redirectUrl . $separator . 'invoice_id=' . $invitation->invoice->public_id); } else { // Allow redirecting to iFrame for offsite payments @@ -184,6 +191,7 @@ class OnlinePaymentController extends BaseController * @param $paymentDriver * @param $exception * @param bool $showPayment + * * @return \Illuminate\Http\RedirectResponse */ private function error($paymentDriver, $exception, $showPayment = false) @@ -203,16 +211,18 @@ class OnlinePaymentController extends BaseController Utils::logError($message, 'PHP', true); $route = $showPayment ? 'payment/' : 'view/'; + return redirect()->to($route . $paymentDriver->invitation->invitation_key); } /** * @param $routingNumber + * * @return \Illuminate\Http\JsonResponse */ public function getBankInfo($routingNumber) { - if (strlen($routingNumber) != 9 || !preg_match('/\d{9}/', $routingNumber)) { + if (strlen($routingNumber) != 9 || ! preg_match('/\d{9}/', $routingNumber)) { return response()->json([ 'message' => 'Invalid routing number', ], 400); @@ -224,7 +234,7 @@ class OnlinePaymentController extends BaseController return response()->json([ 'message' => $data, ], 500); - } elseif (!empty($data)) { + } elseif (! empty($data)) { return response()->json($data); } @@ -236,6 +246,7 @@ class OnlinePaymentController extends BaseController /** * @param $accountKey * @param $gatewayId + * * @return \Illuminate\Http\JsonResponse */ public function handlePaymentWebhook($accountKey, $gatewayId) @@ -244,7 +255,7 @@ class OnlinePaymentController extends BaseController $account = Account::where('accounts.account_key', '=', $accountKey)->first(); - if (!$account) { + if (! $account) { return response()->json([ 'message' => 'Unknown account', ], 404); @@ -252,7 +263,7 @@ class OnlinePaymentController extends BaseController $accountGateway = $account->getGatewayConfig(intval($gatewayId)); - if (!$accountGateway) { + if (! $accountGateway) { return response()->json([ 'message' => 'Unknown gateway', ], 404); @@ -262,9 +273,11 @@ class OnlinePaymentController extends BaseController try { $result = $paymentDriver->handleWebHook(Input::all()); + return response()->json(['message' => $result]); } catch (Exception $exception) { Utils::logError($exception->getMessage(), 'PHP'); + return response()->json(['message' => $exception->getMessage()], 500); } } @@ -311,7 +324,7 @@ class OnlinePaymentController extends BaseController $data = [ 'currency_id' => $account->currency_id, - 'contact' => Input::all() + 'contact' => Input::all(), ]; $client = $clientRepo->save($data); } @@ -332,7 +345,7 @@ class OnlinePaymentController extends BaseController 'qty' => 1, 'tax_rate1' => $product->default_tax_rate ? $product->default_tax_rate->rate : 0, 'tax_name1' => $product->default_tax_rate ? $product->default_tax_rate->name : '', - ]] + ]], ]; $invoice = $invoiceService->save($data); if ($invoice->is_recurring) { diff --git a/app/Http/Controllers/PaymentApiController.php b/app/Http/Controllers/PaymentApiController.php index 7fddd7a0f4b9..78caf418e47e 100644 --- a/app/Http/Controllers/PaymentApiController.php +++ b/app/Http/Controllers/PaymentApiController.php @@ -1,13 +1,15 @@ -action) { @@ -84,7 +85,6 @@ class PaymentApiController extends BaseAPIController return $this->itemResponse($payment); } - /** * @SWG\Post( * path="/payments", @@ -121,27 +121,26 @@ class PaymentApiController extends BaseAPIController } /** - * @SWG\Delete( - * path="/payments/{payment_id}", - * summary="Delete a payment", - * tags={"payment"}, - * @SWG\Parameter( - * in="body", - * name="body", - * @SWG\Schema(ref="#/definitions/Payment") - * ), - * @SWG\Response( - * response=200, - * description="Delete payment", - * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ - + * @SWG\Delete( + * path="/payments/{payment_id}", + * summary="Delete a payment", + * tags={"payment"}, + * @SWG\Parameter( + * in="body", + * name="body", + * @SWG\Schema(ref="#/definitions/Payment") + * ), + * @SWG\Response( + * response=200, + * description="Delete payment", + * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Payment")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function destroy(UpdatePaymentRequest $request) { $payment = $request->entity(); diff --git a/app/Http/Controllers/PaymentController.php b/app/Http/Controllers/PaymentController.php index 622517555b85..67bc81238b5a 100644 --- a/app/Http/Controllers/PaymentController.php +++ b/app/Http/Controllers/PaymentController.php @@ -1,20 +1,22 @@ -paymentService->bulk($ids, $action, ['amount'=>$amount]); + $count = $this->paymentService->bulk($ids, $action, ['amount' => $amount]); if ($count > 0) { - $message = Utils::pluralize($action=='refund' ? 'refunded_payment':$action.'d_payment', $count); + $message = Utils::pluralize($action == 'refund' ? 'refunded_payment' : $action.'d_payment', $count); Session::flash('message', $message); } diff --git a/app/Http/Controllers/PaymentTermController.php b/app/Http/Controllers/PaymentTermController.php index d5178099984c..65037b0f088b 100644 --- a/app/Http/Controllers/PaymentTermController.php +++ b/app/Http/Controllers/PaymentTermController.php @@ -1,13 +1,15 @@ -name = trim(Input::get('name')); - $paymentTerm->num_days = Utils::parseInt(Input::get('num_days')); + $paymentTerm->name = trim(Input::get('name')); + $paymentTerm->num_days = Utils::parseInt(Input::get('num_days')); $paymentTerm->save(); $message = $publicId ? trans('texts.updated_payment_term') : trans('texts.created_payment_term'); @@ -119,8 +125,8 @@ class PaymentTermController extends BaseController public function bulk() { $action = Input::get('bulk_action'); - $ids = Input::get('bulk_public_id'); - $count = $this->paymentTermService->bulk($ids, $action); + $ids = Input::get('bulk_public_id'); + $count = $this->paymentTermService->bulk($ids, $action); Session::flash('message', trans('texts.archived_payment_term')); diff --git a/app/Http/Controllers/ProductApiController.php b/app/Http/Controllers/ProductApiController.php index f0a0b8af43e4..39b398008731 100644 --- a/app/Http/Controllers/ProductApiController.php +++ b/app/Http/Controllers/ProductApiController.php @@ -1,12 +1,14 @@ -invoiceRepo = $invoiceRepo; } - /** - * @SWG\Get( - * path="/quotes", - * tags={"quote"}, - * summary="List of quotes", - * @SWG\Response( - * response=200, - * description="A list with quotes", - * @SWG\Schema(type="array", @SWG\Items(ref="#/definitions/Invoice")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ + /** + * @SWG\Get( + * path="/quotes", + * tags={"quote"}, + * summary="List of quotes", + * @SWG\Response( + * response=200, + * description="A list with quotes", + * @SWG\Schema(type="array", @SWG\Items(ref="#/definitions/Invoice")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function index() { $invoices = Invoice::scope() diff --git a/app/Http/Controllers/QuoteController.php b/app/Http/Controllers/QuoteController.php index 480169ed4458..244c38c6193b 100644 --- a/app/Http/Controllers/QuoteController.php +++ b/app/Http/Controllers/QuoteController.php @@ -1,26 +1,28 @@ -rate . ' ' . $rate->name] = $rate->name . ' ' . ($rate->rate+0) . '%'; + $options[$rate->rate . ' ' . $rate->name] = $rate->name . ' ' . ($rate->rate + 0) . '%'; // load default invoice tax if ($rate->id == $account->default_tax_rate_id) { @@ -138,6 +140,7 @@ class QuoteController extends BaseController $clone = $this->invoiceService->convertQuote($invoice); Session::flash('message', trans('texts.converted_to_invoice')); + return Redirect::to('invoices/'.$clone->public_id); } diff --git a/app/Http/Controllers/RecurringInvoiceController.php b/app/Http/Controllers/RecurringInvoiceController.php index 95aa97a1fcdc..2b1cc2977361 100644 --- a/app/Http/Controllers/RecurringInvoiceController.php +++ b/app/Http/Controllers/RecurringInvoiceController.php @@ -1,10 +1,12 @@ - $versionInstalled, 'versionAvailable' => $this->updater->source()->getVersionAvailable(), - 'updateAvailable' => $updateAvailable + 'updateAvailable' => $updateAvailable, ] ); } /** - * Run the actual update + * Run the actual update. * * @return \Illuminate\Http\RedirectResponse */ diff --git a/app/Http/Controllers/TaskApiController.php b/app/Http/Controllers/TaskApiController.php index 10c2936190c7..ca24c03941d7 100644 --- a/app/Http/Controllers/TaskApiController.php +++ b/app/Http/Controllers/TaskApiController.php @@ -1,12 +1,14 @@ -response($data); } - - /** * @SWG\Put( * path="/task/{task_id}", @@ -109,7 +109,6 @@ class TaskApiController extends BaseAPIController * ) * ) */ - public function update(UpdateTaskRequest $request) { $task = $request->entity(); diff --git a/app/Http/Controllers/TaskController.php b/app/Http/Controllers/TaskController.php index fe1809b876bf..412aeb67cec6 100644 --- a/app/Http/Controllers/TaskController.php +++ b/app/Http/Controllers/TaskController.php @@ -1,26 +1,28 @@ -trashed()) { + if (! $task->trashed()) { $actions[] = ['url' => 'javascript:submitAction("archive")', 'label' => trans('texts.archive_task')]; $actions[] = ['url' => 'javascript:onDeleteClick()', 'label' => trans('texts.delete_task')]; } else { @@ -214,6 +219,7 @@ class TaskController extends BaseController /** * @param null $publicId + * * @return \Illuminate\Http\RedirectResponse */ private function save($publicId = null) @@ -250,6 +256,7 @@ class TaskController extends BaseController if ($action == 'stop') { $this->taskRepo->save($ids, ['action' => $action]); Session::flash('message', trans('texts.stopped_task')); + return Redirect::to('tasks'); } elseif ($action == 'invoice' || $action == 'add_to_invoice') { $tasks = Task::scope($ids)->with('client')->orderBy('project_id', 'id')->get(); @@ -259,19 +266,22 @@ class TaskController extends BaseController $lastProjectId = false; foreach ($tasks as $task) { if ($task->client) { - if (!$clientPublicId) { + if (! $clientPublicId) { $clientPublicId = $task->client->public_id; } elseif ($clientPublicId != $task->client->public_id) { Session::flash('error', trans('texts.task_error_multiple_clients')); + return Redirect::to('tasks'); } } if ($task->is_running) { Session::flash('error', trans('texts.task_error_running')); + return Redirect::to('tasks'); } elseif ($task->invoice_id) { Session::flash('error', trans('texts.task_error_invoiced')); + return Redirect::to('tasks'); } @@ -289,6 +299,7 @@ class TaskController extends BaseController return Redirect::to("invoices/create/{$clientPublicId}")->with('tasks', $data); } else { $invoiceId = Input::get('invoice_id'); + return Redirect::to("invoices/{$invoiceId}/edit")->with('tasks', $data); } } else { @@ -303,7 +314,7 @@ class TaskController extends BaseController private function checkTimezone() { - if (!Auth::user()->account->timezone) { + if (! Auth::user()->account->timezone) { $link = link_to('/settings/localization?focus=timezone_id', trans('texts.click_here'), ['target' => '_blank']); Session::flash('warning', trans('texts.timezone_unset', ['link' => $link])); } diff --git a/app/Http/Controllers/TaxRateApiController.php b/app/Http/Controllers/TaxRateApiController.php index 2fa442af49b2..128c1db5229a 100644 --- a/app/Http/Controllers/TaxRateApiController.php +++ b/app/Http/Controllers/TaxRateApiController.php @@ -1,9 +1,11 @@ -taxRateRepo->save($request->input()); Session::flash('message', trans('texts.created_tax_rate')); + return Redirect::to('settings/' . ACCOUNT_TAX_RATES); } @@ -72,10 +75,10 @@ class TaxRateController extends BaseController $this->taxRateRepo->save($request->input(), $request->entity()); Session::flash('message', trans('texts.updated_tax_rate')); + return Redirect::to('settings/' . ACCOUNT_TAX_RATES); } - public function bulk() { $action = Input::get('bulk_action'); diff --git a/app/Http/Controllers/TokenController.php b/app/Http/Controllers/TokenController.php index 742218ed065b..414151fd3ee2 100644 --- a/app/Http/Controllers/TokenController.php +++ b/app/Http/Controllers/TokenController.php @@ -1,17 +1,19 @@ -save(); } - /** * @return \Illuminate\Contracts\View\View */ @@ -113,9 +117,9 @@ class TokenController extends BaseController return Redirect::to('settings/' . ACCOUNT_API_TOKENS); } - /** * @param bool $tokenPublicId + * * @return $this|\Illuminate\Http\RedirectResponse */ public function save($tokenPublicId = false) diff --git a/app/Http/Controllers/UserApiController.php b/app/Http/Controllers/UserApiController.php index 3bb82b13fdc2..64365c910ec5 100644 --- a/app/Http/Controllers/UserApiController.php +++ b/app/Http/Controllers/UserApiController.php @@ -1,12 +1,14 @@ -registered) { Session::flash('error', trans('texts.register_to_add_user')); + return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT); } if (! Auth::user()->confirmed) { Session::flash('error', trans('texts.confirmation_required')); + return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT); } if (Utils::isNinja() && ! Auth::user()->caddAddUsers()) { Session::flash('error', trans('texts.max_users_reached')); + return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT); } @@ -146,8 +150,7 @@ class UserController extends BaseController } /** - * Stores new account - * + * Stores new account. */ public function save($userPublicId = false) { @@ -205,7 +208,7 @@ class UserController extends BaseController $user->save(); - if (!$user->confirmed) { + if (! $user->confirmed) { $this->userMailer->sendConfirmation($user, Auth::user()); $message = trans('texts.sent_invite'); } else { @@ -229,9 +232,8 @@ class UserController extends BaseController return Redirect::to('settings/' . ACCOUNT_USER_MANAGEMENT); } - /** - * Attempt to confirm account with code + * Attempt to confirm account with code. * * @param string $code */ @@ -249,6 +251,7 @@ class UserController extends BaseController if ($user->public_id) { Auth::logout(); $token = Password::getRepository()->create($user); + return Redirect::to("/password/reset/{$token}"); } else { if (Auth::check()) { @@ -261,6 +264,7 @@ class UserController extends BaseController } else { $url = '/login'; } + return Redirect::to($url)->with('message', $notice_msg); } } else { @@ -273,9 +277,9 @@ class UserController extends BaseController public function changePassword() { // check the current password is correct - if (!Auth::validate([ + if (! Auth::validate([ 'email' => Auth::user()->email, - 'password' => Input::get('current_password') + 'password' => Input::get('current_password'), ])) { return trans('texts.password_error_incorrect'); } @@ -347,6 +351,7 @@ class UserController extends BaseController Session::put(SESSION_USER_ACCOUNTS, $users); Session::flash('message', trans('texts.unlinked_account')); + return Redirect::to('/manage_companies'); } diff --git a/app/Http/Controllers/VendorApiController.php b/app/Http/Controllers/VendorApiController.php index b88c5831afcc..24ea7601166d 100644 --- a/app/Http/Controllers/VendorApiController.php +++ b/app/Http/Controllers/VendorApiController.php @@ -1,14 +1,16 @@ -itemResponse($vendor); } - /** - * @SWG\Put( - * path="/vendors/{vendor_id}", - * tags={"vendor"}, - * summary="Update a vendor", - * @SWG\Parameter( - * in="body", - * name="body", - * @SWG\Schema(ref="#/definitions/Vendor") - * ), - * @SWG\Response( - * response=200, - * description="Update vendor", - * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ - + /** + * @SWG\Put( + * path="/vendors/{vendor_id}", + * tags={"vendor"}, + * summary="Update a vendor", + * @SWG\Parameter( + * in="body", + * name="body", + * @SWG\Schema(ref="#/definitions/Vendor") + * ), + * @SWG\Response( + * response=200, + * description="Update vendor", + * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function update(UpdateVendorRequest $request, $publicId) { if ($request->action) { @@ -124,29 +125,27 @@ class VendorApiController extends BaseAPIController return $this->itemResponse($vendor); } - - /** - * @SWG\Delete( - * path="/vendors/{vendor_id}", - * tags={"vendor"}, - * summary="Delete a vendor", - * @SWG\Parameter( - * in="body", - * name="body", - * @SWG\Schema(ref="#/definitions/Vendor") - * ), - * @SWG\Response( - * response=200, - * description="Delete vendor", - * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor")) - * ), - * @SWG\Response( - * response="default", - * description="an ""unexpected"" error" - * ) - * ) - */ - + /** + * @SWG\Delete( + * path="/vendors/{vendor_id}", + * tags={"vendor"}, + * summary="Delete a vendor", + * @SWG\Parameter( + * in="body", + * name="body", + * @SWG\Schema(ref="#/definitions/Vendor") + * ), + * @SWG\Response( + * response=200, + * description="Delete vendor", + * @SWG\Schema(type="object", @SWG\Items(ref="#/definitions/Vendor")) + * ), + * @SWG\Response( + * response="default", + * description="an ""unexpected"" error" + * ) + * ) + */ public function destroy(VendorRequest $request) { $vendor = $request->entity(); diff --git a/app/Http/Controllers/VendorController.php b/app/Http/Controllers/VendorController.php index bc16ee9e407c..e89c0028f738 100644 --- a/app/Http/Controllers/VendorController.php +++ b/app/Http/Controllers/VendorController.php @@ -1,21 +1,23 @@ -entity(); $actionLinks = [ - ['label' => trans('texts.new_vendor'), 'url' => URL::to('/vendors/create/' . $vendor->public_id)] + ['label' => trans('texts.new_vendor'), 'url' => URL::to('/vendors/create/' . $vendor->public_id)], ]; $data = [ - 'actionLinks' => $actionLinks, - 'showBreadcrumbs' => false, - 'vendor' => $vendor, - 'title' => trans('texts.view_vendor'), - 'hasRecurringInvoices' => false, - 'hasQuotes' => false, - 'hasTasks' => false, + 'actionLinks' => $actionLinks, + 'showBreadcrumbs' => false, + 'vendor' => $vendor, + 'title' => trans('texts.view_vendor'), + 'hasRecurringInvoices' => false, + 'hasQuotes' => false, + 'hasTasks' => false, ]; return View::make('vendors.show', $data); @@ -117,7 +120,8 @@ class VendorController extends BaseController /** * Show the form for editing the specified resource. * - * @param int $id + * @param int $id + * * @return Response */ public function edit(VendorRequest $request) @@ -155,7 +159,8 @@ class VendorController extends BaseController /** * Update the specified resource in storage. * - * @param int $id + * @param int $id + * * @return Response */ public function update(UpdateVendorRequest $request) diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 50eaea9c8aec..46a45d9ca6d6 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -1,10 +1,11 @@ -is('api/v1/login') @@ -41,7 +43,8 @@ class ApiCheck // check API secret if (! $hasApiSecret) { sleep(ERROR_DELAY); - $error['error'] = ['message'=>'Invalid value for API_SECRET']; + $error['error'] = ['message' => 'Invalid value for API_SECRET']; + return Response::json($error, 403, $headers); } } else { @@ -54,24 +57,26 @@ class ApiCheck Session::set('token_id', $token->id); } else { sleep(ERROR_DELAY); - $error['error'] = ['message'=>'Invalid token']; + $error['error'] = ['message' => 'Invalid token']; + return Response::json($error, 403, $headers); } } - if (!Utils::isNinja() && !$loggingIn) { + if (! Utils::isNinja() && ! $loggingIn) { return $next($request); } - if (!Utils::hasFeature(FEATURE_API) && !$hasApiSecret) { - $error['error'] = ['message'=>'API requires pro plan']; + if (! Utils::hasFeature(FEATURE_API) && ! $hasApiSecret) { + $error['error'] = ['message' => 'API requires pro plan']; + return Response::json($error, 403, $headers); } else { $key = Auth::check() ? Auth::user()->account->id : $request->getClientIp(); // http://stackoverflow.com/questions/1375501/how-do-i-throttle-my-sites-api-users $hour = 60 * 60; - $hour_limit = 100; # users are limited to 100 requests/hour + $hour_limit = 100; // users are limited to 100 requests/hour $hour_throttle = Cache::get("hour_throttle:{$key}", null); $last_api_request = Cache::get("last_api_request:{$key}", 0); $last_api_diff = time() - $last_api_request; @@ -89,6 +94,7 @@ class ApiCheck if ($new_hour_throttle > $hour) { $wait = ceil($new_hour_throttle - $hour); sleep(1); + return Response::json("Please wait {$wait} second(s)", 403, $headers); } diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index de82df62aea2..d4592dae23af 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -1,22 +1,25 @@ -check(); if ($guard == 'client') { - if (!empty($request->invitation_key)) { + if (! empty($request->invitation_key)) { $contact_key = session('contact_key'); if ($contact_key) { $contact = $this->getContact($contact_key); $invitation = $this->getInvitation($request->invitation_key); - if (!$invitation) { + if (! $invitation) { return response()->view('error', [ 'error' => trans('texts.invoice_not_found'), 'hideHeader' => true, @@ -46,7 +49,7 @@ class Authenticate } } - if (!empty($request->contact_key)) { + if (! empty($request->contact_key)) { $contact_key = $request->contact_key; Session::put('contact_key', $contact_key); } else { @@ -55,7 +58,7 @@ class Authenticate if ($contact_key) { $contact = $this->getContact($contact_key); - } elseif (!empty($request->invitation_key)) { + } elseif (! empty($request->invitation_key)) { $invitation = $this->getInvitation($request->invitation_key); $contact = $invitation->contact; Session::put('contact_key', $contact->contact_key); @@ -70,16 +73,16 @@ class Authenticate } // Does this account require portal passwords? - if ($account && (!$account->enable_portal_password || !$account->hasFeature(FEATURE_CLIENT_PORTAL_PASSWORD))) { + if ($account && (! $account->enable_portal_password || ! $account->hasFeature(FEATURE_CLIENT_PORTAL_PASSWORD))) { $authenticated = true; } - if (!$authenticated && $contact && !$contact->password) { + if (! $authenticated && $contact && ! $contact->password) { $authenticated = true; } } - if (!$authenticated) { + if (! $authenticated) { if ($request->ajax()) { return response('Unauthorized.', 401); } else { @@ -92,12 +95,13 @@ class Authenticate /** * @param $key + * * @return \Illuminate\Database\Eloquent\Model|null|static */ protected function getInvitation($key) { $invitation = Invitation::withTrashed()->where('invitation_key', '=', $key)->first(); - if ($invitation && !$invitation->is_deleted) { + if ($invitation && ! $invitation->is_deleted) { return $invitation; } else { return null; @@ -106,12 +110,13 @@ class Authenticate /** * @param $key + * * @return \Illuminate\Database\Eloquent\Model|null|static */ protected function getContact($key) { $contact = Contact::withTrashed()->where('contact_key', '=', $key)->first(); - if ($contact && !$contact->is_deleted) { + if ($contact && ! $contact->is_deleted) { return $contact; } else { return null; diff --git a/app/Http/Middleware/DuplicateSubmissionCheck.php b/app/Http/Middleware/DuplicateSubmissionCheck.php index f92a31a48398..dc8ae4004acc 100644 --- a/app/Http/Middleware/DuplicateSubmissionCheck.php +++ b/app/Http/Middleware/DuplicateSubmissionCheck.php @@ -1,16 +1,19 @@ -getAction(); // Check if we have any permissions to check the user has. - if ($permissions = !empty($actions['permissions']) ? $actions['permissions'] : null) { - if (!Auth::user($guard)->hasPermission($permissions, !empty($actions['permissions_require_all']))) { + if ($permissions = ! empty($actions['permissions']) ? $actions['permissions'] : null) { + if (! Auth::user($guard)->hasPermission($permissions, ! empty($actions['permissions_require_all']))) { return response('Unauthorized.', 401); } } @@ -44,7 +45,7 @@ class PermissionsRequired $action = explode('@', $request->route()->getActionName()); if (isset(static::$actions[$action[0]]) && isset(static::$actions[$action[0]][$action[1]])) { $controller_permissions = static::$actions[$action[0]][$action[1]]; - if (!Auth::user($guard)->hasPermission($controller_permissions)) { + if (! Auth::user($guard)->hasPermission($controller_permissions)) { return response('Unauthorized.', 401); } } @@ -53,10 +54,10 @@ class PermissionsRequired } /** - * add a controller's action permission + * add a controller's action permission. * * @param Controller $controller - * @param array $permissions + * @param array $permissions */ public static function addPermission(Controller $controller, array $permissions) { diff --git a/app/Http/Middleware/QueryLogging.php b/app/Http/Middleware/QueryLogging.php index 1bc8160dff7c..c0a4852c69ae 100644 --- a/app/Http/Middleware/QueryLogging.php +++ b/app/Http/Middleware/QueryLogging.php @@ -1,21 +1,24 @@ -secure()) { + if (Utils::requireHTTPS() && ! $request->secure()) { return Redirect::secure($request->path()); } // If the database doens't yet exist we'll skip the rest - if (!Utils::isNinja() && !Utils::isDatabaseSetup()) { + if (! Utils::isNinja() && ! Utils::isDatabaseSetup()) { return $next($request); } // Check if a new version was installed - if (!Utils::isNinja()) { + if (! Utils::isNinja()) { $file = storage_path() . '/version.txt'; $version = @file_get_contents($file); if ($version != NINJA_VERSION) { @@ -58,6 +61,7 @@ class StartupCheck $handle = fopen($file, 'w'); fwrite($handle, NINJA_VERSION); fclose($handle); + return Redirect::to('/update'); } } @@ -67,7 +71,7 @@ class StartupCheck $count = Session::get(SESSION_COUNTER, 0); Session::put(SESSION_COUNTER, ++$count); - if (isset($_SERVER['REQUEST_URI']) && !Utils::startsWith($_SERVER['REQUEST_URI'], '/news_feed') && !Session::has('news_feed_id')) { + if (isset($_SERVER['REQUEST_URI']) && ! Utils::startsWith($_SERVER['REQUEST_URI'], '/news_feed') && ! Session::has('news_feed_id')) { $data = false; if (Utils::isNinja()) { $data = Utils::getNewsFeedResponse(); @@ -117,7 +121,7 @@ class StartupCheck } // Make sure the account/user localization settings are in the session - if (Auth::check() && !Session::has(SESSION_TIMEZONE)) { + if (Auth::check() && ! Session::has(SESSION_TIMEZONE)) { Event::fire(new UserLoggedIn()); } @@ -168,9 +172,9 @@ class StartupCheck Session::flash('message', 'Cache cleared'); } foreach ($cachedTables as $name => $class) { - if (Input::has('clear_cache') || !Cache::has($name)) { + if (Input::has('clear_cache') || ! Cache::has($name)) { // check that the table exists in case the migration is pending - if (! Schema::hasTable((new $class)->getTable())) { + if (! Schema::hasTable((new $class())->getTable())) { continue; } if ($name == 'paymentTerms') { diff --git a/app/Http/Middleware/VerifyCsrfToken.php b/app/Http/Middleware/VerifyCsrfToken.php index 3fbef6812658..2a8b178f5952 100644 --- a/app/Http/Middleware/VerifyCsrfToken.php +++ b/app/Http/Middleware/VerifyCsrfToken.php @@ -1,14 +1,15 @@ -user()->can('create', ENTITY_PAYMENT); diff --git a/app/Http/Requests/CreatePaymentRequest.php b/app/Http/Requests/CreatePaymentRequest.php index cd7345e9eb5b..f2e1d468419a 100644 --- a/app/Http/Requests/CreatePaymentRequest.php +++ b/app/Http/Requests/CreatePaymentRequest.php @@ -1,4 +1,6 @@ -entity()) { if ($this->user()->can('view', $this->entity())) { HistoryUtils::trackViewed($this->entity()); + return true; } } else { diff --git a/app/Http/Requests/ExpenseCategoryRequest.php b/app/Http/Requests/ExpenseCategoryRequest.php index 47a05b83dd56..55f2ee78791a 100644 --- a/app/Http/Requests/ExpenseCategoryRequest.php +++ b/app/Http/Requests/ExpenseCategoryRequest.php @@ -1,4 +1,6 @@ -req = $req; } - public function authorize() { return true; @@ -43,14 +43,14 @@ class RegisterRequest extends Request public function response(array $errors) { /* If the user is not validating from a mobile app - pass through parent::response */ - if (!isset($this->req->api_secret)) { + if (! isset($this->req->api_secret)) { return parent::response($errors); } /* If the user is validating from a mobile app - pass through first error string and return error */ foreach ($errors as $error) { foreach ($error as $key => $value) { - $message['error'] = ['message'=>$value]; + $message['error'] = ['message' => $value]; $message = json_encode($message, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); diff --git a/app/Http/Requests/Request.php b/app/Http/Requests/Request.php index 7fa613457e26..4ce91b8540c4 100644 --- a/app/Http/Requests/Request.php +++ b/app/Http/Requests/Request.php @@ -1,20 +1,22 @@ - $value) { - $message['error'] = ['message'=>$value]; + $message['error'] = ['message' => $value]; $message = json_encode($message, JSON_PRETTY_PRINT); $headers = Utils::getApiHeaders(); diff --git a/app/Http/Requests/SaveClientPortalSettings.php b/app/Http/Requests/SaveClientPortalSettings.php index 6503ce86aa4e..7886722ae2f6 100644 --- a/app/Http/Requests/SaveClientPortalSettings.php +++ b/app/Http/Requests/SaveClientPortalSettings.php @@ -1,7 +1,9 @@ - 'auth:client'], function () { Route::get('client/documents/{invitation_key}/{documents}/{filename?}', 'ClientPortalController@getDocument'); Route::get('client/documents/{invitation_key}/{filename?}', 'ClientPortalController@getInvoiceDocumentsZip'); - Route::get('api/client.quotes', ['as'=>'api.client.quotes', 'uses'=>'ClientPortalController@quoteDatatable']); - Route::get('api/client.credits', ['as'=>'api.client.credits', 'uses'=>'ClientPortalController@creditDatatable']); - Route::get('api/client.invoices', ['as'=>'api.client.invoices', 'uses'=>'ClientPortalController@invoiceDatatable']); - Route::get('api/client.recurring_invoices', ['as'=>'api.client.recurring_invoices', 'uses'=>'ClientPortalController@recurringInvoiceDatatable']); - Route::get('api/client.documents', ['as'=>'api.client.documents', 'uses'=>'ClientPortalController@documentDatatable']); - Route::get('api/client.payments', ['as'=>'api.client.payments', 'uses'=>'ClientPortalController@paymentDatatable']); - Route::get('api/client.activity', ['as'=>'api.client.activity', 'uses'=>'ClientPortalController@activityDatatable']); + Route::get('api/client.quotes', ['as' => 'api.client.quotes', 'uses' => 'ClientPortalController@quoteDatatable']); + Route::get('api/client.credits', ['as' => 'api.client.credits', 'uses' => 'ClientPortalController@creditDatatable']); + Route::get('api/client.invoices', ['as' => 'api.client.invoices', 'uses' => 'ClientPortalController@invoiceDatatable']); + Route::get('api/client.recurring_invoices', ['as' => 'api.client.recurring_invoices', 'uses' => 'ClientPortalController@recurringInvoiceDatatable']); + Route::get('api/client.documents', ['as' => 'api.client.documents', 'uses' => 'ClientPortalController@documentDatatable']); + Route::get('api/client.payments', ['as' => 'api.client.payments', 'uses' => 'ClientPortalController@paymentDatatable']); + Route::get('api/client.activity', ['as' => 'api.client.activity', 'uses' => 'ClientPortalController@activityDatatable']); }); - Route::get('license', 'NinjaController@show_license_payment'); Route::post('license', 'NinjaController@do_license_payment'); Route::get('claim_license', 'NinjaController@claim_license'); @@ -102,7 +100,6 @@ Route::post('/client/recover_password', ['as' => 'forgot', 'uses' => 'ClientAuth Route::get('/client/password/reset/{invitation_key}/{token}', ['as' => 'forgot', 'uses' => 'ClientAuth\PasswordController@getReset']); Route::post('/client/password/reset', ['as' => 'forgot', 'uses' => 'ClientAuth\PasswordController@postReset']); - if (Utils::isNinja()) { Route::post('/signup/register', 'AccountController@doRegister'); Route::get('/news_feed/{user_type}/{version}/', 'HomeController@newsFeed'); @@ -192,11 +189,9 @@ Route::group(['middleware' => 'auth:user'], function () { Route::resource('products', 'ProductController'); Route::post('products/bulk', 'ProductController@bulk'); - Route::get('/resend_confirmation', 'AccountController@resendConfirmation'); Route::post('/update_setup', 'AppController@updateSetup'); - // vendor Route::resource('vendors', 'VendorController'); Route::get('api/vendors', 'VendorController@getDatatable'); @@ -353,7 +348,6 @@ Route::get('/comments/feed', function () { return Redirect::to(NINJA_WEB_URL.'/comments/feed', 301); }); - /* if (Utils::isNinjaDev()) { diff --git a/app/Includes/parsecsv.lib.php b/app/Includes/parsecsv.lib.php index 8d47887d7a8c..c57506646963 100644 --- a/app/Includes/parsecsv.lib.php +++ b/app/Includes/parsecsv.lib.php @@ -2,8 +2,7 @@ class parseCSV { - -/* + /* Class: parseCSV v0.3.2 http://code.google.com/p/parsecsv-for-php/ @@ -79,79 +78,78 @@ class parseCSV */ - /** * Configuration - * - set these options with $object->var_name = 'value'; + * - set these options with $object->var_name = 'value';. */ - # use first line/entry as field names + // use first line/entry as field names public $heading = true; - # override field names + // override field names public $fields = []; - # sort entries by this field + // sort entries by this field public $sort_by = null; public $sort_reverse = false; - # delimiter (comma) and enclosure (double quote) + // delimiter (comma) and enclosure (double quote) public $delimiter = ','; public $enclosure = '"'; - # basic SQL-like conditions for row matching + // basic SQL-like conditions for row matching public $conditions = null; - # number of rows to ignore from beginning of data + // number of rows to ignore from beginning of data public $offset = null; - # limits the number of returned rows to specified amount + // limits the number of returned rows to specified amount public $limit = null; - # number of rows to analyze when attempting to auto-detect delimiter + // number of rows to analyze when attempting to auto-detect delimiter public $auto_depth = 15; - # characters to ignore when attempting to auto-detect delimiter + // characters to ignore when attempting to auto-detect delimiter public $auto_non_chars = "a-zA-Z0-9\n\r"; - # preferred delimiter characters, only used when all filtering method - # returns multiple possible delimiters (happens very rarely) + // preferred delimiter characters, only used when all filtering method + // returns multiple possible delimiters (happens very rarely) public $auto_preferred = ",;\t.:|"; - # character encoding options + // character encoding options public $convert_encoding = false; public $input_encoding = 'ISO-8859-1'; public $output_encoding = 'ISO-8859-1'; - # used by unparse(), save(), and output() functions + // used by unparse(), save(), and output() functions public $linefeed = "\r\n"; - # only used by output() function + // only used by output() function public $output_delimiter = ','; public $output_filename = 'data.csv'; - /** - * Internal variables + * Internal variables. */ - # current file + // current file public $file; - # loaded file contents + // loaded file contents public $file_data; - # array of field values in data parsed + // array of field values in data parsed public $titles = []; - # two dimentional array of CSV data + // two dimentional array of CSV data public $data = []; - /** - * Constructor + * Constructor. + * * @param input CSV file or string - * @return nothing + * + * @return nothing */ public function __construct($input = null, $offset = null, $limit = null, $conditions = null) { @@ -164,24 +162,25 @@ class parseCSV if (count($conditions) > 0) { $this->conditions = $conditions; } - if (!empty($input)) { + if (! empty($input)) { $this->parse($input); } } - // ============================================== // ----- [ Main Functions ] --------------------- // ============================================== /** - * Parse CSV file or string + * Parse CSV file or string. + * * @param input CSV file or string - * @return nothing + * + * @return nothing */ public function parse($input = null, $offset = null, $limit = null, $conditions = null) { - if (!empty($input)) { + if (! empty($input)) { if ($offset !== null) { $this->offset = $offset; } @@ -201,35 +200,41 @@ class parseCSV return false; } } + return true; } /** - * Save changes, or new file and/or data + * Save changes, or new file and/or data. + * * @param file file to save to * @param data 2D array with data * @param append append current data to end of target CSV if exists * @param fields field names - * @return true or false + * + * @return true or false */ public function save($file = null, $data = [], $append = false, $fields = []) { if (empty($file)) { $file = &$this->file; } - $mode = ($append) ? 'at' : 'wt' ; - $is_php = (preg_match('/\.php$/i', $file)) ? true : false ; + $mode = ($append) ? 'at' : 'wt'; + $is_php = (preg_match('/\.php$/i', $file)) ? true : false; + return $this->_wfile($file, $this->unparse($data, $fields, $append, $is_php), $mode); } /** - * Generate CSV based string for output + * Generate CSV based string for output. + * * @param output if true, prints headers and strings to browser * @param filename filename sent to browser in headers if output is true * @param data 2D array with data * @param fields field names * @param delimiter delimiter used to separate data - * @return CSV data using delimiter of choice, or default + * + * @return CSV data using delimiter of choice, or default */ public function output($output = true, $filename = null, $data = [], $fields = [], $delimiter = null) { @@ -245,14 +250,17 @@ class parseCSV header('Content-Disposition: inline; filename="'.$filename.'"'); echo $data; } + return $data; } /** - * Convert character encoding + * Convert character encoding. + * * @param input input character encoding, uses default if left blank * @param output output character encoding, uses default if left blank - * @return nothing + * + * @return nothing */ public function encoding($input = null, $output = null) { @@ -267,13 +275,15 @@ class parseCSV /** * Auto-Detect Delimiter: Find delimiter by analyzing a specific number of - * rows to determine most probable delimiter character + * rows to determine most probable delimiter character. + * * @param file local CSV file * @param parse true/false parse file directly * @param search_depth number of rows to analyze * @param preferred preferred delimiter characters * @param enclosure enclosure character, default is double quote ("). - * @return delimiter character + * + * @return delimiter character */ public function auto($file = null, $parse = true, $search_depth = null, $preferred = null, $enclosure = null) { @@ -308,21 +318,21 @@ class parseCSV $to_end = true; // walk specific depth finding posssible delimiter characters - for ($i=0; $i < $strlen; $i++) { + for ($i = 0; $i < $strlen; $i++) { $ch = $data{$i}; - $nch = (isset($data{$i+1})) ? $data{$i+1} : false ; - $pch = (isset($data{$i-1})) ? $data{$i-1} : false ; + $nch = (isset($data{$i + 1})) ? $data{$i + 1} : false; + $pch = (isset($data{$i - 1})) ? $data{$i - 1} : false; // open and closing quotes - if ($ch == $enclosure && (!$enclosed || $nch != $enclosure)) { - $enclosed = ($enclosed) ? false : true ; + if ($ch == $enclosure && (! $enclosed || $nch != $enclosure)) { + $enclosed = ($enclosed) ? false : true; // inline quotes } elseif ($ch == $enclosure && $enclosed) { $i++; // end of row - } elseif (($ch == "\n" && $pch != "\r" || $ch == "\r") && !$enclosed) { + } elseif (($ch == "\n" && $pch != "\r" || $ch == "\r") && ! $enclosed) { if ($n >= $search_depth) { $strlen = 0; $to_end = false; @@ -331,9 +341,9 @@ class parseCSV } // count character - } elseif (!$enclosed) { - if (!preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch)) { - if (!isset($chars[$ch][$n])) { + } elseif (! $enclosed) { + if (! preg_match('/['.preg_quote($this->auto_non_chars, '/').']/i', $ch)) { + if (! isset($chars[$ch][$n])) { $chars[$ch][$n] = 1; } else { $chars[$ch][$n]++; @@ -343,7 +353,7 @@ class parseCSV } // filtering - $depth = ($to_end) ? $n-1 : $n ; + $depth = ($to_end) ? $n - 1 : $n; $filtered = []; foreach ($chars as $char => $value) { if ($match = $this->_check_count($char, $value, $depth, $preferred)) { @@ -364,15 +374,16 @@ class parseCSV return $delimiter; } - // ============================================== // ----- [ Core Functions ] --------------------- // ============================================== /** - * Read file to string and call parse_string() + * Read file to string and call parse_string(). + * * @param file local CSV file - * @return 2D array with CSV data, or false on failure + * + * @return 2D array with CSV data, or false on failure */ public function parse_file($file = null) { @@ -382,13 +393,16 @@ class parseCSV if (empty($this->file_data)) { $this->load_data($file); } - return (!empty($this->file_data)) ? $this->parse_string() : false ; + + return (! empty($this->file_data)) ? $this->parse_string() : false; } /** - * Parse CSV strings to arrays + * Parse CSV strings to arrays. + * * @param data CSV string - * @return 2D array with CSV data, or false on failure + * + * @return 2D array with CSV data, or false on failure */ public function parse_string($data = null) { @@ -404,21 +418,21 @@ class parseCSV $row = []; $row_count = 0; $current = ''; - $head = (!empty($this->fields)) ? $this->fields : [] ; + $head = (! empty($this->fields)) ? $this->fields : []; $col = 0; $enclosed = false; $was_enclosed = false; $strlen = strlen($data); // walk through each character - for ($i=0; $i < $strlen; $i++) { + for ($i = 0; $i < $strlen; $i++) { $ch = $data{$i}; - $nch = (isset($data{$i+1})) ? $data{$i+1} : false ; - $pch = (isset($data{$i-1})) ? $data{$i-1} : false ; + $nch = (isset($data{$i + 1})) ? $data{$i + 1} : false; + $pch = (isset($data{$i - 1})) ? $data{$i - 1} : false; // open and closing quotes - if ($ch == $this->enclosure && (!$enclosed || $nch != $this->enclosure)) { - $enclosed = ($enclosed) ? false : true ; + if ($ch == $this->enclosure && (! $enclosed || $nch != $this->enclosure)) { + $enclosed = ($enclosed) ? false : true; if ($enclosed) { $was_enclosed = true; } @@ -429,11 +443,11 @@ class parseCSV $i++; // end of field/row - } elseif (($ch == $this->delimiter || ($ch == "\n" && $pch != "\r") || $ch == "\r") && !$enclosed) { - if (!$was_enclosed) { + } elseif (($ch == $this->delimiter || ($ch == "\n" && $pch != "\r") || $ch == "\r") && ! $enclosed) { + if (! $was_enclosed) { $current = trim($current); } - $key = (!empty($head[$col])) ? $head[$col] : $col ; + $key = (! empty($head[$col])) ? $head[$col] : $col; $row[$key] = $current; $current = ''; $col++; @@ -443,12 +457,12 @@ class parseCSV if ($this->_validate_offset($row_count) && $this->_validate_row_conditions($row, $this->conditions)) { if ($this->heading && empty($head)) { $head = $row; - } elseif (empty($this->fields) || (!empty($this->fields) && (($this->heading && $row_count > 0) || !$this->heading))) { - if (!empty($this->sort_by) && !empty($row[$this->sort_by])) { + } elseif (empty($this->fields) || (! empty($this->fields) && (($this->heading && $row_count > 0) || ! $this->heading))) { + if (! empty($this->sort_by) && ! empty($row[$this->sort_by])) { if (isset($rows[$row[$this->sort_by]])) { $rows[$row[$this->sort_by].'_0'] = &$rows[$row[$this->sort_by]]; unset($rows[$row[$this->sort_by]]); - for ($sn=1; isset($rows[$row[$this->sort_by].'_'.$sn]); $sn++) { + for ($sn = 1; isset($rows[$row[$this->sort_by].'_'.$sn]); $sn++) { } $rows[$row[$this->sort_by].'_'.$sn] = $row; } else { @@ -473,42 +487,45 @@ class parseCSV } } $this->titles = $head; - if (!empty($this->sort_by)) { - ($this->sort_reverse) ? krsort($rows) : ksort($rows) ; + if (! empty($this->sort_by)) { + ($this->sort_reverse) ? krsort($rows) : ksort($rows); if ($this->offset !== null || $this->limit !== null) { $rows = array_slice($rows, ($this->offset === null ? 0 : $this->offset), $this->limit, true); } } + return $rows; } /** - * Create CSV data from array + * Create CSV data from array. + * * @param data 2D array with data * @param fields field names * @param append if true, field names will not be output * @param is_php if a php die() call should be put on the first * line of the file, this is later ignored when read. * @param delimiter field delimiter to use - * @return CSV data (text string) + * + * @return CSV data (text string) */ public function unparse($data = [], $fields = [], $append = false, $is_php = false, $delimiter = null) { - if (!is_array($data) || empty($data)) { + if (! is_array($data) || empty($data)) { $data = &$this->data; } - if (!is_array($fields) || empty($fields)) { + if (! is_array($fields) || empty($fields)) { $fields = &$this->titles; } if ($delimiter === null) { $delimiter = $this->delimiter; } - $string = ($is_php) ? "".$this->linefeed : '' ; + $string = ($is_php) ? "".$this->linefeed : ''; $entry = []; // create heading - if ($this->heading && !$append) { + if ($this->heading && ! $append) { foreach ($fields as $key => $value) { $entry[] = $this->_enclose_value($value); } @@ -529,9 +546,11 @@ class parseCSV } /** - * Load local file or string + * Load local file or string. + * * @param input local CSV file - * @return true or false + * + * @return true or false */ public function load_data($input = null) { @@ -544,7 +563,7 @@ class parseCSV } else { $data = $input; } - if (!empty($data) || $data = $this->_rfile($file)) { + if (! empty($data) || $data = $this->_rfile($file)) { if ($this->file != $file) { $this->file = $file; } @@ -558,27 +577,30 @@ class parseCSV $data .= "\n"; } $this->file_data = &$data; + return true; } + return false; } - // ============================================== // ----- [ Internal Functions ] ----------------- // ============================================== /** - * Validate a row against specified conditions + * Validate a row against specified conditions. + * * @param row array with values from a row * @param conditions specified conditions that the row must match - * @return true of false + * + * @return true of false */ public function _validate_row_conditions($row = [], $conditions = null) { - if (!empty($row)) { - if (!empty($conditions)) { - $conditions = (strpos($conditions, ' OR ') !== false) ? explode(' OR ', $conditions) : [$conditions] ; + if (! empty($row)) { + if (! empty($conditions)) { + $conditions = (strpos($conditions, ' OR ') !== false) ? explode(' OR ', $conditions) : [$conditions]; $or = ''; foreach ($conditions as $key => $value) { if (strpos($value, ' AND ') !== false) { @@ -587,23 +609,28 @@ class parseCSV foreach ($value as $k => $v) { $and .= $this->_validate_row_condition($row, $v); } - $or .= (strpos($and, '0') !== false) ? '0' : '1' ; + $or .= (strpos($and, '0') !== false) ? '0' : '1'; } else { $or .= $this->_validate_row_condition($row, $value); } } - return (strpos($or, '1') !== false) ? true : false ; + + return (strpos($or, '1') !== false) ? true : false; } + return true; } + return false; } /** - * Validate a row against a single condition + * Validate a row against a single condition. + * * @param row array with values from a row * @param condition specified condition that the row must match - * @return true of false + * + * @return true of false */ public function _validate_row_condition($row, $condition) { @@ -650,34 +677,40 @@ class parseCSV return '1'; } elseif ($op == 'contains' && preg_match('/'.preg_quote($value, '/').'/i', $row[$field])) { return '1'; - } elseif ($op == 'does not contain' && !preg_match('/'.preg_quote($value, '/').'/i', $row[$field])) { + } elseif ($op == 'does not contain' && ! preg_match('/'.preg_quote($value, '/').'/i', $row[$field])) { return '1'; } else { return '0'; } } } + return '1'; } /** - * Validates if the row is within the offset or not if sorting is disabled + * Validates if the row is within the offset or not if sorting is disabled. + * * @param current_row the current row number being processed - * @return true of false + * + * @return true of false */ public function _validate_offset($current_row) { if ($this->sort_by === null && $this->offset !== null && $current_row < $this->offset) { return false; } + return true; } /** * Enclose values if needed - * - only used by unparse() + * - only used by unparse(). + * * @param value string to process - * @return Processed value + * + * @return Processed value */ public function _enclose_value($value = null) { @@ -689,13 +722,16 @@ class parseCSV $value = $this->enclosure.$value.$this->enclosure; } } + return $value; } /** - * Check file data + * Check file data. + * * @param file local filename - * @return true or false + * + * @return true or false */ public function _check_data($file = null) { @@ -703,16 +739,18 @@ class parseCSV if ($file === null) { $file = $this->file; } + return $this->load_data($file); } + return true; } - /** * Check if passed info might be delimiter - * - only used by find_delimiter() - * @return special string used for delimiter selection, or false + * - only used by find_delimiter(). + * + * @return special string used for delimiter selection, or false */ public function _check_count($char, $array, $depth, $preferred) { @@ -725,7 +763,7 @@ class parseCSV $first = $value; } elseif ($value == $first && $equal !== false) { $equal = true; - } elseif ($value == $first+1 && $equal !== false) { + } elseif ($value == $first + 1 && $equal !== false) { $equal = true; $almost = true; } else { @@ -733,9 +771,10 @@ class parseCSV } } if ($equal) { - $match = ($almost) ? 2 : 1 ; + $match = ($almost) ? 2 : 1; $pref = strpos($preferred, $char); - $pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999' ; + $pref = ($pref !== false) ? str_pad($pref, 3, '0', STR_PAD_LEFT) : '999'; + return $pref.$match.'.'.(99999 - str_pad($first, 5, '0', STR_PAD_LEFT)); } else { return false; @@ -744,30 +783,36 @@ class parseCSV } /** - * Read local file + * Read local file. + * * @param file local filename - * @return Data from file, or false on failure + * + * @return Data from file, or false on failure */ public function _rfile($file = null) { if (is_readable($file)) { - if (!($fh = fopen($file, 'r'))) { + if (! ($fh = fopen($file, 'r'))) { return false; } $data = fread($fh, filesize($file)); fclose($fh); + return $data; } + return false; } /** - * Write to local file + * Write to local file. + * * @param file local filename * @param string data to write to file * @param mode fopen() mode * @param lock flock() mode - * @return true or false + * + * @return true or false */ public function _wfile($file, $string = '', $mode = 'wb', $lock = 2) { @@ -779,6 +824,7 @@ class parseCSV return true; } } + return false; } } diff --git a/app/Jobs/Job.php b/app/Jobs/Job.php index cd1bae1ceb3d..605ad09ff400 100644 --- a/app/Jobs/Job.php +++ b/app/Jobs/Job.php @@ -17,7 +17,7 @@ abstract class Job */ protected $jobName; - /** + /* * Handle a job failure. * * @param ContactMailer $mailer diff --git a/app/Jobs/SendInvoiceEmail.php b/app/Jobs/SendInvoiceEmail.php index 073c74356a8c..2b8f77573a76 100644 --- a/app/Jobs/SendInvoiceEmail.php +++ b/app/Jobs/SendInvoiceEmail.php @@ -4,13 +4,13 @@ namespace App\Jobs; use App\Models\Invoice; use App\Ninja\Mailers\ContactMailer; -use Illuminate\Queue\SerializesModels; -use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; use Monolog\Logger; /** - * Class SendInvoiceEmail + * Class SendInvoiceEmail. */ class SendInvoiceEmail extends Job implements ShouldQueue { @@ -35,8 +35,8 @@ class SendInvoiceEmail extends Job implements ShouldQueue * Create a new job instance. * * @param Invoice $invoice - * @param string $pdf - * @param bool $reminder + * @param string $pdf + * @param bool $reminder */ public function __construct(Invoice $invoice, $reminder = false, $pdfString = false) { @@ -55,7 +55,7 @@ class SendInvoiceEmail extends Job implements ShouldQueue $mailer->sendInvoice($this->invoice, $this->reminder, $this->pdfString); } - /** + /* * Handle a job failure. * * @param ContactMailer $mailer diff --git a/app/Jobs/SendNotificationEmail.php b/app/Jobs/SendNotificationEmail.php index cb62295f4c67..fbb6904bb89e 100644 --- a/app/Jobs/SendNotificationEmail.php +++ b/app/Jobs/SendNotificationEmail.php @@ -4,12 +4,12 @@ namespace App\Jobs; use App\Models\Payment; use App\Ninja\Mailers\UserMailer; -use Illuminate\Queue\SerializesModels; -use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; /** - * Class SendInvoiceEmail + * Class SendInvoiceEmail. */ class SendNotificationEmail extends Job implements ShouldQueue { @@ -35,13 +35,12 @@ class SendNotificationEmail extends Job implements ShouldQueue */ protected $payment; - /** * Create a new job instance. - * @param UserMailer $userMailer + * @param UserMailer $userMailer * @param ContactMailer $contactMailer - * @param PushService $pushService + * @param PushService $pushService */ public function __construct($user, $invoice, $type, $payment) { diff --git a/app/Jobs/SendPaymentEmail.php b/app/Jobs/SendPaymentEmail.php index 27bd08f8063c..e23d291efcec 100644 --- a/app/Jobs/SendPaymentEmail.php +++ b/app/Jobs/SendPaymentEmail.php @@ -4,12 +4,12 @@ namespace App\Jobs; use App\Models\Payment; use App\Ninja\Mailers\ContactMailer; -use Illuminate\Queue\SerializesModels; -use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; /** - * Class SendInvoiceEmail + * Class SendInvoiceEmail. */ class SendPaymentEmail extends Job implements ShouldQueue { @@ -20,7 +20,6 @@ class SendPaymentEmail extends Job implements ShouldQueue */ protected $payment; - /** * Create a new job instance. diff --git a/app/Jobs/SendPushNotification.php b/app/Jobs/SendPushNotification.php index fe1ba74d9a1b..e6eba575e84d 100644 --- a/app/Jobs/SendPushNotification.php +++ b/app/Jobs/SendPushNotification.php @@ -3,13 +3,13 @@ namespace App\Jobs; use App\Models\Invoice; -use Illuminate\Queue\SerializesModels; -use Illuminate\Queue\InteractsWithQueue; -use Illuminate\Contracts\Queue\ShouldQueue; use App\Services\PushService; +use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Queue\SerializesModels; /** - * Class SendInvoiceEmail + * Class SendInvoiceEmail. */ class SendPushNotification extends Job implements ShouldQueue { @@ -25,7 +25,6 @@ class SendPushNotification extends Job implements ShouldQueue */ protected $type; - /** * Create a new job instance. diff --git a/app/Libraries/CurlUtils.php b/app/Libraries/CurlUtils.php index 4904e15aeaac..ccd118e32063 100644 --- a/app/Libraries/CurlUtils.php +++ b/app/Libraries/CurlUtils.php @@ -1,4 +1,6 @@ -account_id]) ? $history[$entity->account_id] : []; $data = []; // Add to the list and make sure to only show each item once - for ($i = 0; $iurl == $item->url) { @@ -160,7 +162,7 @@ class HistoryUtils $icon = ''; if ($item->client_id) { $link = url('/clients/' . $item->client_id); - $name = $item->client_name ; + $name = $item->client_name; $buttonLink = url('/invoices/create/' . $item->client_id); $button = ' diff --git a/app/Libraries/OFX.php b/app/Libraries/OFX.php index 4552ceee31ce..2fa13d80c589 100644 --- a/app/Libraries/OFX.php +++ b/app/Libraries/OFX.php @@ -1,10 +1,12 @@ -bank = $bank; $this->request = $request; } + public function go() { $c = curl_init(); @@ -40,6 +44,7 @@ class OFX $this->responseHeader = $tmp[0]; $this->responseBody = ''.$tmp[1]; } + public function xml() { $xml = $this->responseBody; @@ -52,6 +57,7 @@ class OFX public static function closeTags($x) { $x = preg_replace('/\s+/', '', $x); + return preg_replace('/(<([^<\/]+)>)(?!.*?<\/\2>)([^<]+)/', '\1\3', $x); } } @@ -68,6 +74,7 @@ class Bank public $fid; public $org; public $url; + public function __construct($finance, $fid, $url, $org) { $this->finance = $finance; @@ -83,12 +90,14 @@ class Login public $bank; public $id; public $pass; + public function __construct($bank, $id, $pass) { $this->bank = $bank; $this->id = $id; $this->pass = $pass; } + public function setup() { $ofxRequest = @@ -149,6 +158,7 @@ class Account public $ledgerBalance; public $availableBalance; public $response; + public function __construct($login, $id, $type, $subType = null, $bankId = null) { $this->login = $login; @@ -157,6 +167,7 @@ class Account $this->subType = $subType; $this->bankId = $bankId; } + public function setup($includeTransactions = true) { $ofxRequest = @@ -227,10 +238,10 @@ class Account $this->response = $o->response; $x = $o->xml(); $a = $x->xpath('/OFX/*/*/*/LEDGERBAL/BALAMT'); - $this->ledgerBalance = (double) $a[0]; + $this->ledgerBalance = (float) $a[0]; $a = $x->xpath('/OFX/*/*/*/AVAILBAL/BALAMT'); if (isset($a[0])) { - $this->availableBalance = (double) $a[0]; + $this->availableBalance = (float) $a[0]; } } } diff --git a/app/Libraries/Skype/ButtonCard.php b/app/Libraries/Skype/ButtonCard.php index f2e1c52ae6f7..ed3136917538 100644 --- a/app/Libraries/Skype/ButtonCard.php +++ b/app/Libraries/Skype/ButtonCard.php @@ -1,4 +1,6 @@ -contentType = 'application/vnd.microsoft.card.hero'; - $this->content = new stdClass; + $this->content = new stdClass(); $this->content->buttons = []; } diff --git a/app/Libraries/Skype/InvoiceCard.php b/app/Libraries/Skype/InvoiceCard.php index f7a1d6097781..88f4dcd8232b 100644 --- a/app/Libraries/Skype/InvoiceCard.php +++ b/app/Libraries/Skype/InvoiceCard.php @@ -1,4 +1,6 @@ -contentType = 'application/vnd.microsoft.card.receipt'; - $this->content = new stdClass; + $this->content = new stdClass(); $this->content->facts = []; $this->content->items = []; $this->content->buttons = []; @@ -17,7 +19,7 @@ class InvoiceCard $this->setTitle(trans('texts.invoice_for_client', [ 'invoice' => link_to($invoice->getRoute(), $invoice->invoice_number), - 'client' => link_to($invoice->client->getRoute(), $invoice->client->getDisplayName()) + 'client' => link_to($invoice->client->getRoute(), $invoice->client->getDisplayName()), ])); $this->addFact(trans('texts.email'), HTML::mailto($invoice->client->contacts[0]->email)->toHtml()); @@ -60,7 +62,7 @@ class InvoiceCard public function addFact($key, $value) { - $fact = new stdClass; + $fact = new stdClass(); $fact->key = $key; $fact->value = $value; diff --git a/app/Libraries/Skype/InvoiceItemCard.php b/app/Libraries/Skype/InvoiceItemCard.php index 7922d7053001..f62f00810d00 100644 --- a/app/Libraries/Skype/InvoiceItemCard.php +++ b/app/Libraries/Skype/InvoiceItemCard.php @@ -1,4 +1,6 @@ -account; } elseif ($contactKey = session('contact_key')) { @@ -135,7 +137,7 @@ class Utils SOCIAL_GOOGLE, SOCIAL_FACEBOOK, SOCIAL_GITHUB, - SOCIAL_LINKEDIN + SOCIAL_LINKEDIN, ]; foreach ($providers as $provider) { @@ -150,7 +152,7 @@ class Utils public static function allowNewAccounts() { - return Utils::isNinja() || Auth::check(); + return self::isNinja() || Auth::check(); } public static function isPro() @@ -202,7 +204,7 @@ class Utils public static function getUserType() { - if (Utils::isNinja()) { + if (self::isNinja()) { return USER_TYPE_CLOUD_HOST; } else { return USER_TYPE_SELF_HOST; @@ -216,8 +218,8 @@ class Utils public static function getNewsFeedResponse($userType = false) { - if (!$userType) { - $userType = Utils::getUserType(); + if (! $userType) { + $userType = self::getUserType(); } $response = new stdClass(); @@ -231,7 +233,7 @@ class Utils public static function getProLabel($feature) { if (Auth::check() - && !Auth::user()->isPro() + && ! Auth::user()->isPro() && $feature == ACCOUNT_ADVANCED_SETTINGS) { return ' PRO'; } else { @@ -311,7 +313,7 @@ class Utils public static function fatalError($message = false, $exception = false) { - if (!$message) { + if (! $message) { $message = 'An error occurred, please try again later.'; } @@ -329,6 +331,7 @@ class Utils { $class = get_class($exception); $code = method_exists($exception, 'getStatusCode') ? $exception->getStatusCode() : $exception->getCode(); + return "***{$class}*** [{$code}] : {$exception->getFile()} [Line {$exception->getLine()}] => {$exception->getMessage()}"; } @@ -390,6 +393,7 @@ class Utils if (! $cache) { static::logError("Cache for {$type} is not set"); + return null; } @@ -404,15 +408,15 @@ class Utils { $value = floatval($value); - if (!$currencyId) { + if (! $currencyId) { $currencyId = Session::get(SESSION_CURRENCY, DEFAULT_CURRENCY); } - if (!$decorator) { + if (! $decorator) { $decorator = Session::get(SESSION_CURRENCY_DECORATOR, CURRENCY_DECORATOR_SYMBOL); } - if (!$countryId && Auth::check()) { + if (! $countryId && Auth::check()) { $countryId = Auth::user()->account->country_id; } @@ -458,7 +462,7 @@ class Utils public static function pluralizeEntityType($type) { - if (! Utils::isNinjaProd()) { + if (! self::isNinjaProd()) { if ($module = \Module::find($type)) { return $module->get('plural', $type); } @@ -479,6 +483,7 @@ class Utils } $lastDigits = substr($value, -4); + return str_repeat('*', $length - 4) . $lastDigits; } @@ -534,7 +539,7 @@ class Utils $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATETIME_FORMAT, DEFAULT_DATETIME_FORMAT); - return Utils::timestampToString($timestamp, $timezone, $format); + return self::timestampToString($timestamp, $timezone, $format); } public static function timestampToDateString($timestamp) @@ -542,12 +547,12 @@ class Utils $timezone = Session::get(SESSION_TIMEZONE, DEFAULT_TIMEZONE); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); - return Utils::timestampToString($timestamp, $timezone, $format); + return self::timestampToString($timestamp, $timezone, $format); } public static function dateToString($date) { - if (!$date) { + if (! $date) { return false; } @@ -560,12 +565,12 @@ class Utils $timestamp = $dateTime->getTimestamp(); $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); - return Utils::timestampToString($timestamp, false, $format); + return self::timestampToString($timestamp, false, $format); } - public static function timestampToString($timestamp, $timezone = false, $format) + public static function timestampToString($timestamp, $timezone, $format) { - if (!$timestamp) { + if (! $timestamp) { return ''; } $date = Carbon::createFromTimeStamp($timestamp); @@ -581,14 +586,14 @@ class Utils public static function toSqlDate($date, $formatResult = true) { - if (!$date) { + if (! $date) { return; } $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); $dateTime = DateTime::createFromFormat($format, $date); - if (!$dateTime) { + if (! $dateTime) { return $date; } else { return $formatResult ? $dateTime->format('Y-m-d') : $dateTime; @@ -597,14 +602,14 @@ class Utils public static function fromSqlDate($date, $formatResult = true) { - if (!$date || $date == '0000-00-00') { + if (! $date || $date == '0000-00-00') { return ''; } $format = Session::get(SESSION_DATE_FORMAT, DEFAULT_DATE_FORMAT); $dateTime = DateTime::createFromFormat('Y-m-d', $date); - if (!$dateTime) { + if (! $dateTime) { return $date; } else { return $formatResult ? $dateTime->format($format) : $dateTime; @@ -613,7 +618,7 @@ class Utils public static function fromSqlDateTime($date, $formatResult = true) { - if (!$date || $date == '0000-00-00 00:00:00') { + if (! $date || $date == '0000-00-00 00:00:00') { return ''; } @@ -630,7 +635,8 @@ class Utils { // http://stackoverflow.com/a/3172665 $f = ':'; - return sprintf('%02d%s%02d%s%02d', floor($t/3600), $f, ($t/60)%60, $f, $t%60); + + return sprintf('%02d%s%02d%s%02d', floor($t / 3600), $f, ($t / 60) % 60, $f, $t % 60); } public static function today($formatResult = true) @@ -649,12 +655,12 @@ class Utils public static function processVariables($str) { - if (!$str) { + if (! $str) { return ''; } $variables = ['MONTH', 'QUARTER', 'YEAR']; - for ($i = 0; $i 'POST', CURLOPT_POST => 1, CURLOPT_POSTFIELDS => $jsonEncodedData, - CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Content-Length: '.strlen($jsonEncodedData)], + CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'Content-Length: '.strlen($jsonEncodedData)], ]; curl_setopt_array($curl, $opts); @@ -854,7 +860,7 @@ class Utils public static function isEmpty($value) { - return !$value || $value == '0' || $value == '0.00' || $value == '0,00'; + return ! $value || $value == '0' || $value == '0.00' || $value == '0,00'; } public static function startsWith($haystack, $needle) @@ -915,9 +921,10 @@ class Utils public static function transFlowText($key) { $str = trans("texts.$key"); - if (!in_array(App::getLocale(), ['de', 'fr'])) { + if (! in_array(App::getLocale(), ['de', 'fr'])) { $str = strtolower($str); } + return $str; } @@ -931,6 +938,7 @@ class Utils $subdomain = $host[0]; } } + return $subdomain; } @@ -950,6 +958,7 @@ class Utils if (isset($parts['path'])) { $domain .= $parts['path']; } + return $domain; } @@ -961,6 +970,7 @@ class Utils $oldSubdomain = $host[0]; $domain = str_replace("://{$oldSubdomain}.", "://{$subdomain}.", $domain); } + return $domain; } @@ -969,12 +979,14 @@ class Utils $name = trim($name); $lastName = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name); $firstName = trim(preg_replace('#'.$lastName.'#', '', $name)); + return [$firstName, $lastName]; } public static function decodePDF($string) { $string = str_replace('data:application/pdf;base64,', '', $string); + return base64_decode($string); } @@ -998,7 +1010,7 @@ class Utils public static function formatWebsite($website) { - if (!$website) { + if (! $website) { return ''; } @@ -1018,13 +1030,14 @@ class Utils public static function wrapAdjustment($adjustment, $currencyId, $countryId) { $class = $adjustment <= 0 ? 'success' : 'default'; - $adjustment = Utils::formatMoney($adjustment, $currencyId, $countryId); + $adjustment = self::formatMoney($adjustment, $currencyId, $countryId); + return "

$adjustment

"; } public static function copyContext($entity1, $entity2) { - if (!$entity2) { + if (! $entity2) { return $entity1; } @@ -1033,7 +1046,7 @@ class Utils 'payment_id', 'invoice_id', 'credit_id', - 'invitation_id' + 'invitation_id', ]; $fields1 = $entity1->getAttributes(); @@ -1050,7 +1063,7 @@ class Utils public static function addHttp($url) { - if (!preg_match('~^(?:f|ht)tps?://~i', $url)) { + if (! preg_match('~^(?:f|ht)tps?://~i', $url)) { $url = 'http://' . $url; } @@ -1075,7 +1088,7 @@ class Utils } /** - * Gets an array of weekday names (in English) + * Gets an array of weekday names (in English). * * @see getTranslatedWeekdayNames() * @@ -1087,7 +1100,7 @@ class Utils } /** - * Gets an array of translated weekday names + * Gets an array of translated weekday names. * * @return \Illuminate\Support\Collection */ diff --git a/app/Libraries/lib_autolink.php b/app/Libraries/lib_autolink.php index 5498dd31ae5f..dbc8690b0b96 100644 --- a/app/Libraries/lib_autolink.php +++ b/app/Libraries/lib_autolink.php @@ -1,43 +1,45 @@ - - # This code is licensed under the MIT license - # + + // This code is licensed under the MIT license + // - # - # These are global options. You can set them before calling the autolinking - # functions to change the output. - # + //################################################################### + + // + // These are global options. You can set them before calling the autolinking + // functions to change the output. + // $GLOBALS['autolink_options'] = [ - # Should http:// be visibly stripped from the front - # of URLs? + // Should http:// be visibly stripped from the front + // of URLs? 'strip_protocols' => false, ]; - #################################################################### + //################################################################### - function autolink($text, $limit=30, $tagfill='', $auto_title = true) + function autolink($text, $limit = 30, $tagfill = '', $auto_title = true) { $text = autolink_do($text, '![a-z][a-z-]+://!i', $limit, $tagfill, $auto_title); $text = autolink_do($text, '!(mailto|skype):!i', $limit, $tagfill, $auto_title); $text = autolink_do($text, '!www\\.!i', $limit, $tagfill, $auto_title, 'http://'); + return $text; } - #################################################################### + //################################################################### - function autolink_do($text, $sub, $limit, $tagfill, $auto_title, $force_prefix=null) + function autolink_do($text, $sub, $limit, $tagfill, $auto_title, $force_prefix = null) { - $text_l = StrToLower($text); + $text_l = strtolower($text); $cursor = 0; $loop = 1; $buffer = ''; @@ -46,14 +48,14 @@ $ok = 1; $matched = preg_match($sub, $text_l, $m, PREG_OFFSET_CAPTURE, $cursor); - if (!$matched) { + if (! $matched) { $loop = 0; $ok = 0; } else { $pos = $m[0][1]; $sub_len = strlen($m[0][0]); - $pre_hit = substr($text, $cursor, $pos-$cursor); + $pre_hit = substr($text, $cursor, $pos - $cursor); $hit = substr($text, $pos, $sub_len); $pre = substr($text, 0, $pos); $post = substr($text, $pos + $sub_len); @@ -61,15 +63,15 @@ $fail_text = $pre_hit.$hit; $fail_len = strlen($fail_text); - # - # substring found - first check to see if we're inside a link tag already... - # + // + // substring found - first check to see if we're inside a link tag already... + // $bits = preg_split('!
!i', $pre); $last_bit = array_pop($bits); if (preg_match("!\n"; + //echo "fail 1 at $cursor
\n"; $ok = 0; $cursor += $fail_len; @@ -77,16 +79,16 @@ } } - # - # looks like a nice spot to autolink from - check the pre - # to see if there was whitespace before this match - # + // + // looks like a nice spot to autolink from - check the pre + // to see if there was whitespace before this match + // if ($ok) { if ($pre) { - if (!preg_match('![\s\(\[\{>]$!s', $pre)) { + if (! preg_match('![\s\(\[\{>]$!s', $pre)) { - #echo "fail 2 at $cursor ($pre)
\n"; + //echo "fail 2 at $cursor ($pre)
\n"; $ok = 0; $cursor += $fail_len; @@ -95,9 +97,9 @@ } } - # - # we want to autolink here - find the extent of the url - # + // + // we want to autolink here - find the extent of the url + // if ($ok) { if (preg_match('/^([a-z0-9\-\.\/\-_%~!?=,:;&+*#@\(\)\$]+)/i', $post, $matches)) { @@ -108,28 +110,26 @@ $url = html_entity_decode($url); - - # - # remove trailing punctuation from url - # + // + // remove trailing punctuation from url + // while (preg_match('|[.,!;:?]$|', $url)) { - $url = substr($url, 0, strlen($url)-1); + $url = substr($url, 0, strlen($url) - 1); $cursor--; } foreach (['()', '[]', '{}'] as $pair) { $o = substr($pair, 0, 1); $c = substr($pair, 1, 1); if (preg_match("!^(\\$c|^)[^\\$o]+\\$c$!", $url)) { - $url = substr($url, 0, strlen($url)-1); + $url = substr($url, 0, strlen($url) - 1); $cursor--; } } - - # - # nice-i-fy url here - # + // + // nice-i-fy url here + // $link_url = $url; $display_url = $url; @@ -140,32 +140,31 @@ if ($GLOBALS['autolink_options']['strip_protocols']) { if (preg_match('!^(http|https)://!i', $display_url, $m)) { - $display_url = substr($display_url, strlen($m[1])+3); + $display_url = substr($display_url, strlen($m[1]) + 3); } } $display_url = autolink_label($display_url, $limit); - - # - # add the url - # + // + // add the url + // $currentTagfill = $tagfill; - if ($display_url != $link_url && !preg_match('@title=@msi', $currentTagfill) && $auto_title) { + if ($display_url != $link_url && ! preg_match('@title=@msi', $currentTagfill) && $auto_title) { $display_quoted = preg_quote($display_url, '!'); - if (!preg_match("!^(http|https)://{$display_quoted}$!i", $link_url)) { + if (! preg_match("!^(http|https)://{$display_quoted}$!i", $link_url)) { $currentTagfill .= ' title="'.$link_url.'"'; } } - $link_url_enc = HtmlSpecialChars($link_url); - $display_url_enc = HtmlSpecialChars($display_url); + $link_url_enc = htmlspecialchars($link_url); + $display_url_enc = htmlspecialchars($display_url); $buffer .= "{$display_url_enc}"; } else { - #echo "fail 3 at $cursor
\n"; + //echo "fail 3 at $cursor
\n"; $ok = 0; $cursor += $fail_len; @@ -174,48 +173,48 @@ } } - # - # add everything from the cursor to the end onto the buffer. - # + // + // add everything from the cursor to the end onto the buffer. + // $buffer .= substr($text, $cursor); return $buffer; } - #################################################################### + //################################################################### function autolink_label($text, $limit) { - if (!$limit) { + if (! $limit) { return $text; } if (strlen($text) > $limit) { - return substr($text, 0, $limit-3).'...'; + return substr($text, 0, $limit - 3).'...'; } return $text; } - #################################################################### + //################################################################### - function autolink_email($text, $tagfill='') + function autolink_email($text, $tagfill = '') { - $atom = '[^()<>@,;:\\\\".\\[\\]\\x00-\\x20\\x7f]+'; # from RFC822 + $atom = '[^()<>@,;:\\\\".\\[\\]\\x00-\\x20\\x7f]+'; // from RFC822 - #die($atom); + //die($atom); - $text_l = StrToLower($text); + $text_l = strtolower($text); $cursor = 0; $loop = 1; $buffer = ''; while (($cursor < strlen($text)) && $loop) { - # - # find an '@' symbol - # + // + // find an '@' symbol + // $ok = 1; $pos = strpos($text_l, '@', $cursor); @@ -224,24 +223,24 @@ $loop = 0; $ok = 0; } else { - $pre = substr($text, $cursor, $pos-$cursor); + $pre = substr($text, $cursor, $pos - $cursor); $hit = substr($text, $pos, 1); $post = substr($text, $pos + 1); $fail_text = $pre.$hit; $fail_len = strlen($fail_text); - #die("$pre::$hit::$post::$fail_text"); + //die("$pre::$hit::$post::$fail_text"); - # - # substring found - first check to see if we're inside a link tag already... - # + // + // substring found - first check to see if we're inside a link tag already... + // $bits = preg_split('!!i', $pre); $last_bit = array_pop($bits); if (preg_match("!\n"; + //echo "fail 1 at $cursor
\n"; $ok = 0; $cursor += $fail_len; @@ -249,23 +248,23 @@ } } - # - # check backwards - # + // + // check backwards + // if ($ok) { if (preg_match("!($atom(\.$atom)*)\$!", $pre, $matches)) { - # move matched part of address into $hit + // move matched part of address into $hit $len = strlen($matches[1]); $plen = strlen($pre); - $hit = substr($pre, $plen-$len).$hit; - $pre = substr($pre, 0, $plen-$len); + $hit = substr($pre, $plen - $len).$hit; + $pre = substr($pre, 0, $plen - $len); } else { - #echo "fail 2 at $cursor ($pre)
\n"; + //echo "fail 2 at $cursor ($pre)
\n"; $ok = 0; $cursor += $fail_len; @@ -273,21 +272,21 @@ } } - # - # check forwards - # + // + // check forwards + // if ($ok) { if (preg_match("!^($atom(\.$atom)*)!", $post, $matches)) { - # move matched part of address into $hit + // move matched part of address into $hit $len = strlen($matches[1]); $hit .= substr($post, 0, $len); $post = substr($post, $len); } else { - #echo "fail 3 at $cursor ($post)
\n"; + //echo "fail 3 at $cursor ($post)
\n"; $ok = 0; $cursor += $fail_len; @@ -295,9 +294,9 @@ } } - # - # commit - # + // + // commit + // if ($ok) { $cursor += strlen($pre) + strlen($hit); @@ -306,13 +305,13 @@ } } - # - # add everything from the cursor to the end onto the buffer. - # + // + // add everything from the cursor to the end onto the buffer. + // $buffer .= substr($text, $cursor); return $buffer; } - ####################################################################; + //###################################################################; diff --git a/app/Listeners/ActivityListener.php b/app/Listeners/ActivityListener.php index 25435a3a844f..59acdb457b98 100644 --- a/app/Listeners/ActivityListener.php +++ b/app/Listeners/ActivityListener.php @@ -1,50 +1,52 @@ -activityRepo->create( diff --git a/app/Listeners/AnalyticsListener.php b/app/Listeners/AnalyticsListener.php index c100a0feec29..5b26b59ab683 100644 --- a/app/Listeners/AnalyticsListener.php +++ b/app/Listeners/AnalyticsListener.php @@ -1,10 +1,12 @@ -language_id || $this->language_id == DEFAULT_LANGUAGE; + return ! $this->language_id || $this->language_id == DEFAULT_LANGUAGE; } /** @@ -404,6 +407,7 @@ class Account extends Eloquent public function getCityState() { $swap = $this->country && $this->country->swap_postal_code; + return Utils::cityStateZip($this->city, $this->state, $this->postal_code, $swap); } @@ -458,6 +462,7 @@ class Account extends Eloquent /** * @param string $date + * * @return DateTime|null|string */ public function getDateTime($date = 'now') @@ -476,7 +481,6 @@ class Account extends Eloquent return $this->date_format ? $this->date_format->format : DEFAULT_DATE_FORMAT; } - public function getSampleLink() { $invitation = new Invitation(); @@ -486,11 +490,11 @@ class Account extends Eloquent return $invitation->getLink(); } - /** * @param $amount * @param null $client * @param bool $hideSymbol + * * @return string */ public function formatMoney($amount, $client = null, $decorator = false) @@ -528,6 +532,7 @@ class Account extends Eloquent /** * @param $date + * * @return null|string */ public function formatDate($date) @@ -543,6 +548,7 @@ class Account extends Eloquent /** * @param $date + * * @return null|string */ public function formatDateTime($date) @@ -558,6 +564,7 @@ class Account extends Eloquent /** * @param $date + * * @return null|string */ public function formatTime($date) @@ -605,6 +612,7 @@ class Account extends Eloquent /** * @param bool $type + * * @return AccountGateway|bool */ public function getGatewayByType($type = false) @@ -666,8 +674,9 @@ class Account extends Eloquent } /** - * @param bool $invitation + * @param bool $invitation * @param mixed $gatewayTypeId + * * @return bool */ public function paymentDriver($invitation = false, $gatewayTypeId = false) @@ -690,6 +699,7 @@ class Account extends Eloquent /** * @param $gatewayId + * * @return bool */ public function hasGatewayId($gatewayId) @@ -699,6 +709,7 @@ class Account extends Eloquent /** * @param $gatewayId + * * @return bool */ public function getGatewayConfig($gatewayId) @@ -721,7 +732,7 @@ class Account extends Eloquent $this->calculateLogoDetails(); } - return !empty($this->logo); + return ! empty($this->logo); } /** @@ -742,7 +753,7 @@ class Account extends Eloquent $this->logo = $this->account_key.'.jpg'; } - if (!empty($this->logo)) { + if (! empty($this->logo)) { $image = imagecreatefromstring($disk->get($this->logo)); $this->logo_width = imagesx($image); $this->logo_height = imagesy($image); @@ -758,21 +769,23 @@ class Account extends Eloquent */ public function getLogoRaw() { - if (!$this->hasLogo()) { + if (! $this->hasLogo()) { return null; } $disk = $this->getLogoDisk(); + return $disk->get($this->logo); } /** * @param bool $cachebuster + * * @return null|string */ public function getLogoURL($cachebuster = false) { - if (!$this->hasLogo()) { + if (! $this->hasLogo()) { return null; } @@ -822,6 +835,7 @@ class Account extends Eloquent /** * @param $userId * @param $name + * * @return null */ public function getToken($userId, $name) @@ -840,7 +854,7 @@ class Account extends Eloquent */ public function getLogoWidth() { - if (!$this->hasLogo()) { + if (! $this->hasLogo()) { return null; } @@ -852,7 +866,7 @@ class Account extends Eloquent */ public function getLogoHeight() { - if (!$this->hasLogo()) { + if (! $this->hasLogo()) { return null; } @@ -862,6 +876,7 @@ class Account extends Eloquent /** * @param $entityType * @param null $clientId + * * @return mixed */ public function createInvoice($entityType = ENTITY_INVOICE, $clientId = null) @@ -883,14 +898,14 @@ class Account extends Eloquent $invoice->invoice_type_id = INVOICE_TYPE_QUOTE; } - if ($this->hasClientNumberPattern($invoice) && !$clientId) { + if ($this->hasClientNumberPattern($invoice) && ! $clientId) { // do nothing, we don't yet know the value } elseif (! $invoice->invoice_number) { $invoice->invoice_number = $this->getNextNumber($invoice); } } - if (!$clientId) { + if (! $clientId) { $invoice->client = Client::createNew(); $invoice->client->public_id = 0; } @@ -957,6 +972,7 @@ class Account extends Eloquent /** * @param $feature + * * @return bool */ public function hasFeature($feature) @@ -966,9 +982,9 @@ class Account extends Eloquent } $planDetails = $this->getPlanDetails(); - $selfHost = !Utils::isNinjaProd(); + $selfHost = ! Utils::isNinjaProd(); - if (!$selfHost && function_exists('ninja_account_features')) { + if (! $selfHost && function_exists('ninja_account_features')) { $result = ninja_account_features($this, $feature); if ($result != null) { @@ -997,20 +1013,20 @@ class Account extends Eloquent case FEATURE_API: case FEATURE_CLIENT_PORTAL_PASSWORD: case FEATURE_CUSTOM_URL: - return $selfHost || !empty($planDetails); + return $selfHost || ! empty($planDetails); // Pro; No trial allowed, unless they're trialing enterprise with an active pro plan case FEATURE_MORE_CLIENTS: - return $selfHost || !empty($planDetails) && (!$planDetails['trial'] || !empty($this->getPlanDetails(false, false))); + return $selfHost || ! empty($planDetails) && (! $planDetails['trial'] || ! empty($this->getPlanDetails(false, false))); // White Label case FEATURE_WHITE_LABEL: - if ($this->isNinjaAccount() || (!$selfHost && $planDetails && !$planDetails['expires'])) { + if ($this->isNinjaAccount() || (! $selfHost && $planDetails && ! $planDetails['expires'])) { return false; } // Fallthrough case FEATURE_REMOVE_CREATED_BY: - return !empty($planDetails);// A plan is required even for self-hosted users + return ! empty($planDetails); // A plan is required even for self-hosted users // Enterprise; No Trial allowed; grandfathered for old pro users case FEATURE_USERS:// Grandfathered for old Pro users @@ -1019,12 +1035,12 @@ class Account extends Eloquent $planDetails = $this->getPlanDetails(false, false); } - return $selfHost || !empty($planDetails) && ($planDetails['plan'] == PLAN_ENTERPRISE || $planDetails['started'] <= date_create(PRO_USERS_GRANDFATHER_DEADLINE)); + return $selfHost || ! empty($planDetails) && ($planDetails['plan'] == PLAN_ENTERPRISE || $planDetails['started'] <= date_create(PRO_USERS_GRANDFATHER_DEADLINE)); // Enterprise; No Trial allowed case FEATURE_DOCUMENTS: case FEATURE_USER_PERMISSIONS: - return $selfHost || !empty($planDetails) && $planDetails['plan'] == PLAN_ENTERPRISE && !$planDetails['trial']; + return $selfHost || ! empty($planDetails) && $planDetails['plan'] == PLAN_ENTERPRISE && ! $planDetails['trial']; default: return false; @@ -1033,11 +1049,12 @@ class Account extends Eloquent /** * @param null $plan_details + * * @return bool */ public function isPro(&$plan_details = null) { - if (!Utils::isNinjaProd()) { + if (! Utils::isNinjaProd()) { return true; } @@ -1047,16 +1064,17 @@ class Account extends Eloquent $plan_details = $this->getPlanDetails(); - return !empty($plan_details); + return ! empty($plan_details); } /** * @param null $plan_details + * * @return bool */ public function isEnterprise(&$plan_details = null) { - if (!Utils::isNinjaProd()) { + if (! Utils::isNinjaProd()) { return true; } @@ -1072,11 +1090,12 @@ class Account extends Eloquent /** * @param bool $include_inactive * @param bool $include_trial + * * @return array|null */ public function getPlanDetails($include_inactive = false, $include_trial = true) { - if (!$this->company) { + if (! $this->company) { return null; } @@ -1084,7 +1103,7 @@ class Account extends Eloquent $price = $this->company->plan_price; $trial_plan = $this->company->trial_plan; - if ((!$plan || $plan == PLAN_FREE) && (!$trial_plan || !$include_trial)) { + if ((! $plan || $plan == PLAN_FREE) && (! $trial_plan || ! $include_trial)) { return null; } @@ -1112,22 +1131,22 @@ class Account extends Eloquent } } - if (!$include_inactive && !$plan_active && !$trial_active) { + if (! $include_inactive && ! $plan_active && ! $trial_active) { return null; } // Should we show plan details or trial details? - if (($plan && !$trial_plan) || !$include_trial) { + if (($plan && ! $trial_plan) || ! $include_trial) { $use_plan = true; - } elseif (!$plan && $trial_plan) { + } elseif (! $plan && $trial_plan) { $use_plan = false; } else { // There is both a plan and a trial - if (!empty($plan_active) && empty($trial_active)) { + if (! empty($plan_active) && empty($trial_active)) { $use_plan = true; - } elseif (empty($plan_active) && !empty($trial_active)) { + } elseif (empty($plan_active) && ! empty($trial_active)) { $use_plan = false; - } elseif (!empty($plan_active) && !empty($trial_active)) { + } elseif (! empty($plan_active) && ! empty($trial_active)) { // Both are active; use whichever is a better plan if ($plan == PLAN_ENTERPRISE) { $use_plan = true; @@ -1175,7 +1194,7 @@ class Account extends Eloquent */ public function isTrial() { - if (!Utils::isNinjaProd()) { + if (! Utils::isNinjaProd()) { return false; } @@ -1191,7 +1210,7 @@ class Account extends Eloquent { $planDetails = $this->getPlanDetails(true); - if (!$planDetails || !$planDetails['trial']) { + if (! $planDetails || ! $planDetails['trial']) { return 0; } @@ -1223,7 +1242,7 @@ class Account extends Eloquent */ public function getLogoSize() { - if (!$this->hasLogo()) { + if (! $this->hasLogo()) { return null; } @@ -1240,6 +1259,7 @@ class Account extends Eloquent /** * @param $eventId + * * @return \Illuminate\Database\Eloquent\Model|null|static */ public function getSubscription($eventId) @@ -1298,6 +1318,7 @@ class Account extends Eloquent /** * @param $entityType + * * @return mixed */ public function getDefaultEmailSubject($entityType) @@ -1311,6 +1332,7 @@ class Account extends Eloquent /** * @param $entityType + * * @return mixed */ public function getEmailSubject($entityType) @@ -1330,6 +1352,7 @@ class Account extends Eloquent /** * @param $entityType * @param bool $message + * * @return string */ public function getDefaultEmailTemplate($entityType, $message = false) @@ -1358,6 +1381,7 @@ class Account extends Eloquent /** * @param $entityType * @param bool $message + * * @return mixed */ public function getEmailTemplate($entityType, $message = false) @@ -1369,7 +1393,7 @@ class Account extends Eloquent $template = $this->$field; } - if (!$template) { + if (! $template) { $template = $this->getDefaultEmailTemplate($entityType, $message); } @@ -1379,6 +1403,7 @@ class Account extends Eloquent /** * @param string $view + * * @return string */ public function getTemplateView($view = '') @@ -1401,6 +1426,7 @@ class Account extends Eloquent /** * @param $reminder + * * @return bool */ public function getReminderDate($reminder) @@ -1417,11 +1443,12 @@ class Account extends Eloquent /** * @param Invoice $invoice + * * @return bool|string */ public function getInvoiceReminder(Invoice $invoice) { - for ($i=1; $i<=3; $i++) { + for ($i = 1; $i <= 3; $i++) { if ($date = $this->getReminderDate($i)) { $field = $this->{"field_reminder{$i}"} == REMINDER_FIELD_DUE_DATE ? 'due_date' : 'invoice_date'; if ($invoice->$field == $date) { @@ -1435,11 +1462,12 @@ class Account extends Eloquent /** * @param null $storage_gateway + * * @return bool */ public function showTokenCheckbox(&$storage_gateway = null) { - if (!($storage_gateway = $this->getTokenGatewayId())) { + if (! ($storage_gateway = $this->getTokenGatewayId())) { return false; } @@ -1469,7 +1497,7 @@ class Account extends Eloquent public function getTokenGateway() { $gatewayId = $this->getTokenGatewayId(); - if (!$gatewayId) { + if (! $gatewayId) { return; } @@ -1503,18 +1531,19 @@ class Account extends Eloquent /** * @param $host + * * @return bool */ public function checkSubdomain($host) { - if (!$this->subdomain) { + if (! $this->subdomain) { return true; } $server = explode('.', $host); $subdomain = $server[0]; - if (!in_array($subdomain, ['app', 'www']) && $subdomain != $this->subdomain) { + if (! in_array($subdomain, ['app', 'www']) && $subdomain != $this->subdomain) { return false; } @@ -1524,6 +1553,7 @@ class Account extends Eloquent /** * @param $field * @param bool $entity + * * @return bool */ public function showCustomField($field, $entity = false) @@ -1532,7 +1562,7 @@ class Account extends Eloquent return true; } - if (!$entity) { + if (! $entity) { return false; } @@ -1582,6 +1612,7 @@ class Account extends Eloquent /** * @param string $protocol + * * @return string */ public function getFontsUrl($protocol = '') @@ -1597,7 +1628,7 @@ class Account extends Eloquent $google_fonts[] = $headerFontSettings['google_font']; } - return ($protocol?$protocol.':':'').'//fonts.googleapis.com/css?family='.implode('|', $google_fonts); + return ($protocol ? $protocol.':' : '').'//fonts.googleapis.com/css?family='.implode('|', $google_fonts); } /** @@ -1634,6 +1665,7 @@ class Account extends Eloquent /** * @param bool $include_weight + * * @return string */ public function getHeaderFontCss($include_weight = true) @@ -1650,6 +1682,7 @@ class Account extends Eloquent /** * @param bool $include_weight + * * @return string */ public function getBodyFontCss($include_weight = true) diff --git a/app/Models/AccountGateway.php b/app/Models/AccountGateway.php index a974cc484fe6..514fea0cfb3f 100644 --- a/app/Models/AccountGateway.php +++ b/app/Models/AccountGateway.php @@ -1,11 +1,13 @@ -getConfigField('enableAch')); + return ! empty($this->getConfigField('enableAch')); } /** @@ -142,7 +148,7 @@ class AccountGateway extends EntityModel */ public function getPayPalEnabled() { - return !empty($this->getConfigField('enablePayPal')); + return ! empty($this->getConfigField('enablePayPal')); } /** @@ -186,7 +192,7 @@ class AccountGateway extends EntityModel */ public function getPlaidEnabled() { - return !empty($this->getPlaidClientId()) && $this->getAchEnabled(); + return ! empty($this->getPlaidClientId()) && $this->getAchEnabled(); } /** @@ -194,7 +200,7 @@ class AccountGateway extends EntityModel */ public function getPlaidEnvironment() { - if (!$this->getPlaidClientId()) { + if (! $this->getPlaidClientId()) { return null; } diff --git a/app/Models/AccountGatewaySettings.php b/app/Models/AccountGatewaySettings.php index 6dcc13c8e381..b0eb0e2920f1 100644 --- a/app/Models/AccountGatewaySettings.php +++ b/app/Models/AccountGatewaySettings.php @@ -1,7 +1,9 @@ -gateway_id == GATEWAY_BRAINTREE) { $merchantId = $accountGateway->getConfigField('merchantId'); $testMode = $accountGateway->getConfigField('testMode'); + return $testMode ? "https://sandbox.braintreegateway.com/merchants/{$merchantId}/customers/{$this->token}" : "https://www.braintreegateway.com/merchants/{$merchantId}/customers/{$this->token}"; } else { return false; diff --git a/app/Models/AccountToken.php b/app/Models/AccountToken.php index 5ef52e170117..dace5f00b91b 100644 --- a/app/Models/AccountToken.php +++ b/app/Models/AccountToken.php @@ -1,9 +1,11 @@ -account->enable_portal_password) { - if (!empty($data['password']) && $data['password']!='-%unchanged%-') { + if (! empty($data['password']) && $data['password'] != '-%unchanged%-') { $contact->password = bcrypt($data['password']); } elseif (empty($data['password'])) { $contact->password = null; @@ -374,6 +377,7 @@ class Client extends EntityModel public function getCityState() { $swap = $this->country && $this->country->swap_postal_code; + return Utils::cityStateZip($this->city, $this->state, $this->postal_code, $swap); } @@ -487,7 +491,7 @@ class Client extends EntityModel return $this->currency_id; } - if (!$this->account) { + if (! $this->account) { $this->load('account'); } @@ -503,7 +507,7 @@ class Client extends EntityModel return $this->currency->code; } - if (!$this->account) { + if (! $this->account) { $this->load('account'); } @@ -512,6 +516,7 @@ class Client extends EntityModel /** * @param $isQuote + * * @return mixed */ public function getCounter($isQuote) diff --git a/app/Models/Company.php b/app/Models/Company.php index 59fa5835ee0d..6756bd072a52 100644 --- a/app/Models/Company.php +++ b/app/Models/Company.php @@ -1,13 +1,15 @@ -discount = $discount; $this->promo_expires = date_create()->modify($validFor . ' days')->format('Y-m-d'); $this->save(); + return true; } } diff --git a/app/Models/Contact.php b/app/Models/Contact.php index 266794bb9d63..593eb207077e 100644 --- a/app/Models/Contact.php +++ b/app/Models/Contact.php @@ -1,13 +1,15 @@ -contact_key = $contact_key = str_random(RANDOM_KEY_LENGTH); static::where('id', $this->id)->update(['contact_key' => $contact_key]); } + return $contact_key; } diff --git a/app/Models/Country.php b/app/Models/Country.php index 709f831e8d21..410e1595b6a9 100644 --- a/app/Models/Country.php +++ b/app/Models/Country.php @@ -1,9 +1,11 @@ -disk)?$this->disk:env('DOCUMENT_FILESYSTEM', 'documents')); + return Storage::disk(! empty($this->disk) ? $this->disk : env('DOCUMENT_FILESYSTEM', 'documents')); } /** @@ -155,7 +158,7 @@ class Document extends EntityModel */ public function setDiskAttribute($value) { - $this->attributes['disk'] = $value?$value:env('DOCUMENT_FILESYSTEM', 'documents'); + $this->attributes['disk'] = $value ? $value : env('DOCUMENT_FILESYSTEM', 'documents'); } /** @@ -171,15 +174,17 @@ class Document extends EntityModel */ public function getDirectPreviewUrl() { - return $this->preview?static::getDirectFileUrl($this->preview, $this->getDisk(), true):null; + return $this->preview ? static::getDirectFileUrl($this->preview, $this->getDisk(), true) : null; } /** * @param $path * @param $disk * @param bool $prioritizeSpeed - * @return null|string + * * @throws \OpenCloud\Common\Exceptions\NoNameError + * + * @return null|string */ public static function getDirectFileUrl($path, $disk, $prioritizeSpeed = false) { @@ -190,11 +195,11 @@ class Document extends EntityModel $client = $adapter->getClient(); $command = $client->getCommand('GetObject', [ 'Bucket' => $adapter->getBucket(), - 'Key' => $fullPath + 'Key' => $fullPath, ]); return (string) $client->createPresignedRequest($command, '+10 minutes')->getUri(); - } elseif (!$prioritizeSpeed // Rackspace temp URLs are slow, so we don't use them for previews + } elseif (! $prioritizeSpeed // Rackspace temp URLs are slow, so we don't use them for previews && $adapter instanceof \League\Flysystem\Rackspace\RackspaceAdapter) { $secret = env('RACKSPACE_TEMP_URL_SECRET'); if ($secret) { @@ -210,6 +215,7 @@ class Document extends EntityModel $urlPath = urldecode($url->getPath()); $body = sprintf("%s\n%d\n%s", 'GET', $expiry, $urlPath); $hash = hash_hmac('sha1', $body, $secret); + return sprintf('%s?temp_url_sig=%s&temp_url_expires=%d', $url, $hash, $expiry); } } @@ -257,6 +263,7 @@ class Document extends EntityModel /** * @param $invitation + * * @return \Illuminate\Contracts\Routing\UrlGenerator|string */ public function getClientUrl($invitation) @@ -277,9 +284,10 @@ class Document extends EntityModel */ public function getVFSJSUrl() { - if (!$this->isPDFEmbeddable()) { + if (! $this->isPDFEmbeddable()) { return null; } + return url('documents/js/'.$this->public_id.'/'.$this->name.'.js'); } @@ -288,9 +296,10 @@ class Document extends EntityModel */ public function getClientVFSJSUrl() { - if (!$this->isPDFEmbeddable()) { + if (! $this->isPDFEmbeddable()) { return null; } + return url('client/documents/js/'.$this->public_id.'/'.$this->name.'.js'); } @@ -299,7 +308,7 @@ class Document extends EntityModel */ public function getPreviewUrl() { - return $this->preview?url('documents/preview/'.$this->public_id.'/'.$this->name.'.'.pathinfo($this->preview, PATHINFO_EXTENSION)):null; + return $this->preview ? url('documents/preview/'.$this->public_id.'/'.$this->name.'.'.pathinfo($this->preview, PATHINFO_EXTENSION)) : null; } /** @@ -324,7 +333,7 @@ class Document extends EntityModel */ public function cloneDocument() { - $document = Document::createNew($this); + $document = self::createNew($this); $document->path = $this->path; $document->preview = $this->preview; $document->name = $this->name; @@ -346,7 +355,7 @@ Document::deleted(function ($document) { ->where('documents.disk', '=', $document->disk) ->count(); - if (!$same_path_count) { + if (! $same_path_count) { $document->getDisk()->delete($document->path); } @@ -356,7 +365,7 @@ Document::deleted(function ($document) { ->where('documents.preview', '=', $document->preview) ->where('documents.disk', '=', $document->disk) ->count(); - if (!$same_preview_count) { + if (! $same_preview_count) { $document->getDisk()->delete($document->preview); } } diff --git a/app/Models/EntityModel.php b/app/Models/EntityModel.php index 8c31fb47254c..02d90df56812 100644 --- a/app/Models/EntityModel.php +++ b/app/Models/EntityModel.php @@ -1,4 +1,6 @@ -account_id; } @@ -162,6 +167,7 @@ class EntityModel extends Eloquent /** * @param $query + * * @return mixed */ public function scopeWithArchived($query) @@ -187,6 +193,7 @@ class EntityModel extends Eloquent /** * @param $entityType + * * @return string */ public static function getClassName($entityType) @@ -206,6 +213,7 @@ class EntityModel extends Eloquent /** * @param $entityType + * * @return string */ public static function getTransformerName($entityType) @@ -222,13 +230,14 @@ class EntityModel extends Eloquent public function setNullValues() { foreach ($this->fillable as $field) { - if (strstr($field, '_id') && !$this->$field) { + if (strstr($field, '_id') && ! $this->$field) { $this->$field = null; } } } // converts "App\Models\Client" to "client_id" + /** * @return string */ @@ -236,13 +245,15 @@ class EntityModel extends Eloquent { $class = get_class($this); $parts = explode('\\', $class); - $name = $parts[count($parts)-1]; + $name = $parts[count($parts) - 1]; + return strtolower($name) . '_id'; } /** * @param $data * @param $entityType + * * @return bool|string */ public static function validate($data, $entityType, $entity = false) diff --git a/app/Models/Expense.php b/app/Models/Expense.php index d0b52bcb4929..2ebd51d18975 100644 --- a/app/Models/Expense.php +++ b/app/Models/Expense.php @@ -1,13 +1,15 @@ - 'expense_date', ]; } + /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ @@ -134,7 +137,7 @@ class Expense extends EntityModel if ($this->transaction_id) { return $this->transaction_id; } elseif ($this->public_notes) { - return mb_strimwidth($this->public_notes, 0, 16, "..."); + return mb_strimwidth($this->public_notes, 0, 16, '...'); } else { return '#' . $this->public_id; } @@ -197,6 +200,7 @@ class Expense extends EntityModel /** * @param $query * @param null $bankdId + * * @return mixed */ public function scopeBankId($query, $bankdId = null) diff --git a/app/Models/ExpenseCategory.php b/app/Models/ExpenseCategory.php index 77782e5b85ef..ba07e60c77bc 100644 --- a/app/Models/ExpenseCategory.php +++ b/app/Models/ExpenseCategory.php @@ -1,10 +1,12 @@ -present()->clientPortalLink(); } - if ($iframe_url && !$forceOnsite) { + if ($iframe_url && ! $forceOnsite) { return "{$iframe_url}?{$this->invitation_key}"; } elseif ($this->account->subdomain) { $url = Utils::replaceSubdomain($url, $account->subdomain); diff --git a/app/Models/Invoice.php b/app/Models/Invoice.php index b36a0ca5b2b0..fad799d06d5d 100644 --- a/app/Models/Invoice.php +++ b/app/Models/Invoice.php @@ -1,19 +1,21 @@ -isType(INVOICE_TYPE_STANDARD) && !$this->is_recurring && $this->is_public; + return $this->isType(INVOICE_TYPE_STANDARD) && ! $this->is_recurring && $this->is_public; } /** @@ -234,6 +236,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param bool $calculate + * * @return int|mixed */ public function getAmountPaid($calculate = false) @@ -250,9 +253,10 @@ class Invoice extends EntityModel implements BalanceAffecting } $amount += $payment->getCompletedAmount(); } + return $amount; } else { - return ($this->amount - $this->balance); + return $this->amount - $this->balance; } } @@ -374,6 +378,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $query + * * @return mixed */ public function scopeInvoices($query) @@ -384,6 +389,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $query + * * @return mixed */ public function scopeRecurring($query) @@ -394,6 +400,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $query + * * @return mixed */ public function scopeQuotes($query) @@ -405,6 +412,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $query * @param $typeId + * * @return mixed */ public function scopeInvoiceType($query, $typeId) @@ -414,6 +422,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $typeId + * * @return bool */ public function isType($typeId) @@ -501,7 +510,7 @@ class Invoice extends EntityModel implements BalanceAffecting // if the user marks it as sent rather than acually sending it // then we won't track it in the activity log - if (!$notify) { + if (! $notify) { return; } @@ -514,7 +523,7 @@ class Invoice extends EntityModel implements BalanceAffecting public function markViewed() { - if (!$this->isViewed()) { + if (! $this->isViewed()) { $this->invoice_status_id = INVOICE_STATUS_VIEWED; $this->save(); } @@ -583,6 +592,7 @@ class Invoice extends EntityModel implements BalanceAffecting public function getFileName() { $entityType = $this->getEntityType(); + return trans("texts.$entityType") . '_' . $this->invoice_number . '.pdf'; } @@ -636,7 +646,7 @@ class Invoice extends EntityModel implements BalanceAffecting } // it isn't considered overdue until the end of the day - return time() > (strtotime($dueDate) + (60*60*24)); + return time() > (strtotime($dueDate) + (60 * 60 * 24)); } public function statusClass() @@ -651,6 +661,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $invoice + * * @return string */ public static function calcLink($invoice) @@ -903,12 +914,13 @@ class Invoice extends EntityModel implements BalanceAffecting } /** - * @return bool|\Recurr\RecurrenceCollection * @throws \Recurr\Exception\MissingData + * + * @return bool|\Recurr\RecurrenceCollection */ public function getSchedule() { - if (!$this->start_date || !$this->is_recurring || !$this->frequency_id) { + if (! $this->start_date || ! $this->is_recurring || ! $this->frequency_id) { return false; } @@ -941,12 +953,13 @@ class Invoice extends EntityModel implements BalanceAffecting */ public function getNextSendDate() { - if ($this->start_date && !$this->last_sent_date) { + if ($this->start_date && ! $this->last_sent_date) { $startDate = $this->getOriginal('start_date') . ' ' . $this->account->recurring_hour . ':00:00'; + return $this->account->getDateTime($startDate); } - if (!$schedule = $this->getSchedule()) { + if (! $schedule = $this->getSchedule()) { return null; } @@ -959,11 +972,12 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param null $invoice_date + * * @return mixed|null */ public function getDueDate($invoice_date = null) { - if (!$this->is_recurring) { + if (! $this->is_recurring) { return $this->due_date ? $this->due_date : null; } else { $now = time(); @@ -983,17 +997,17 @@ class Invoice extends EntityModel implements BalanceAffecting // The year is always 1998; January is 1st, 2nd, last day of the month. // February is 1st Sunday after, 1st Monday after, ..., through 4th Saturday after. $dueDateVal = strtotime($this->due_date); - $monthVal = (int)date('n', $dueDateVal); - $dayVal = (int)date('j', $dueDateVal); + $monthVal = (int) date('n', $dueDateVal); + $dayVal = (int) date('j', $dueDateVal); $dueDate = false; if ($monthVal == 1) {// January; day of month - $currentDay = (int)date('j', $now); - $lastDayOfMonth = (int)date('t', $now); + $currentDay = (int) date('j', $now); + $lastDayOfMonth = (int) date('t', $now); - $dueYear = (int)date('Y', $now);// This year - $dueMonth = (int)date('n', $now);// This month - $dueDay = $dayVal;// The day specified for the invoice + $dueYear = (int) date('Y', $now); // This year + $dueMonth = (int) date('n', $now); // This month + $dueDay = $dayVal; // The day specified for the invoice if ($dueDay > $lastDayOfMonth) { // No later than the end of the month @@ -1007,7 +1021,7 @@ class Invoice extends EntityModel implements BalanceAffecting // Reset the due day $dueDay = $dayVal; - $lastDayOfMonth = (int)date('t', mktime(0, 0, 0, $dueMonth, 1, $dueYear));// The number of days in next month + $lastDayOfMonth = (int) date('t', mktime(0, 0, 0, $dueMonth, 1, $dueYear)); // The number of days in next month // Check against the last day again if ($dueDay > $lastDayOfMonth) { @@ -1021,22 +1035,24 @@ class Invoice extends EntityModel implements BalanceAffecting $ordinals = ['first', 'second', 'third', 'fourth']; $daysOfWeek = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']; - $ordinalIndex = ceil($dayVal / 7) - 1;// 1-7 are "first"; 8-14 are "second", etc. - $dayOfWeekIndex = ($dayVal - 1) % 7;// 1,8,15,22 are Sunday, 2,9,16,23 are Monday, etc. - $dayStr = $ordinals[$ordinalIndex] . ' ' . $daysOfWeek[$dayOfWeekIndex];// "first sunday", "first monday", etc. + $ordinalIndex = ceil($dayVal / 7) - 1; // 1-7 are "first"; 8-14 are "second", etc. + $dayOfWeekIndex = ($dayVal - 1) % 7; // 1,8,15,22 are Sunday, 2,9,16,23 are Monday, etc. + $dayStr = $ordinals[$ordinalIndex] . ' ' . $daysOfWeek[$dayOfWeekIndex]; // "first sunday", "first monday", etc. $dueDate = strtotime($dayStr, $now); } if ($dueDate) { - return date('Y-m-d', $dueDate);// SQL format + return date('Y-m-d', $dueDate); // SQL format } } elseif ($this->client->payment_terms != 0) { // No custom due date set for this invoice; use the client's payment terms $days = $this->client->defaultDaysDue(); + return date('Y-m-d', strtotime('+'.$days.' day', $now)); } elseif ($this->account->payment_terms != 0) { $days = $this->account->defaultDaysDue(); + return date('Y-m-d', strtotime('+'.$days.' day', $now)); } } @@ -1048,17 +1064,18 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param int $min * @param int $max + * * @return null */ public function getPrettySchedule($min = 1, $max = 10) { - if (!$schedule = $this->getSchedule($max)) { + if (! $schedule = $this->getSchedule($max)) { return null; } $dates = []; - for ($i=$min; $igetStart(); $date = $this->account->formatDate($dateStart); @@ -1146,7 +1163,7 @@ class Invoice extends EntityModel implements BalanceAffecting $dayOfMonthToday = date('j'); $dayOfMonthStart = date('j', strtotime($this->start_date)); - if (!$this->last_sent_date) { + if (! $this->last_sent_date) { return true; } else { $date1 = new DateTime($this->last_sent_date); @@ -1209,11 +1226,13 @@ class Invoice extends EntityModel implements BalanceAffecting $pdfString = strip_tags($pdfString); } catch (\Exception $exception) { Utils::logError("PhantomJS - Failed to create pdf: {$exception->getMessage()}"); + return false; } if (! $pdfString || strlen($pdfString) < 200) { Utils::logError("PhantomJS - Failed to create pdf: {$pdfString}"); + return false; } @@ -1223,6 +1242,7 @@ class Invoice extends EntityModel implements BalanceAffecting /** * @param $invoiceItem * @param $invoiceTotal + * * @return float|int */ public function getItemTaxable($invoiceItem, $invoiceTotal) @@ -1274,8 +1294,10 @@ class Invoice extends EntityModel implements BalanceAffecting // if $calculatePaid is true we'll loop through each payment to // determine the sum, otherwise we'll use the cached paid_to_date amount + /** * @param bool $calculatePaid + * * @return array */ public function getTaxes($calculatePaid = false) @@ -1286,13 +1308,13 @@ class Invoice extends EntityModel implements BalanceAffecting if ($this->tax_name1) { $invoiceTaxAmount = round($taxable * ($this->tax_rate1 / 100), 2); - $invoicePaidAmount = floatVal($this->amount) && $invoiceTaxAmount ? ($paidAmount / $this->amount * $invoiceTaxAmount) : 0; + $invoicePaidAmount = floatval($this->amount) && $invoiceTaxAmount ? ($paidAmount / $this->amount * $invoiceTaxAmount) : 0; $this->calculateTax($taxes, $this->tax_name1, $this->tax_rate1, $invoiceTaxAmount, $invoicePaidAmount); } if ($this->tax_name2) { $invoiceTaxAmount = round($taxable * ($this->tax_rate2 / 100), 2); - $invoicePaidAmount = floatVal($this->amount) && $invoiceTaxAmount ? ($paidAmount / $this->amount * $invoiceTaxAmount) : 0; + $invoicePaidAmount = floatval($this->amount) && $invoiceTaxAmount ? ($paidAmount / $this->amount * $invoiceTaxAmount) : 0; $this->calculateTax($taxes, $this->tax_name2, $this->tax_rate2, $invoiceTaxAmount, $invoicePaidAmount); } @@ -1301,13 +1323,13 @@ class Invoice extends EntityModel implements BalanceAffecting if ($invoiceItem->tax_name1) { $itemTaxAmount = round($taxable * ($invoiceItem->tax_rate1 / 100), 2); - $itemPaidAmount = floatVal($this->amount) && $itemTaxAmount ? ($paidAmount / $this->amount * $itemTaxAmount) : 0; + $itemPaidAmount = floatval($this->amount) && $itemTaxAmount ? ($paidAmount / $this->amount * $itemTaxAmount) : 0; $this->calculateTax($taxes, $invoiceItem->tax_name1, $invoiceItem->tax_rate1, $itemTaxAmount, $itemPaidAmount); } if ($invoiceItem->tax_name2) { $itemTaxAmount = round($taxable * ($invoiceItem->tax_rate2 / 100), 2); - $itemPaidAmount = floatVal($this->amount) && $itemTaxAmount ? ($paidAmount / $this->amount * $itemTaxAmount) : 0; + $itemPaidAmount = floatval($this->amount) && $itemTaxAmount ? ($paidAmount / $this->amount * $itemTaxAmount) : 0; $this->calculateTax($taxes, $invoiceItem->tax_name2, $invoiceItem->tax_rate2, $itemTaxAmount, $itemPaidAmount); } } @@ -1335,9 +1357,9 @@ class Invoice extends EntityModel implements BalanceAffecting if (! isset($taxes[$key])) { $taxes[$key] = [ 'name' => $name, - 'rate' => $rate+0, + 'rate' => $rate + 0, 'amount' => 0, - 'paid' => 0 + 'paid' => 0, ]; } @@ -1353,6 +1375,7 @@ class Invoice extends EntityModel implements BalanceAffecting if (count($this->documents)) { return true; } + return $this->hasExpenseDocuments(); } @@ -1366,6 +1389,7 @@ class Invoice extends EntityModel implements BalanceAffecting return true; } } + return false; } @@ -1374,13 +1398,13 @@ class Invoice extends EntityModel implements BalanceAffecting */ public function getAutoBillEnabled() { - if (!$this->is_recurring) { + if (! $this->is_recurring) { $recurInvoice = $this->recurring_invoice; } else { $recurInvoice = $this; } - if (!$recurInvoice) { + if (! $recurInvoice) { return false; } @@ -1418,7 +1442,7 @@ class Invoice extends EntityModel implements BalanceAffecting } Invoice::creating(function ($invoice) { - if (!$invoice->is_recurring) { + if (! $invoice->is_recurring) { $invoice->account->incrementCounter($invoice); } }); diff --git a/app/Models/InvoiceDesign.php b/app/Models/InvoiceDesign.php index 4db185be309c..a28f35e427b3 100644 --- a/app/Models/InvoiceDesign.php +++ b/app/Models/InvoiceDesign.php @@ -1,11 +1,13 @@ -client) { + if (! $this->client) { return false; } diff --git a/app/Models/Payment.php b/app/Models/Payment.php index 0d2634c3ed04..6819e31cc1f1 100644 --- a/app/Models/Payment.php +++ b/app/Models/Payment.php @@ -1,16 +1,18 @@ -amount; } @@ -283,14 +286,16 @@ class Payment extends EntityModel */ public function getBankDataAttribute() { - if (!$this->routing_number) { + if (! $this->routing_number) { return null; } + return PaymentMethod::lookupBankData($this->routing_number); } /** * @param $bank_name + * * @return null */ public function getBankNameAttribute($bank_name) @@ -300,11 +305,12 @@ class Payment extends EntityModel } $bankData = $this->bank_data; - return $bankData?$bankData->name:null; + return $bankData ? $bankData->name : null; } /** * @param $value + * * @return null|string */ public function getLast4Attribute($value) @@ -328,7 +334,6 @@ class Payment extends EntityModel return static::$statusClasses[$statusId]; } - public function statusClass() { return static::calcStatusClass($this->payment_status_id); @@ -337,6 +342,7 @@ class Payment extends EntityModel public function statusLabel() { $amount = $this->account->formatMoney($this->refunded, $this->client); + return static::calcStatusLabel($this->payment_status_id, $this->payment_status->name, $amount); } diff --git a/app/Models/PaymentLibrary.php b/app/Models/PaymentLibrary.php index d9445015d2b3..99f5ebabc2ed 100644 --- a/app/Models/PaymentLibrary.php +++ b/app/Models/PaymentLibrary.php @@ -1,9 +1,11 @@ -routing_number) { + if (! $this->routing_number) { return null; } + return static::lookupBankData($this->routing_number); } /** * @param $bank_name + * * @return null */ public function getBankNameAttribute($bank_name) @@ -94,11 +98,12 @@ class PaymentMethod extends EntityModel } $bankData = $this->bank_data; - return $bankData?$bankData->name:null; + return $bankData ? $bankData->name : null; } /** * @param $value + * * @return null|string */ public function getLast4Attribute($value) @@ -109,6 +114,7 @@ class PaymentMethod extends EntityModel /** * @param $query * @param $clientId + * * @return mixed */ public function scopeClientId($query, $clientId) @@ -141,6 +147,7 @@ class PaymentMethod extends EntityModel /** * @param $routingNumber + * * @return mixed|null|\stdClass|string */ public static function lookupBankData($routingNumber) @@ -153,12 +160,12 @@ class PaymentMethod extends EntityModel $dataPath = base_path('vendor/gatepay/FedACHdir/FedACHdir.txt'); - if (!file_exists($dataPath) || !$size = filesize($dataPath)) { + if (! file_exists($dataPath) || ! $size = filesize($dataPath)) { return 'Invalid data file'; } $lineSize = 157; - $numLines = $size/$lineSize; + $numLines = $size / $lineSize; if ($numLines % 1 != 0) { // The number of lines should be an integer @@ -197,11 +204,13 @@ class PaymentMethod extends EntityModel } } - if (!empty($data)) { + if (! empty($data)) { Cache::put('bankData:'.$routingNumber, $data, 5); + return $data; } else { Cache::put('bankData:'.$routingNumber, false, 5); + return null; } } diff --git a/app/Models/PaymentStatus.php b/app/Models/PaymentStatus.php index d4c06899e56e..f0c172cb220a 100644 --- a/app/Models/PaymentStatus.php +++ b/app/Models/PaymentStatus.php @@ -1,9 +1,11 @@ -where('product_key', '=', $key)->first(); + return self::scope()->where('product_key', '=', $key)->first(); } /** diff --git a/app/Models/Project.php b/app/Models/Project.php index 63f576e9b70f..834aef98b00e 100644 --- a/app/Models/Project.php +++ b/app/Models/Project.php @@ -1,10 +1,12 @@ -time_log) ?: []; foreach ($parts as $part) { - if (count($part) == 1 || !$part[1]) { + if (count($part) == 1 || ! $part[1]) { $duration += time() - $part[0]; } else { $duration += $part[1] - $part[0]; @@ -146,9 +151,9 @@ class Task extends EntityModel public function getCurrentDuration() { $parts = json_decode($this->time_log) ?: []; - $part = $parts[count($parts)-1]; + $part = $parts[count($parts) - 1]; - if (count($part) == 1 || !$part[1]) { + if (count($part) == 1 || ! $part[1]) { return time() - $part[0]; } else { return 0; @@ -161,6 +166,7 @@ class Task extends EntityModel public function hasPreviousDuration() { $parts = json_decode($this->time_log) ?: []; + return count($parts) && (count($parts[0]) && $parts[0][1]); } @@ -173,7 +179,7 @@ class Task extends EntityModel } /** - * Gets the route to the tasks edit action + * Gets the route to the tasks edit action. * * @return string */ @@ -190,7 +196,7 @@ class Task extends EntityModel public function getDisplayName() { if ($this->description) { - return mb_strimwidth($this->description, 0, 16, "..."); + return mb_strimwidth($this->description, 0, 16, '...'); } return '#' . $this->public_id; @@ -274,7 +280,6 @@ class Task extends EntityModel } } - Task::created(function ($task) { event(new TaskWasCreated($task)); }); diff --git a/app/Models/TaxRate.php b/app/Models/TaxRate.php index 6bba12fc4f26..356369e0f806 100644 --- a/app/Models/TaxRate.php +++ b/app/Models/TaxRate.php @@ -1,9 +1,11 @@ -$field ?: ''; } /** * @param $entityType + * * @return bool */ public function getNumberPattern($entityType) @@ -95,11 +101,13 @@ trait GeneratesNumbers } $field = "{$entityType}_number_pattern"; + return $this->$field; } /** * @param $entityType + * * @return bool */ public function hasNumberPattern($entityType) @@ -109,6 +117,7 @@ trait GeneratesNumbers /** * @param $entityType + * * @return string */ public function hasClientNumberPattern($invoice) @@ -120,6 +129,7 @@ trait GeneratesNumbers /** * @param $entity + * * @return bool|mixed */ public function applyNumberPattern($entity, $counter = 0) @@ -128,7 +138,7 @@ trait GeneratesNumbers $counter = $counter ?: $this->getCounter($entityType); $pattern = $this->getNumberPattern($entityType); - if (!$pattern) { + if (! $pattern) { return false; } @@ -165,11 +175,12 @@ trait GeneratesNumbers /** * @param $pattern * @param $invoice + * * @return mixed */ private function getClientInvoiceNumber($pattern, $invoice) { - if (!$invoice->client) { + if (! $invoice->client) { return $pattern; } @@ -190,6 +201,7 @@ trait GeneratesNumbers /** * @param $entityType + * * @return mixed */ public function getCounter($entityType) @@ -205,11 +217,13 @@ trait GeneratesNumbers /** * @param $entityType + * * @return mixed|string */ public function previewNextInvoiceNumber($entityType = ENTITY_INVOICE) { $invoice = $this->createInvoice($entityType); + return $this->getNextNumber($invoice); } diff --git a/app/Models/Traits/PresentsInvoice.php b/app/Models/Traits/PresentsInvoice.php index e739036d54fa..bb9920f23c35 100644 --- a/app/Models/Traits/PresentsInvoice.php +++ b/app/Models/Traits/PresentsInvoice.php @@ -1,7 +1,9 @@ -invoice_fields) { $fields = json_decode($this->invoice_fields, true); + return $this->applyLabels($fields); } else { return $this->getDefaultInvoiceFields(); @@ -120,7 +123,7 @@ trait PresentsInvoice 'account.custom_value1', 'account.custom_value2', '.blank', - ] + ], ]; return $this->applyLabels($fields); @@ -230,7 +233,7 @@ trait PresentsInvoice 'client.custom_value1' => 'custom_client_label1', 'client.custom_value2' => 'custom_client_label2', 'account.custom_value1' => 'custom_label1', - 'account.custom_value2' => 'custom_label2' + 'account.custom_value2' => 'custom_label2', ] as $field => $property) { $data[$field] = $this->$property ?: trans('texts.custom_field'); } diff --git a/app/Models/Traits/SendsEmails.php b/app/Models/Traits/SendsEmails.php index 402293cba2d3..883f97b5ffa5 100644 --- a/app/Models/Traits/SendsEmails.php +++ b/app/Models/Traits/SendsEmails.php @@ -1,10 +1,12 @@ -theme_id || in_array($this->theme_id, [2, 3, 5, 6, 7, 8, 10, 11, 12]); + return ! $this->theme_id || in_array($this->theme_id, [2, 3, 5, 6, 7, 8, 10, 11, 12]); } /** @@ -191,6 +194,7 @@ class User extends Authenticatable /** * @param bool $success * @param bool $forced + * * @return bool */ public function afterSave($success = true, $forced = false) @@ -268,7 +272,7 @@ class User extends Authenticatable */ public static function onUpdatedUser($user) { - if (!$user->getOriginal('email') + if (! $user->getOriginal('email') || $user->getOriginal('email') == TEST_USERNAME || $user->getOriginal('username') == TEST_USERNAME || $user->getOriginal('email') == 'tests@bitrock.com') { @@ -288,14 +292,13 @@ class User extends Authenticatable && $this->getOriginal('confirmed'); } - - - /** - * Set the permissions attribute on the model. - * - * @param mixed $value - * @return $this - */ + /** + * Set the permissions attribute on the model. + * + * @param mixed $value + * + * @return $this + */ protected function setPermissionsAttribute($value) { if (empty($value)) { @@ -316,9 +319,10 @@ class User extends Authenticatable } /** - * Expands the value of the permissions attribute + * Expands the value of the permissions attribute. + * + * @param mixed $value * - * @param mixed $value * @return mixed */ protected function getPermissionsAttribute($value) @@ -334,18 +338,19 @@ class User extends Authenticatable } /** - * Checks to see if the user has the required permission + * Checks to see if the user has the required permission. * - * @param mixed $permission Either a single permission or an array of possible permissions - * @param boolean True to require all permissions, false to require only one - * @return boolean + * @param mixed $permission Either a single permission or an array of possible permissions + * @param bool True to require all permissions, false to require only one + * + * @return bool */ public function hasPermission($permission, $requireAll = false) { if ($this->is_admin) { return true; } elseif (is_string($permission)) { - return !empty($this->permissions[$permission]); + return ! empty($this->permissions[$permission]); } elseif (is_array($permission)) { if ($requireAll) { return count(array_diff($permission, $this->permissions)) == 0; @@ -359,11 +364,12 @@ class User extends Authenticatable /** * @param $entity + * * @return bool */ public function owns($entity) { - return !empty($entity->user_id) && $entity->user_id == $this->id; + return ! empty($entity->user_id) && $entity->user_id == $this->id; } /** @@ -374,7 +380,6 @@ class User extends Authenticatable return $this->hasPermission('view_all') ? false : $this->id; } - public function caddAddUsers() { if (! Utils::isNinjaProd()) { @@ -396,8 +401,8 @@ class User extends Authenticatable public function canCreateOrEdit($entityType, $entity = false) { - return (($entity && $this->can('edit', $entity)) - || (!$entity && $this->can('create', $entityType))); + return ($entity && $this->can('edit', $entity)) + || (! $entity && $this->can('create', $entityType)); } public function primaryAccount() diff --git a/app/Models/UserAccount.php b/app/Models/UserAccount.php index 63200eb25f07..f7a8a009dabe 100644 --- a/app/Models/UserAccount.php +++ b/app/Models/UserAccount.php @@ -1,9 +1,11 @@ -$field && $this->$field == $userId) { return true; } } + return false; } @@ -40,9 +44,9 @@ class UserAccount extends Eloquent return; } - for ($i=1; $i<=5; $i++) { + for ($i = 1; $i <= 5; $i++) { $field = "user_id{$i}"; - if (!$this->$field) { + if (! $this->$field) { $this->$field = $userId; break; } @@ -54,11 +58,11 @@ class UserAccount extends Eloquent */ public function removeUserId($userId) { - if (!$userId || !self::hasUserId($userId)) { + if (! $userId || ! self::hasUserId($userId)) { return; } - for ($i=1; $i<=5; $i++) { + for ($i = 1; $i <= 5; $i++) { $field = "user_id{$i}"; if ($this->$field && $this->$field == $userId) { $this->$field = null; diff --git a/app/Models/Vendor.php b/app/Models/Vendor.php index 3fe1a6dbcbbd..1dd933396ce6 100644 --- a/app/Models/Vendor.php +++ b/app/Models/Vendor.php @@ -1,15 +1,17 @@ -country && $this->country->swap_postal_code; + return Utils::cityStateZip($this->city, $this->state, $this->postal_code, $swap); } @@ -319,7 +323,7 @@ class Vendor extends EntityModel return $this->currency_id; } - if (!$this->account) { + if (! $this->account) { $this->load('account'); } @@ -356,7 +360,6 @@ Vendor::updated(function ($vendor) { event(new VendorWasUpdated($vendor)); }); - Vendor::deleting(function ($vendor) { $vendor->setNullValues(); }); diff --git a/app/Models/VendorContact.php b/app/Models/VendorContact.php index df1b40c9365c..cb594c26929a 100644 --- a/app/Models/VendorContact.php +++ b/app/Models/VendorContact.php @@ -1,11 +1,13 @@ -gateway_id == GATEWAY_CUSTOM) { $accountGateway = $this->getAccountGateway($model->id); $name = $accountGateway->getConfigField('name') . ' [' . trans('texts.custom') . ']'; + return link_to("gateways/{$model->public_id}/edit", $name)->toHtml(); } elseif ($model->gateway_id != GATEWAY_WEPAY) { return link_to("gateways/{$model->public_id}/edit", $model->name)->toHtml(); @@ -32,10 +35,10 @@ class AccountGatewayDatatable extends EntityDatatable $config = $accountGateway->getConfig(); $endpoint = WEPAY_ENVIRONMENT == WEPAY_STAGE ? 'https://stage.wepay.com/' : 'https://www.wepay.com/'; $wepayAccountId = $config->accountId; - $wepayState = isset($config->state)?$config->state:null; + $wepayState = isset($config->state) ? $config->state : null; $linkText = $model->name; $url = $endpoint.'account/'.$wepayAccountId; - $html = link_to($url, $linkText, ['target'=>'_blank'])->toHtml(); + $html = link_to($url, $linkText, ['target' => '_blank'])->toHtml(); try { if ($wepayState == 'action_required') { @@ -54,7 +57,7 @@ class AccountGatewayDatatable extends EntityDatatable return $html; } - } + }, ], [ 'limit', @@ -65,7 +68,7 @@ class AccountGatewayDatatable extends EntityDatatable $accountGateway = $this->getAccountGateway($model->id); $paymentDriver = $accountGateway->paymentDriver(); $gatewayTypes = $paymentDriver->gatewayTypes(); - $gatewayTypes = array_diff($gatewayTypes, array(GATEWAY_TYPE_TOKEN)); + $gatewayTypes = array_diff($gatewayTypes, [GATEWAY_TYPE_TOKEN]); } $html = ''; @@ -86,11 +89,11 @@ class AccountGatewayDatatable extends EntityDatatable $html .= Utils::formatMoney($accountGatewaySettings->min_limit) . ' - ' . Utils::formatMoney($accountGatewaySettings->max_limit); } elseif ($accountGatewaySettings && $accountGatewaySettings->min_limit !== null) { $html .= trans('texts.min_limit', - array('min' => Utils::formatMoney($accountGatewaySettings->min_limit)) + ['min' => Utils::formatMoney($accountGatewaySettings->min_limit)] ); } elseif ($accountGatewaySettings && $accountGatewaySettings->max_limit !== null) { $html .= trans('texts.max_limit', - array('max' => Utils::formatMoney($accountGatewaySettings->max_limit)) + ['max' => Utils::formatMoney($accountGatewaySettings->max_limit)] ); } else { $html .= trans('texts.no_limit'); @@ -98,7 +101,7 @@ class AccountGatewayDatatable extends EntityDatatable } return $html; - } + }, ], ]; } @@ -112,37 +115,38 @@ class AccountGatewayDatatable extends EntityDatatable return $model->resendConfirmationUrl; }, function ($model) { - return !$model->deleted_at && $model->gateway_id == GATEWAY_WEPAY && !empty($model->resendConfirmationUrl); - } - ] , [ + return ! $model->deleted_at && $model->gateway_id == GATEWAY_WEPAY && ! empty($model->resendConfirmationUrl); + }, + ], [ uctrans('texts.edit_gateway'), function ($model) { return URL::to("gateways/{$model->public_id}/edit"); }, function ($model) { - return !$model->deleted_at; - } + return ! $model->deleted_at; + }, ], [ uctrans('texts.finish_setup'), function ($model) { return $model->setupUrl; }, function ($model) { - return !$model->deleted_at && $model->gateway_id == GATEWAY_WEPAY && !empty($model->setupUrl); - } + return ! $model->deleted_at && $model->gateway_id == GATEWAY_WEPAY && ! empty($model->setupUrl); + }, ], [ uctrans('texts.manage_account'), function ($model) { $accountGateway = $this->getAccountGateway($model->id); $endpoint = WEPAY_ENVIRONMENT == WEPAY_STAGE ? 'https://stage.wepay.com/' : 'https://www.wepay.com/'; + return [ 'url' => $endpoint.'account/'.$accountGateway->getConfig()->accountId, - 'attributes' => 'target="_blank"' + 'attributes' => 'target="_blank"', ]; }, function ($model) { - return !$model->deleted_at && $model->gateway_id == GATEWAY_WEPAY; - } + return ! $model->deleted_at && $model->gateway_id == GATEWAY_WEPAY; + }, ], [ uctrans('texts.terms_of_service'), function ($model) { @@ -150,8 +154,8 @@ class AccountGatewayDatatable extends EntityDatatable }, function ($model) { return $model->gateway_id == GATEWAY_WEPAY; - } - ] + }, + ], ]; foreach (Cache::get('gatewayTypes') as $gatewayType) { @@ -177,7 +181,7 @@ class AccountGatewayDatatable extends EntityDatatable return in_array($gatewayType->id, $gatewayTypes); } - } + }, ]; } diff --git a/app/Ninja/Datatables/ActivityDatatable.php b/app/Ninja/Datatables/ActivityDatatable.php index 0261bfc3bb1d..8c3785168af0 100644 --- a/app/Ninja/Datatables/ActivityDatatable.php +++ b/app/Ninja/Datatables/ActivityDatatable.php @@ -1,4 +1,6 @@ -created_at)); - } + }, ], [ 'activity_type_id', @@ -39,20 +41,20 @@ class ActivityDatatable extends EntityDatatable } return $str; - } + }, ], [ 'balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); - } + }, ], [ 'adjustment', function ($model) { return $model->adjustment != 0 ? Utils::wrapAdjustment($model->adjustment, $model->currency_id, $model->country_id) : ''; - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Datatables/BankAccountDatatable.php b/app/Ninja/Datatables/BankAccountDatatable.php index 68494013f7b6..6adab1504d6a 100644 --- a/app/Ninja/Datatables/BankAccountDatatable.php +++ b/app/Ninja/Datatables/BankAccountDatatable.php @@ -1,4 +1,6 @@ -public_id}/edit"); }, - ] + ], ]; } } diff --git a/app/Ninja/Datatables/ClientDatatable.php b/app/Ninja/Datatables/ClientDatatable.php index 4cfe477825b3..6913274f977c 100644 --- a/app/Ninja/Datatables/ClientDatatable.php +++ b/app/Ninja/Datatables/ClientDatatable.php @@ -1,8 +1,10 @@ -public_id}", $model->name ?: '')->toHtml(); - } + }, ], [ 'contact', function ($model) { return link_to("clients/{$model->public_id}", $model->contact ?: '')->toHtml(); - } + }, ], [ 'email', function ($model) { return link_to("clients/{$model->public_id}", $model->email ?: '')->toHtml(); - } + }, ], [ 'client_created_at', function ($model) { return Utils::timestampToDateString(strtotime($model->created_at)); - } + }, ], [ 'last_login', function ($model) { return Utils::timestampToDateString(strtotime($model->last_login)); - } + }, ], [ 'balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); - } - ] + }, + ], ]; } @@ -61,7 +63,7 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_CLIENT, $model->user_id]); - } + }, ], [ '--divider--', function () { @@ -69,8 +71,9 @@ class ClientDatatable extends EntityDatatable }, function ($model) { $user = Auth::user(); + return $user->can('editByOwner', [ENTITY_CLIENT, $model->user_id]) && ($user->can('create', ENTITY_TASK) || $user->can('create', ENTITY_INVOICE)); - } + }, ], [ trans('texts.new_task'), @@ -79,7 +82,7 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_TASK); - } + }, ], [ trans('texts.new_invoice'), @@ -88,7 +91,7 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_INVOICE); - } + }, ], [ trans('texts.new_quote'), @@ -97,7 +100,7 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->hasFeature(FEATURE_QUOTES) && Auth::user()->can('create', ENTITY_QUOTE); - } + }, ], [ '--divider--', function () { @@ -105,8 +108,9 @@ class ClientDatatable extends EntityDatatable }, function ($model) { $user = Auth::user(); + return ($user->can('create', ENTITY_TASK) || $user->can('create', ENTITY_INVOICE)) && ($user->can('create', ENTITY_PAYMENT) || $user->can('create', ENTITY_CREDIT) || $user->can('create', ENTITY_EXPENSE)); - } + }, ], [ trans('texts.enter_payment'), @@ -115,7 +119,7 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_PAYMENT); - } + }, ], [ trans('texts.enter_credit'), @@ -124,7 +128,7 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_CREDIT); - } + }, ], [ trans('texts.enter_expense'), @@ -133,8 +137,8 @@ class ClientDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_EXPENSE); - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Datatables/CreditDatatable.php b/app/Ninja/Datatables/CreditDatatable.php index 4d7b3e1616bf..3bbf4430fa72 100644 --- a/app/Ninja/Datatables/CreditDatatable.php +++ b/app/Ninja/Datatables/CreditDatatable.php @@ -1,8 +1,10 @@ -can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { return Utils::getClientDisplayName($model); } return $model->client_public_id ? link_to("clients/{$model->client_public_id}", Utils::getClientDisplayName($model))->toHtml() : ''; }, - ! $this->hideClient + ! $this->hideClient, ], [ 'amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id) . ''; - } + }, ], [ 'balance', function ($model) { return Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); - } + }, ], [ 'credit_date', @@ -43,14 +45,14 @@ class CreditDatatable extends EntityDatatable } return link_to("credits/{$model->public_id}/edit", Utils::fromSqlDate($model->credit_date))->toHtml(); - } + }, ], [ 'private_notes', function ($model) { return $model->private_notes; - } - ] + }, + ], ]; } @@ -64,7 +66,7 @@ class CreditDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_CREDIT, $model->user_id]); - } + }, ], [ trans('texts.apply_credit'), @@ -73,8 +75,8 @@ class CreditDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_PAYMENT); - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Datatables/EntityDatatable.php b/app/Ninja/Datatables/EntityDatatable.php index ef177ae2bf76..008b1f877d12 100644 --- a/app/Ninja/Datatables/EntityDatatable.php +++ b/app/Ninja/Datatables/EntityDatatable.php @@ -1,4 +1,6 @@ - mtrans($this->entityType, 'delete_'.$this->entityType), 'url' => 'javascript:submitForm_'.$this->entityType.'("delete")', - ] + ], ]; } @@ -53,7 +55,7 @@ class EntityDatatable foreach ($columns as $column) { if (count($column) == 3) { // third column is optionally used to determine visibility - if (!$column[2]) { + if (! $column[2]) { continue; } } diff --git a/app/Ninja/Datatables/ExpenseCategoryDatatable.php b/app/Ninja/Datatables/ExpenseCategoryDatatable.php index 741872c02c53..f73364066ac6 100644 --- a/app/Ninja/Datatables/ExpenseCategoryDatatable.php +++ b/app/Ninja/Datatables/ExpenseCategoryDatatable.php @@ -1,7 +1,9 @@ -public_id}/edit", $model->category)->toHtml(); - } + }, ], ]; } @@ -30,11 +32,11 @@ class ExpenseCategoryDatatable extends EntityDatatable [ trans('texts.edit_category'), function ($model) { - return URL::to("expense_categories/{$model->public_id}/edit") ; + return URL::to("expense_categories/{$model->public_id}/edit"); }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_EXPENSE_CATEGORY, $model->user_id]); - } + }, ], ]; } diff --git a/app/Ninja/Datatables/ExpenseDatatable.php b/app/Ninja/Datatables/ExpenseDatatable.php index a7dc329cf4b0..1073bef63017 100644 --- a/app/Ninja/Datatables/ExpenseDatatable.php +++ b/app/Ninja/Datatables/ExpenseDatatable.php @@ -1,9 +1,11 @@ -vendor_public_id) { - if (!Auth::user()->can('viewByOwner', [ENTITY_VENDOR, $model->vendor_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_VENDOR, $model->vendor_user_id])) { return $model->vendor_name; } @@ -26,13 +28,13 @@ class ExpenseDatatable extends EntityDatatable return ''; } }, - ! $this->hideClient + ! $this->hideClient, ], [ 'client_name', function ($model) { if ($model->client_public_id) { - if (!Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { return Utils::getClientDisplayName($model); } @@ -41,17 +43,17 @@ class ExpenseDatatable extends EntityDatatable return ''; } }, - ! $this->hideClient + ! $this->hideClient, ], [ 'expense_date', function ($model) { - if (!Auth::user()->can('viewByOwner', [ENTITY_EXPENSE, $model->user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_EXPENSE, $model->user_id])) { return Utils::fromSqlDate($model->expense_date); } return link_to("expenses/{$model->public_id}/edit", Utils::fromSqlDate($model->expense_date))->toHtml(); - } + }, ], [ 'amount', @@ -66,25 +68,25 @@ class ExpenseDatatable extends EntityDatatable } return $str; - } + }, ], [ 'category', function ($model) { return $model->category != null ? substr($model->category, 0, 100) : ''; - } + }, ], [ 'public_notes', function ($model) { return $model->public_notes != null ? substr($model->public_notes, 0, 100) : ''; - } + }, ], [ 'status', function ($model) { return self::getStatusLabel($model->invoice_id, $model->should_be_invoiced, $model->balance); - } + }, ], ]; } @@ -95,11 +97,11 @@ class ExpenseDatatable extends EntityDatatable [ trans('texts.edit_expense'), function ($model) { - return URL::to("expenses/{$model->public_id}/edit") ; + return URL::to("expenses/{$model->public_id}/edit"); }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_EXPENSE, $model->user_id]); - } + }, ], [ trans('texts.view_invoice'), @@ -108,7 +110,7 @@ class ExpenseDatatable extends EntityDatatable }, function ($model) { return $model->invoice_public_id && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->invoice_user_id]); - } + }, ], [ trans('texts.invoice_expense'), @@ -116,8 +118,8 @@ class ExpenseDatatable extends EntityDatatable return "javascript:submitForm_expense('invoice', {$model->public_id})"; }, function ($model) { - return ! $model->invoice_id && (!$model->deleted_at || $model->deleted_at == '0000-00-00') && Auth::user()->can('create', ENTITY_INVOICE); - } + return ! $model->invoice_id && (! $model->deleted_at || $model->deleted_at == '0000-00-00') && Auth::user()->can('create', ENTITY_INVOICE); + }, ], ]; } diff --git a/app/Ninja/Datatables/InvoiceDatatable.php b/app/Ninja/Datatables/InvoiceDatatable.php index c84db083f432..24b3b2496189 100644 --- a/app/Ninja/Datatables/InvoiceDatatable.php +++ b/app/Ninja/Datatables/InvoiceDatatable.php @@ -1,9 +1,11 @@ -can('viewByOwner', [ENTITY_INVOICE, $model->user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_INVOICE, $model->user_id])) { return $model->invoice_number; } return link_to("{$entityType}s/{$model->public_id}/edit", $model->invoice_number, ['class' => Utils::getEntityRowClass($model)])->toHtml(); - } + }, ], [ 'client_name', function ($model) { - if (!Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { return Utils::getClientDisplayName($model); } + return link_to("clients/{$model->client_public_id}", Utils::getClientDisplayName($model))->toHtml(); }, - ! $this->hideClient + ! $this->hideClient, ], [ 'date', function ($model) { return Utils::fromSqlDate($model->date); - } + }, ], [ 'amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); - } + }, ], [ 'balance', @@ -53,11 +56,11 @@ class InvoiceDatatable extends EntityDatatable return $model->partial > 0 ? trans('texts.partial_remaining', [ 'partial' => Utils::formatMoney($model->partial, $model->currency_id, $model->country_id), - 'balance' => Utils::formatMoney($model->balance, $model->currency_id, $model->country_id)] + 'balance' => Utils::formatMoney($model->balance, $model->currency_id, $model->country_id), ] ) : Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); }, - $entityType == ENTITY_INVOICE + $entityType == ENTITY_INVOICE, ], [ $entityType == ENTITY_INVOICE ? 'due_date' : 'valid_until', @@ -69,8 +72,8 @@ class InvoiceDatatable extends EntityDatatable 'status', function ($model) use ($entityType) { return $model->quote_invoice_id ? link_to("invoices/{$model->quote_invoice_id}/edit", trans('texts.converted'))->toHtml() : self::getStatusLabel($model); - } - ] + }, + ], ]; } @@ -86,7 +89,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } + }, ], [ trans("texts.clone_{$entityType}"), @@ -95,13 +98,13 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_INVOICE); - } + }, ], [ trans('texts.view_history'), function ($model) use ($entityType) { return URL::to("{$entityType}s/{$entityType}_history/{$model->public_id}"); - } + }, ], [ '--divider--', function () { @@ -109,7 +112,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]) || Auth::user()->can('create', ENTITY_PAYMENT); - } + }, ], [ trans('texts.mark_sent'), @@ -118,7 +121,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) { return $model->invoice_status_id < INVOICE_STATUS_SENT && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } + }, ], [ trans('texts.mark_paid'), @@ -127,7 +130,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) use ($entityType) { return $entityType == ENTITY_INVOICE && $model->balance > 0 && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } + }, ], [ trans('texts.enter_payment'), @@ -136,7 +139,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) use ($entityType) { return $entityType == ENTITY_INVOICE && $model->balance > 0 && Auth::user()->can('create', ENTITY_PAYMENT); - } + }, ], [ trans('texts.view_quote'), @@ -145,7 +148,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) use ($entityType) { return $entityType == ENTITY_INVOICE && $model->quote_id && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } + }, ], [ trans('texts.view_invoice'), @@ -154,7 +157,7 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) use ($entityType) { return $entityType == ENTITY_QUOTE && $model->quote_invoice_id && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } + }, ], [ trans('texts.convert_to_invoice'), @@ -163,8 +166,8 @@ class InvoiceDatatable extends EntityDatatable }, function ($model) use ($entityType) { return $entityType == ENTITY_QUOTE && ! $model->quote_invoice_id && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } - ] + }, + ], ]; } diff --git a/app/Ninja/Datatables/PaymentDatatable.php b/app/Ninja/Datatables/PaymentDatatable.php index 4a3cd5066eb9..f536b454ef41 100644 --- a/app/Ninja/Datatables/PaymentDatatable.php +++ b/app/Ninja/Datatables/PaymentDatatable.php @@ -1,10 +1,12 @@ -can('viewByOwner', [ENTITY_INVOICE, $model->invoice_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_INVOICE, $model->invoice_user_id])) { return $model->invoice_number; } return link_to("invoices/{$model->invoice_public_id}/edit", $model->invoice_number, ['class' => Utils::getEntityRowClass($model)])->toHtml(); - } + }, ], [ 'client_name', function ($model) { - if (!Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { return Utils::getClientDisplayName($model); } return $model->client_public_id ? link_to("clients/{$model->client_public_id}", Utils::getClientDisplayName($model))->toHtml() : ''; }, - ! $this->hideClient + ! $this->hideClient, ], [ 'transaction_reference', function ($model) { return $model->transaction_reference ? $model->transaction_reference : ''.trans('texts.manual_entry').''; - } + }, ], [ 'method', function ($model) { - return ($model->payment_type && !$model->last4) ? $model->payment_type : ($model->account_gateway_id ? $model->gateway_name : ''); - } + return ($model->payment_type && ! $model->last4) ? $model->payment_type : ($model->account_gateway_id ? $model->gateway_name : ''); + }, ], [ 'source', @@ -61,6 +63,7 @@ class PaymentDatatable extends EntityDatatable if ($model->payment_type_id != PAYMENT_TYPE_ACH) { if ($model->last4) { $expiration = Utils::fromSqlDate($model->expiration, false)->format('m/y'); + return '' . htmlentities($card_type) . '  •••' . $model->last4 . ' ' . $expiration; } elseif ($model->email) { return $model->email; @@ -74,19 +77,19 @@ class PaymentDatatable extends EntityDatatable $bankName = $bankData->name; } } - if (!empty($bankName)) { + if (! empty($bankName)) { return $bankName.'  •••' . $model->last4; } elseif ($model->last4) { return '' . htmlentities($card_type) . '  •••' . $model->last4; } } - } + }, ], [ 'amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); - } + }, ], [ 'payment_date', @@ -96,18 +99,17 @@ class PaymentDatatable extends EntityDatatable } else { return link_to("payments/{$model->public_id}/edit", Utils::dateToString($model->payment_date))->toHtml(); } - } + }, ], [ 'status', function ($model) { return self::getStatusLabel($model); - } - ] + }, + ], ]; } - public function actions() { return [ @@ -118,22 +120,23 @@ class PaymentDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_PAYMENT, $model->user_id]); - } + }, ], [ trans('texts.refund_payment'), function ($model) { $max_refund = number_format($model->amount - $model->refunded, 2); $formatted = Utils::formatMoney($max_refund, $model->currency_id, $model->country_id); - $symbol = Utils::getFromCache($model->currency_id ? $model->currency_id : 1, 'currencies')->symbol ; + $symbol = Utils::getFromCache($model->currency_id ? $model->currency_id : 1, 'currencies')->symbol; + return "javascript:showRefundModal({$model->public_id}, '{$max_refund}', '{$formatted}', '{$symbol}')"; }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_PAYMENT, $model->user_id]) && $model->payment_status_id >= PAYMENT_STATUS_COMPLETED && $model->refunded < $model->amount; - } - ] + }, + ], ]; } diff --git a/app/Ninja/Datatables/ProductDatatable.php b/app/Ninja/Datatables/ProductDatatable.php index 023cba05716b..467efedbc347 100644 --- a/app/Ninja/Datatables/ProductDatatable.php +++ b/app/Ninja/Datatables/ProductDatatable.php @@ -1,9 +1,11 @@ -public_id.'/edit', $model->product_key)->toHtml(); - } + }, ], [ 'notes', function ($model) { return nl2br(Str::limit($model->notes, 100)); - } + }, ], [ 'cost', function ($model) { return Utils::formatMoney($model->cost); - } + }, ], [ 'tax_rate', function ($model) { return $model->tax_rate ? ($model->tax_name . ' ' . $model->tax_rate . '%') : ''; }, - Auth::user()->account->invoice_item_taxes - ] + Auth::user()->account->invoice_item_taxes, + ], ]; } @@ -48,8 +50,8 @@ class ProductDatatable extends EntityDatatable uctrans('texts.edit_product'), function ($model) { return URL::to("products/{$model->public_id}/edit"); - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Datatables/ProjectDatatable.php b/app/Ninja/Datatables/ProjectDatatable.php index 2e1a93ffd578..2235481ad83e 100644 --- a/app/Ninja/Datatables/ProjectDatatable.php +++ b/app/Ninja/Datatables/ProjectDatatable.php @@ -1,8 +1,10 @@ -public_id}/edit", $model->project)->toHtml(); - } + }, ], [ 'client_name', function ($model) { if ($model->client_public_id) { - if (!Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { return Utils::getClientDisplayName($model); } @@ -34,8 +36,8 @@ class ProjectDatatable extends EntityDatatable } else { return ''; } - } - ] + }, + ], ]; } @@ -45,11 +47,11 @@ class ProjectDatatable extends EntityDatatable [ trans('texts.edit_project'), function ($model) { - return URL::to("projects/{$model->public_id}/edit") ; + return URL::to("projects/{$model->public_id}/edit"); }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_PROJECT, $model->user_id]); - } + }, ], ]; } diff --git a/app/Ninja/Datatables/RecurringInvoiceDatatable.php b/app/Ninja/Datatables/RecurringInvoiceDatatable.php index 454e129ecf7e..3f0f159dfb81 100644 --- a/app/Ninja/Datatables/RecurringInvoiceDatatable.php +++ b/app/Ninja/Datatables/RecurringInvoiceDatatable.php @@ -1,8 +1,10 @@ -frequency); $frequency = preg_replace('/\s/', '_', $frequency); + return link_to("invoices/{$model->public_id}", trans('texts.freq_'.$frequency))->toHtml(); - } + }, ], [ 'client_name', function ($model) { return link_to("clients/{$model->client_public_id}", Utils::getClientDisplayName($model))->toHtml(); }, - ! $this->hideClient + ! $this->hideClient, ], [ 'start_date', function ($model) { return Utils::fromSqlDate($model->start_date); - } + }, ], [ 'last_sent', function ($model) { return Utils::fromSqlDate($model->last_sent_date); - } + }, ], [ 'end_date', function ($model) { return Utils::fromSqlDate($model->end_date); - } + }, ], [ 'amount', function ($model) { return Utils::formatMoney($model->amount, $model->currency_id, $model->country_id); - } - ] + }, + ], ]; } @@ -63,16 +66,16 @@ class RecurringInvoiceDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->user_id]); - } + }, ], [ - trans("texts.clone_invoice"), + trans('texts.clone_invoice'), function ($model) { return URL::to("invoices/{$model->public_id}/clone"); }, function ($model) { return Auth::user()->can('create', ENTITY_INVOICE); - } + }, ], ]; diff --git a/app/Ninja/Datatables/TaskDatatable.php b/app/Ninja/Datatables/TaskDatatable.php index 43f890b51fbb..5f7ea1d8ee89 100644 --- a/app/Ninja/Datatables/TaskDatatable.php +++ b/app/Ninja/Datatables/TaskDatatable.php @@ -1,9 +1,11 @@ -can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_CLIENT, $model->client_user_id])) { return Utils::getClientDisplayName($model); } return $model->client_public_id ? link_to("clients/{$model->client_public_id}", Utils::getClientDisplayName($model))->toHtml() : ''; }, - ! $this->hideClient + ! $this->hideClient, ], [ 'project', function ($model) { - if (!Auth::user()->can('editByOwner', [ENTITY_PROJECT, $model->project_user_id])) { + if (! Auth::user()->can('editByOwner', [ENTITY_PROJECT, $model->project_user_id])) { return $model->project; } return $model->project_public_id ? link_to("projects/{$model->project_public_id}/edit", $model->project)->toHtml() : ''; - } + }, ], [ 'date', function ($model) { - if (!Auth::user()->can('viewByOwner', [ENTITY_EXPENSE, $model->user_id])) { + if (! Auth::user()->can('viewByOwner', [ENTITY_EXPENSE, $model->user_id])) { return Task::calcStartTime($model); } + return link_to("tasks/{$model->public_id}/edit", Task::calcStartTime($model))->toHtml(); - } + }, ], [ 'duration', function ($model) { return Utils::formatTime(Task::calcDuration($model)); - } + }, ], [ 'description', function ($model) { return $model->description; - } + }, ], [ 'status', function ($model) { return self::getStatusLabel($model); - } - ] + }, + ], ]; } @@ -73,8 +76,8 @@ class TaskDatatable extends EntityDatatable return URL::to('tasks/'.$model->public_id.'/edit'); }, function ($model) { - return (!$model->deleted_at || $model->deleted_at == '0000-00-00') && Auth::user()->can('editByOwner', [ENTITY_TASK, $model->user_id]); - } + return (! $model->deleted_at || $model->deleted_at == '0000-00-00') && Auth::user()->can('editByOwner', [ENTITY_TASK, $model->user_id]); + }, ], [ trans('texts.view_invoice'), @@ -83,7 +86,7 @@ class TaskDatatable extends EntityDatatable }, function ($model) { return $model->invoice_number && Auth::user()->can('editByOwner', [ENTITY_INVOICE, $model->invoice_user_id]); - } + }, ], [ trans('texts.stop_task'), @@ -92,7 +95,7 @@ class TaskDatatable extends EntityDatatable }, function ($model) { return $model->is_running && Auth::user()->can('editByOwner', [ENTITY_TASK, $model->user_id]); - } + }, ], [ trans('texts.invoice_task'), @@ -100,9 +103,9 @@ class TaskDatatable extends EntityDatatable return "javascript:submitForm_task('invoice', {$model->public_id})"; }, function ($model) { - return ! $model->invoice_number && (!$model->deleted_at || $model->deleted_at == '0000-00-00') && Auth::user()->can('create', ENTITY_INVOICE); - } - ] + return ! $model->invoice_number && (! $model->deleted_at || $model->deleted_at == '0000-00-00') && Auth::user()->can('create', ENTITY_INVOICE); + }, + ], ]; } diff --git a/app/Ninja/Datatables/TaxRateDatatable.php b/app/Ninja/Datatables/TaxRateDatatable.php index 87f7d986ef4a..fb20386e2e71 100644 --- a/app/Ninja/Datatables/TaxRateDatatable.php +++ b/app/Ninja/Datatables/TaxRateDatatable.php @@ -1,4 +1,6 @@ -public_id}/edit", $model->name)->toHtml(); - } + }, ], [ 'rate', function ($model) { return $model->rate . '%'; - } + }, ], [ 'type', function ($model) { return $model->is_inclusive ? trans('texts.inclusive') : trans('texts.exclusive'); - } - ] + }, + ], ]; } @@ -37,8 +39,8 @@ class TaxRateDatatable extends EntityDatatable uctrans('texts.edit_tax_rate'), function ($model) { return URL::to("tax_rates/{$model->public_id}/edit"); - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Datatables/TokenDatatable.php b/app/Ninja/Datatables/TokenDatatable.php index 13513deb15af..31596bf0c31a 100644 --- a/app/Ninja/Datatables/TokenDatatable.php +++ b/app/Ninja/Datatables/TokenDatatable.php @@ -1,4 +1,6 @@ -public_id}/edit", $model->name)->toHtml(); - } + }, ], [ 'token', function ($model) { return $model->token; - } - ] + }, + ], ]; } @@ -31,8 +33,8 @@ class TokenDatatable extends EntityDatatable uctrans('texts.edit_token'), function ($model) { return URL::to("tokens/{$model->public_id}/edit"); - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Datatables/UserDatatable.php b/app/Ninja/Datatables/UserDatatable.php index 5523021b6d59..ecc47039b9a1 100644 --- a/app/Ninja/Datatables/UserDatatable.php +++ b/app/Ninja/Datatables/UserDatatable.php @@ -1,4 +1,6 @@ -public_id ? link_to('users/'.$model->public_id.'/edit', $model->first_name.' '.$model->last_name)->toHtml() : ($model->first_name.' '.$model->last_name); - } + }, ], [ 'email', function ($model) { return $model->email; - } + }, ], [ 'confirmed', function ($model) { - if (!$model->public_id) { + if (! $model->public_id) { return self::getStatusLabel(USER_STATE_OWNER); } elseif ($model->deleted_at) { return self::getStatusLabel(USER_STATE_DISABLED); @@ -37,7 +39,7 @@ class UserDatatable extends EntityDatatable } else { return self::getStatusLabel(USER_STATE_PENDING); } - } + }, ], ]; } @@ -52,7 +54,7 @@ class UserDatatable extends EntityDatatable }, function ($model) { return $model->public_id; - } + }, ], [ uctrans('texts.send_invite'), @@ -61,8 +63,8 @@ class UserDatatable extends EntityDatatable }, function ($model) { return $model->public_id && ! $model->confirmed; - } - ] + }, + ], ]; } @@ -87,6 +89,7 @@ class UserDatatable extends EntityDatatable $class = 'primary'; break; } + return "

$label

"; } } diff --git a/app/Ninja/Datatables/VendorDatatable.php b/app/Ninja/Datatables/VendorDatatable.php index 6e0e063b3da3..98ba3c66febd 100644 --- a/app/Ninja/Datatables/VendorDatatable.php +++ b/app/Ninja/Datatables/VendorDatatable.php @@ -1,8 +1,10 @@ -public_id}", $model->name ?: '')->toHtml(); - } + }, ], [ 'city', function ($model) { return $model->city; - } + }, ], [ 'work_phone', function ($model) { return $model->work_phone; - } + }, ], [ 'email', function ($model) { return link_to("vendors/{$model->public_id}", $model->email ?: '')->toHtml(); - } + }, ], [ 'date', function ($model) { return Utils::timestampToDateString(strtotime($model->created_at)); - } + }, ], ]; } @@ -55,7 +57,7 @@ class VendorDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_VENDOR, $model->user_id]); - } + }, ], [ '--divider--', function () { @@ -63,7 +65,7 @@ class VendorDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('editByOwner', [ENTITY_VENDOR, $model->user_id]) && Auth::user()->can('create', ENTITY_EXPENSE); - } + }, ], [ @@ -73,8 +75,8 @@ class VendorDatatable extends EntityDatatable }, function ($model) { return Auth::user()->can('create', ENTITY_EXPENSE); - } - ] + }, + ], ]; } } diff --git a/app/Ninja/Import/BaseTransformer.php b/app/Ninja/Import/BaseTransformer.php index 579e2d62571f..3d47bde154fd 100644 --- a/app/Ninja/Import/BaseTransformer.php +++ b/app/Ninja/Import/BaseTransformer.php @@ -1,11 +1,13 @@ -maps[ENTITY_CLIENT][$name]); } /** * @param $key + * * @return bool */ public function hasProduct($key) { $key = trim(strtolower($key)); + return isset($this->maps[ENTITY_PRODUCT][$key]); } /** * @param $data * @param $field + * * @return string */ public function getString($data, $field) @@ -56,6 +64,7 @@ class BaseTransformer extends TransformerAbstract /** * @param $data * @param $field + * * @return int */ public function getNumber($data, $field) @@ -66,6 +75,7 @@ class BaseTransformer extends TransformerAbstract /** * @param $data * @param $field + * * @return float */ public function getFloat($data, $field) @@ -75,57 +85,68 @@ class BaseTransformer extends TransformerAbstract /** * @param $name + * * @return null */ public function getClientId($name) { $name = strtolower(trim($name)); + return isset($this->maps[ENTITY_CLIENT][$name]) ? $this->maps[ENTITY_CLIENT][$name] : null; } /** * @param $name + * * @return null */ public function getProductId($name) { $name = strtolower(trim($name)); + return isset($this->maps[ENTITY_PRODUCT][$name]) ? $this->maps[ENTITY_PRODUCT][$name] : null; } /** * @param $name + * * @return null */ public function getCountryId($name) { $name = strtolower(trim($name)); + return isset($this->maps['countries'][$name]) ? $this->maps['countries'][$name] : null; } /** * @param $name + * * @return null */ public function getCountryIdBy2($name) { $name = strtolower(trim($name)); + return isset($this->maps['countries2'][$name]) ? $this->maps['countries2'][$name] : null; } /** * @param $name + * * @return mixed */ public function getFirstName($name) { $name = Utils::splitName($name); + return $name[0]; } /** * @param $date * @param string $format + * * @return null */ public function getDate($data, $field) @@ -143,16 +164,19 @@ class BaseTransformer extends TransformerAbstract /** * @param $name + * * @return mixed */ public function getLastName($name) { $name = Utils::splitName($name); + return $name[1]; } /** * @param $number + * * @return string */ public function getInvoiceNumber($number) @@ -162,56 +186,64 @@ class BaseTransformer extends TransformerAbstract /** * @param $invoiceNumber + * * @return null */ public function getInvoiceId($invoiceNumber) { $invoiceNumber = $this->getInvoiceNumber($invoiceNumber); $invoiceNumber = strtolower($invoiceNumber); + return isset($this->maps[ENTITY_INVOICE][$invoiceNumber]) ? $this->maps[ENTITY_INVOICE][$invoiceNumber] : null; } /** * @param $invoiceNumber + * * @return bool */ public function hasInvoice($invoiceNumber) { $invoiceNumber = $this->getInvoiceNumber($invoiceNumber); $invoiceNumber = strtolower($invoiceNumber); + return isset($this->maps[ENTITY_INVOICE][$invoiceNumber]); } /** * @param $invoiceNumber + * * @return null */ public function getInvoiceClientId($invoiceNumber) { $invoiceNumber = $this->getInvoiceNumber($invoiceNumber); $invoiceNumber = strtolower($invoiceNumber); - return isset($this->maps[ENTITY_INVOICE.'_'.ENTITY_CLIENT][$invoiceNumber])? $this->maps[ENTITY_INVOICE.'_'.ENTITY_CLIENT][$invoiceNumber] : null; - } + return isset($this->maps[ENTITY_INVOICE.'_'.ENTITY_CLIENT][$invoiceNumber]) ? $this->maps[ENTITY_INVOICE.'_'.ENTITY_CLIENT][$invoiceNumber] : null; + } /** * @param $name + * * @return null */ public function getVendorId($name) { $name = strtolower(trim($name)); + return isset($this->maps[ENTITY_VENDOR][$name]) ? $this->maps[ENTITY_VENDOR][$name] : null; } - /** * @param $name + * * @return null */ public function getExpenseCategoryId($name) { $name = strtolower(trim($name)); + return isset($this->maps[ENTITY_EXPENSE_CATEGORY][$name]) ? $this->maps[ENTITY_EXPENSE_CATEGORY][$name] : null; } } diff --git a/app/Ninja/Import/CSV/ClientTransformer.php b/app/Ninja/Import/CSV/ClientTransformer.php index b8d509ad74a9..acb2d2380143 100644 --- a/app/Ninja/Import/CSV/ClientTransformer.php +++ b/app/Ninja/Import/CSV/ClientTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'notes'), 'cost' => $this->getFloat($data, 'amount'), 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/CSV/PaymentTransformer.php b/app/Ninja/Import/CSV/PaymentTransformer.php index e06677fcb3ea..46247f8fd068 100644 --- a/app/Ninja/Import/CSV/PaymentTransformer.php +++ b/app/Ninja/Import/CSV/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'notes'), 'cost' => (float) $data->amount, 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/FreshBooks/PaymentTransformer.php b/app/Ninja/Import/FreshBooks/PaymentTransformer.php index 3cd829f1ea9c..06cc603d3b91 100644 --- a/app/Ninja/Import/FreshBooks/PaymentTransformer.php +++ b/app/Ninja/Import/FreshBooks/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'subject'), 'cost' => (float) $data->invoice_amount, 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/Harvest/PaymentTransformer.php b/app/Ninja/Import/Harvest/PaymentTransformer.php index 3391b9ace16e..e72758d0d941 100644 --- a/app/Ninja/Import/Harvest/PaymentTransformer.php +++ b/app/Ninja/Import/Harvest/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'summary'), 'cost' => (float) $data->billed_total, 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/Hiveage/PaymentTransformer.php b/app/Ninja/Import/Hiveage/PaymentTransformer.php index 2057c32a94fc..c73691d97faa 100644 --- a/app/Ninja/Import/Hiveage/PaymentTransformer.php +++ b/app/Ninja/Import/Hiveage/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'description'), 'cost' => (float) $data->total, 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/Invoiceable/PaymentTransformer.php b/app/Ninja/Import/Invoiceable/PaymentTransformer.php index 6ad823f0370f..d11fef9dfaf3 100644 --- a/app/Ninja/Import/Invoiceable/PaymentTransformer.php +++ b/app/Ninja/Import/Invoiceable/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'description'), 'cost' => (float) $data->total, 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/Nutcache/PaymentTransformer.php b/app/Ninja/Import/Nutcache/PaymentTransformer.php index cd7737d44073..23a53e4b021d 100644 --- a/app/Ninja/Import/Nutcache/PaymentTransformer.php +++ b/app/Ninja/Import/Nutcache/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'line_item'), 'cost' => (float) $data->total, 'qty' => 1, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/Ronin/PaymentTransformer.php b/app/Ninja/Import/Ronin/PaymentTransformer.php index b8f7cf0562fa..3c6f8c791c86 100644 --- a/app/Ninja/Import/Ronin/PaymentTransformer.php +++ b/app/Ninja/Import/Ronin/PaymentTransformer.php @@ -1,15 +1,18 @@ - $this->getString($data, 'description'), 'cost' => (float) $data->amount, 'qty' => (float) $data->quantity, - ] + ], ], ]; }); diff --git a/app/Ninja/Import/Wave/PaymentTransformer.php b/app/Ninja/Import/Wave/PaymentTransformer.php index 799f8abdfef8..95ece47c7c2c 100644 --- a/app/Ninja/Import/Wave/PaymentTransformer.php +++ b/app/Ninja/Import/Wave/PaymentTransformer.php @@ -1,15 +1,18 @@ - (float) $data->item_tax1, 'tax_name2' => (float) $data->item_tax2 ? trans('texts.tax') : '', 'tax_rate2' => (float) $data->item_tax2, - ] + ], ], ]; diff --git a/app/Ninja/Import/Zoho/PaymentTransformer.php b/app/Ninja/Import/Zoho/PaymentTransformer.php index c9684bebb455..8fb914b4afcf 100644 --- a/app/Ninja/Import/Zoho/PaymentTransformer.php +++ b/app/Ninja/Import/Zoho/PaymentTransformer.php @@ -1,15 +1,18 @@ -$reference = new stdClass; + $state->$reference = new stdClass(); $state->$reference->entityType = false; foreach ([ENTITY_INVOICE, ENTITY_CLIENT, ENTITY_INVOICE_ITEM] as $entityType) { $state->$reference->$entityType = []; @@ -60,10 +62,9 @@ class BaseIntent throw new Exception(trans('texts.intent_not_supported')); } - return (new $className($state, $data)); + return new $className($state, $data); } - public function process() { throw new Exception(trans('texts.intent_not_supported')); @@ -115,7 +116,6 @@ class BaseIntent return $this->state->current->entityType; } - public function getState() { return $this->state; diff --git a/app/Ninja/Intents/CreateInvoiceIntent.php b/app/Ninja/Intents/CreateInvoiceIntent.php index ea2647aadcab..915bfae0883e 100644 --- a/app/Ninja/Intents/CreateInvoiceIntent.php +++ b/app/Ninja/Intents/CreateInvoiceIntent.php @@ -1,7 +1,9 @@ -stateEntity(ENTITY_INVOICE)) { $card->addButton('imBack', trans('texts.add_to_invoice', ['invoice' => '']), trans('texts.add_product_to_invoice', ['product' => $item->product_key])); } + return $card; }); diff --git a/app/Ninja/Intents/ProductIntent.php b/app/Ninja/Intents/ProductIntent.php index 73d07e7c7b90..cc7a9ff316ed 100644 --- a/app/Ninja/Intents/ProductIntent.php +++ b/app/Ninja/Intents/ProductIntent.php @@ -1,4 +1,6 @@ -attachPDF() && !$pdfString) { + if ($account->attachPDF() && ! $pdfString) { $pdfString = $invoice->getPDFString(); } @@ -134,13 +138,15 @@ class ContactMailer extends Mailer /** * @param Invitation $invitation - * @param Invoice $invoice + * @param Invoice $invoice * @param $body * @param $subject * @param $pdfString * @param $documentStrings - * @return bool|string + * * @throws \Laracasts\Presenter\Exceptions\PresenterException + * + * @return bool|string */ private function sendInvitation( Invitation $invitation, @@ -163,11 +169,11 @@ class ContactMailer extends Mailer } } - if (!$user->email || !$user->registered) { + if (! $user->email || ! $user->registered) { return trans('texts.email_error_user_unregistered'); - } elseif (!$user->confirmed) { + } elseif (! $user->confirmed) { return trans('texts.email_error_user_unconfirmed'); - } elseif (!$invitation->contact->email) { + } elseif (! $invitation->contact->email) { return trans('texts.email_error_invalid_contact_email'); } elseif ($invitation->contact->trashed()) { return trans('texts.email_error_inactive_contact'); @@ -177,7 +183,7 @@ class ContactMailer extends Mailer 'account' => $account, 'client' => $client, 'invitation' => $invitation, - 'amount' => $invoice->getRequestedAmount() + 'amount' => $invoice->getRequestedAmount(), ]; // Let the client know they'll be billed later @@ -227,6 +233,7 @@ class ContactMailer extends Mailer /** * @param int $length + * * @return string */ protected function generatePassword($length = 9) @@ -335,7 +342,7 @@ class ContactMailer extends Mailer $data = [ 'client' => $name, 'amount' => Utils::formatMoney($amount, DEFAULT_CURRENCY, DEFAULT_COUNTRY), - 'license' => $license + 'license' => $license, ]; $this->sendTo($email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); diff --git a/app/Ninja/Mailers/Mailer.php b/app/Ninja/Mailers/Mailer.php index 7750baff5e4f..c8a29f30ab32 100644 --- a/app/Ninja/Mailers/Mailer.php +++ b/app/Ninja/Mailers/Mailer.php @@ -1,12 +1,14 @@ -subject($subject); // Optionally BCC the email - if (!empty($data['bccEmail'])) { + if (! empty($data['bccEmail'])) { $message->bcc($data['bccEmail']); } // Attach the PDF to the email - if (!empty($data['pdfString']) && !empty($data['pdfFileName'])) { + if (! empty($data['pdfString']) && ! empty($data['pdfFileName'])) { $message->attachData($data['pdfString'], $data['pdfFileName']); } // Attach documents to the email - if (!empty($data['documents'])) { + if (! empty($data['documents'])) { foreach ($data['documents'] as $document) { $message->attachData($document['data'], $document['name']); } @@ -79,6 +82,7 @@ class Mailer /** * @param $response * @param $data + * * @return bool */ private function handleSuccess($response, $data) @@ -94,7 +98,7 @@ class Mailer $messageId = $json->MessageID; } - $notes = isset($data['notes']) ? $data['notes']: false; + $notes = isset($data['notes']) ? $data['notes'] : false; $invoice->markInvitationSent($invitation, $messageId, true, $notes); } @@ -103,6 +107,7 @@ class Mailer /** * @param $exception + * * @return string */ private function handleFailure($exception) diff --git a/app/Ninja/Mailers/UserMailer.php b/app/Ninja/Mailers/UserMailer.php index c463cd7811ea..c509bd66afcb 100644 --- a/app/Ninja/Mailers/UserMailer.php +++ b/app/Ninja/Mailers/UserMailer.php @@ -1,4 +1,6 @@ -email) { + if (! $user->email) { return; } @@ -37,7 +39,7 @@ class UserMailer extends Mailer } /** - * @param User $user + * @param User $user * @param Invoice $invoice * @param $notificationType * @param Payment|null $payment @@ -81,7 +83,7 @@ class UserMailer extends Mailer $subject = trans("texts.notification_{$entityType}_{$notificationType}_subject", [ 'invoice' => $invoice->invoice_number, - 'client' => $client->getDisplayName() + 'client' => $client->getDisplayName(), ]); $this->sendTo($user->email, CONTACT_EMAIL, CONTACT_NAME, $subject, $view, $data); @@ -97,7 +99,7 @@ class UserMailer extends Mailer $invoice = $invitation->invoice; $entityType = $invoice->getEntityType(); - if (!$user->email) { + if (! $user->email) { return; } @@ -116,7 +118,7 @@ class UserMailer extends Mailer public function sendSecurityCode($user, $code) { - if (!$user->email) { + if (! $user->email) { return; } diff --git a/app/Ninja/Notifications/PushFactory.php b/app/Ninja/Notifications/PushFactory.php index eaaec846dd66..86c85548bc34 100644 --- a/app/Ninja/Notifications/PushFactory.php +++ b/app/Ninja/Notifications/PushFactory.php @@ -6,9 +6,8 @@ use Davibennun\LaravelPushNotification\Facades\PushNotification; use Illuminate\Support\Facades\Log; /** - * Class PushFactory + * Class PushFactory. */ - class PushFactory { /** @@ -19,11 +18,10 @@ class PushFactory } /** - * customMessage function + * customMessage function. * * Send a message with a nested custom payload to perform additional trickery within application * - * @access public * * @param $token * @param $message @@ -40,18 +38,16 @@ class PushFactory } /** - * message function + * message function. * * Send a plain text only message to a single device. * - * @access public * * @param $token - device token * @param $message - user specific message * * @return void */ - public function message($token, $message, $device) { try { @@ -64,20 +60,20 @@ class PushFactory } /** - * getFeedback function + * getFeedback function. * * Returns an array of expired/invalid tokens to be removed from iOS PUSH notifications. * * We need to run this once ~ 24hrs * - * @access public * - * @param string $token - A valid token (can be any valid token) + * @param string $token - A valid token (can be any valid token) * @param string $message - Nil value for message - * @param string $device - Type of device the message is being pushed to. + * @param string $device - Type of device the message is being pushed to. + * * @return array */ - public function getFeedback($token, $message = '', $device) + public function getFeedback($token, $message, $device) { $feedback = PushNotification::app($device) ->to($token) diff --git a/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php b/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php index 00ba9421ce03..9bec8c2426bb 100644 --- a/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/AuthorizeNetAIMPaymentDriver.php @@ -1,4 +1,6 @@ -meetsGatewayTypeLimits($this->gatewayType)) { // The customer must have hacked the URL Session::flash('error', trans('texts.limits_not_met')); + return redirect()->to('view/' . $this->invitation->invitation_key); } @@ -136,6 +139,7 @@ class BasePaymentDriver $this->completeOnsitePurchase(); if ($redirectUrl = session('redirect_url:' . $this->invitation->invitation_key)) { $separator = strpos($redirectUrl, '?') === false ? '?' : '&'; + return redirect()->to($redirectUrl . $separator . 'invoice_id=' . $this->invoice()->public_id); } else { Session::flash('message', trans('texts.applied_payment')); @@ -262,6 +266,7 @@ class BasePaymentDriver if (! $this->meetsGatewayTypeLimits($paymentMethod->payment_type->gateway_type_id)) { // The customer must have hacked the URL Session::flash('error', trans('texts.limits_not_met')); + return redirect()->to('view/' . $this->invitation->invitation_key); } } else { @@ -272,6 +277,7 @@ class BasePaymentDriver if (! $this->meetsGatewayTypeLimits($this->gatewayType)) { // The customer must have hacked the URL Session::flash('error', trans('texts.limits_not_met')); + return redirect()->to('view/' . $this->invitation->invitation_key); } } @@ -364,7 +370,7 @@ class BasePaymentDriver 'description' => trans('texts.' . $invoice->getEntityType()) . " {$invoice->invoice_number}", 'transactionId' => $invoice->invoice_number, 'transactionType' => 'Purchase', - 'ip' => Request::ip() + 'ip' => Request::ip(), ]; if ($paymentMethod) { @@ -417,7 +423,7 @@ class BasePaymentDriver 'shippingCity' => $input['city'], 'shippingState' => $input['state'], 'shippingPostcode' => $input['postal_code'], - 'shippingCountry' => $country->iso_3166_2 + 'shippingCountry' => $country->iso_3166_2, ]); } @@ -644,7 +650,7 @@ class BasePaymentDriver } } - if (!empty($plan)) { + if (! empty($plan)) { $account = Account::with('users')->find($invoice->client->public_id); $company = $account->company; @@ -865,7 +871,7 @@ class BasePaymentDriver $gatewayTypeAlias = GatewayType::getAliasFromId($gatewayTypeId); if ($gatewayTypeId == GATEWAY_TYPE_CUSTOM) { - $url = "javascript:showCustomModal();"; + $url = 'javascript:showCustomModal();'; $label = e($this->accountGateway->getConfigField('name')); } else { $url = $this->paymentUrl($gatewayTypeAlias); @@ -884,7 +890,7 @@ class BasePaymentDriver protected function meetsGatewayTypeLimits($gatewayTypeId) { - if (!$gatewayTypeId) { + if (! $gatewayTypeId) { return true; } @@ -898,7 +904,7 @@ class BasePaymentDriver return false; } - if ($accountGatewaySettings->max_limit !== null && $invoice->balance > $accountGatewaySettings->max_limit) { + if ($accountGatewaySettings->max_limit !== null && $invoice->balance > $accountGatewaySettings->max_limit) { return false; } } @@ -941,7 +947,7 @@ class BasePaymentDriver 'laser' => PAYMENT_TYPE_LASER, 'maestro' => PAYMENT_TYPE_MAESTRO, 'solo' => PAYMENT_TYPE_SOLO, - 'switch' => PAYMENT_TYPE_SWITCH + 'switch' => PAYMENT_TYPE_SWITCH, ]; $cardName = strtolower(str_replace([' ', '-', '_'], '', $cardName)); @@ -951,7 +957,7 @@ class BasePaymentDriver $cardName = $matches[1]; } - if (!empty($cardTypes[$cardName])) { + if (! empty($cardTypes[$cardName])) { return $cardTypes[$cardName]; } else { return PAYMENT_TYPE_CREDIT_CARD_OTHER; diff --git a/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php b/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php index 1b0a2397d9a7..47c3213a1116 100644 --- a/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/BitPayPaymentDriver.php @@ -1,11 +1,13 @@ -send() ->getData(); - return ($customer instanceof Customer); + return $customer instanceof Customer; } protected function paymentDetails($paymentMethod = false) @@ -121,7 +123,7 @@ class BraintreePaymentDriver extends BasePaymentDriver 'company' => $this->client()->name, 'email' => $this->contact()->email, 'phone' => $this->contact()->phone, - 'website' => $this->client()->website + 'website' => $this->client()->website, ]; } @@ -157,7 +159,7 @@ class BraintreePaymentDriver extends BasePaymentDriver parent::removePaymentMethod($paymentMethod); $response = $this->gateway()->deletePaymentMethod([ - 'token' => $paymentMethod->source_reference + 'token' => $paymentMethod->source_reference, ])->send(); if ($response->isSuccessful()) { diff --git a/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php b/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php index 1d8ee7a21d05..47eed79ab921 100644 --- a/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/CheckoutComPaymentDriver.php @@ -1,4 +1,6 @@ -gateway()->purchase([ 'amount' => $this->invoice()->getRequestedAmount(), - 'currency' => $this->client()->getCurrencyCode() + 'currency' => $this->client()->getCurrencyCode(), ])->send(); if ($response->isRedirect()) { diff --git a/app/Ninja/PaymentDrivers/CustomPaymentDriver.php b/app/Ninja/PaymentDrivers/CustomPaymentDriver.php index dbe8e6a9ce0a..a09d7e129f33 100644 --- a/app/Ninja/PaymentDrivers/CustomPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/CustomPaymentDriver.php @@ -1,11 +1,13 @@ - Request::query('pt') + 'token' => Request::query('pt'), ]); } } diff --git a/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php b/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php index 8143ad9bf331..ac3d0c847b24 100644 --- a/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/PayPalExpressPaymentDriver.php @@ -1,11 +1,13 @@ -accountGateway && $this->accountGateway->getAchEnabled()) { @@ -153,14 +155,14 @@ class StripePaymentDriver extends BasePaymentDriver $data = $this->tokenResponse; $source = false; - if (!empty($data['object']) && ($data['object'] == 'card' || $data['object'] == 'bank_account')) { + if (! empty($data['object']) && ($data['object'] == 'card' || $data['object'] == 'bank_account')) { $source = $data; - } elseif (!empty($data['object']) && $data['object'] == 'customer') { - $sources = !empty($data['sources']) ? $data['sources'] : $data['cards']; + } elseif (! empty($data['object']) && $data['object'] == 'customer') { + $sources = ! empty($data['sources']) ? $data['sources'] : $data['cards']; $source = reset($sources['data']); - } elseif (!empty($data['source'])) { + } elseif (! empty($data['source'])) { $source = $data['source']; - } elseif (!empty($data['card'])) { + } elseif (! empty($data['card'])) { $source = $data['card']; } @@ -210,7 +212,7 @@ class StripePaymentDriver extends BasePaymentDriver $response = $this->gateway()->deleteCard([ 'customerReference' => $paymentMethod->account_gateway_token->token, - 'cardReference' => $paymentMethod->source_reference + 'cardReference' => $paymentMethod->source_reference, ])->send(); if ($response->isSuccessful()) { @@ -225,36 +227,37 @@ class StripePaymentDriver extends BasePaymentDriver $clientId = $this->accountGateway->getPlaidClientId(); $secret = $this->accountGateway->getPlaidSecret(); - if (!$clientId) { + if (! $clientId) { throw new Exception('plaid client id not set'); // TODO use text strings } - if (!$secret) { + if (! $secret) { throw new Exception('plaid secret not set'); } try { $subdomain = $this->accountGateway->getPlaidEnvironment() == 'production' ? 'api' : 'tartan'; - $response = (new \GuzzleHttp\Client(['base_uri'=>"https://{$subdomain}.plaid.com"]))->request( + $response = (new \GuzzleHttp\Client(['base_uri' => "https://{$subdomain}.plaid.com"]))->request( 'POST', 'exchange_token', [ 'allow_redirects' => false, - 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], + 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], 'body' => http_build_query([ 'client_id' => $clientId, 'secret' => $secret, 'public_token' => $publicToken, 'account_id' => $accountId, - ]) + ]), ] ); + return json_decode($response->getBody(), true); } catch (\GuzzleHttp\Exception\BadResponseException $e) { $response = $e->getResponse(); $body = json_decode($response->getBody(), true); - if ($body && !empty($body['message'])) { + if ($body && ! empty($body['message'])) { throw new Exception($body['message']); } else { throw new Exception($e->getMessage()); @@ -296,13 +299,13 @@ class StripePaymentDriver extends BasePaymentDriver { $apiKey = $this->accountGateway->getConfig()->apiKey; - if (!$apiKey) { + if (! $apiKey) { return 'No API key set'; } try { $options = [ - 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], + 'headers' => ['content-type' => 'application/x-www-form-urlencoded'], 'auth' => [$apiKey, ''], ]; @@ -310,11 +313,12 @@ class StripePaymentDriver extends BasePaymentDriver $options['body'] = $body; } - $response = (new \GuzzleHttp\Client(['base_uri'=>'https://api.stripe.com/v1/']))->request( + $response = (new \GuzzleHttp\Client(['base_uri' => 'https://api.stripe.com/v1/']))->request( $method, $url, $options ); + return json_decode($response->getBody(), true); } catch (\GuzzleHttp\Exception\BadResponseException $e) { $response = $e->getResponse(); @@ -331,16 +335,16 @@ class StripePaymentDriver extends BasePaymentDriver public function handleWebHook($input) { $eventId = array_get($input, 'id'); - $eventType= array_get($input, 'type'); + $eventType = array_get($input, 'type'); $accountGateway = $this->accountGateway; $accountId = $accountGateway->account_id; - if (!$eventId) { + if (! $eventId) { throw new Exception('Missing event id'); } - if (!$eventType) { + if (! $eventType) { throw new Exception('Missing event type'); } @@ -353,14 +357,14 @@ class StripePaymentDriver extends BasePaymentDriver 'customer.bank_account.deleted', ]; - if (!in_array($eventType, $supportedEvents)) { + if (! in_array($eventType, $supportedEvents)) { return ['message' => 'Ignoring event']; } // Fetch the event directly from Stripe for security $eventDetails = $this->makeStripeCall('GET', 'events/'.$eventId); - if (is_string($eventDetails) || !$eventDetails) { + if (is_string($eventDetails) || ! $eventDetails) { return false; } @@ -368,7 +372,7 @@ class StripePaymentDriver extends BasePaymentDriver return false; } - if (!$eventDetails['pending_webhooks']) { + if (! $eventDetails['pending_webhooks']) { return false; } @@ -378,12 +382,12 @@ class StripePaymentDriver extends BasePaymentDriver $payment = Payment::scope(false, $accountId)->where('transaction_reference', '=', $transactionRef)->first(); - if (!$payment) { + if (! $payment) { return false; } if ($eventType == 'charge.failed') { - if (!$payment->isFailed()) { + if (! $payment->isFailed()) { $payment->markFailed($charge['failure_message']); $userMailer = app('App\Ninja\Mailers\UserMailer'); @@ -400,7 +404,7 @@ class StripePaymentDriver extends BasePaymentDriver $paymentMethod = PaymentMethod::scope(false, $accountId)->where('source_reference', '=', $sourceRef)->first(); - if (!$paymentMethod) { + if (! $paymentMethod) { return false; } diff --git a/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php b/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php index cbbf062bbf95..fca754ac79a8 100644 --- a/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php +++ b/app/Ninja/PaymentDrivers/TwoCheckoutPaymentDriver.php @@ -1,4 +1,6 @@ -accountGateway && $this->accountGateway->getAchEnabled()) { @@ -207,14 +209,14 @@ class WePayPaymentDriver extends BasePaymentDriver } } - if (!isset($objectType)) { + if (! isset($objectType)) { throw new Exception('Could not find object id parameter'); } if ($objectType == 'credit_card') { $paymentMethod = PaymentMethod::scope(false, $accountId)->where('source_reference', '=', $objectId)->first(); - if (!$paymentMethod) { + if (! $paymentMethod) { throw new Exception('Unknown payment method'); } @@ -255,7 +257,7 @@ class WePayPaymentDriver extends BasePaymentDriver } elseif ($objectType == 'checkout') { $payment = Payment::scope(false, $accountId)->where('transaction_reference', '=', $objectId)->first(); - if (!$payment) { + if (! $payment) { throw new Exception('Unknown payment'); } @@ -266,7 +268,7 @@ class WePayPaymentDriver extends BasePaymentDriver if ($checkout->state == 'refunded') { $payment->recordRefund(); - } elseif (!empty($checkout->refund) && !empty($checkout->refund->amount_refunded) && ($checkout->refund->amount_refunded - $payment->refunded) > 0) { + } elseif (! empty($checkout->refund) && ! empty($checkout->refund->amount_refunded) && ($checkout->refund->amount_refunded - $payment->refunded) > 0) { $payment->recordRefund($checkout->refund->amount_refunded - $payment->refunded); } diff --git a/app/Ninja/Presenters/AccountPresenter.php b/app/Ninja/Presenters/AccountPresenter.php index 7c6c0d0fb32b..9560e844d7fc 100644 --- a/app/Ninja/Presenters/AccountPresenter.php +++ b/app/Ninja/Presenters/AccountPresenter.php @@ -1,16 +1,17 @@ -entity->getCurrencyId(); $currency = Utils::getFromCache($currencyId, 'currencies'); + return $currency->code; } diff --git a/app/Ninja/Presenters/ClientPresenter.php b/app/Ninja/Presenters/ClientPresenter.php index 06c12fa54de6..4d87bf32616b 100644 --- a/app/Ninja/Presenters/ClientPresenter.php +++ b/app/Ninja/Presenters/ClientPresenter.php @@ -1,4 +1,6 @@ - $this->entity->promo_expires->format('M dS, Y'), - 'amount' => (int)($this->discount * 100) . '%' + 'amount' => (int) ($this->discount * 100) . '%', ]); } @@ -22,7 +24,7 @@ class CompanyPresenter extends EntityPresenter return trans('texts.discount_message', [ 'expires' => $this->entity->discount_expires->format('M dS, Y'), - 'amount' => (int)($this->discount * 100) . '%' + 'amount' => (int) ($this->discount * 100) . '%', ]); } } diff --git a/app/Ninja/Presenters/CreditPresenter.php b/app/Ninja/Presenters/CreditPresenter.php index 8bcafe58d74c..2a2ee78f270c 100644 --- a/app/Ninja/Presenters/CreditPresenter.php +++ b/app/Ninja/Presenters/CreditPresenter.php @@ -1,9 +1,11 @@ -entity->invoice_status ? $this->entity->invoice_status->name : 'draft'; $status = strtolower($status); + return trans("texts.status_{$status}"); } } @@ -138,12 +141,14 @@ class InvoicePresenter extends EntityPresenter { $frequency = $this->entity->frequency ? $this->entity->frequency->name : ''; $frequency = strtolower($frequency); + return trans('texts.freq_'.$frequency); } public function email() { $client = $this->entity->client; + return count($client->contacts) ? $client->contacts[0]->email : ''; } @@ -205,7 +210,7 @@ class InvoicePresenter extends EntityPresenter $actions = [ ['url' => 'javascript:onCloneClick()', 'label' => trans("texts.clone_{$entityType}")], ['url' => url("{$entityType}s/{$entityType}_history/{$invoice->public_id}"), 'label' => trans('texts.view_history')], - DropdownButton::DIVIDER + DropdownButton::DIVIDER, ]; if ($entityType == ENTITY_QUOTE) { @@ -219,7 +224,7 @@ class InvoicePresenter extends EntityPresenter $actions[] = ['url' => url("quotes/{$invoice->quote_id}/edit"), 'label' => trans('texts.view_quote')]; } - if (!$invoice->is_recurring && $invoice->balance > 0) { + if (! $invoice->is_recurring && $invoice->balance > 0) { $actions[] = ['url' => 'javascript:submitBulkAction("markPaid")', 'label' => trans('texts.mark_paid')]; $actions[] = ['url' => 'javascript:onPaymentClick()', 'label' => trans('texts.enter_payment')]; } diff --git a/app/Ninja/Presenters/PaymentPresenter.php b/app/Ninja/Presenters/PaymentPresenter.php index 617358ba6616..b7d6ba8f3fe2 100644 --- a/app/Ninja/Presenters/PaymentPresenter.php +++ b/app/Ninja/Presenters/PaymentPresenter.php @@ -1,4 +1,6 @@ -isExport ? $client->getDisplayName() : $client->present()->link, $account->formatMoney($amount, $client), $account->formatMoney($paid, $client), - $account->formatMoney($amount - $paid, $client) + $account->formatMoney($amount - $paid, $client), ]; $this->addToTotals($client->currency_id, 'amount', $amount); diff --git a/app/Ninja/Reports/ExpenseReport.php b/app/Ninja/Reports/ExpenseReport.php index 80e1dbf68d1f..dc0684bd04b9 100644 --- a/app/Ninja/Reports/ExpenseReport.php +++ b/app/Ninja/Reports/ExpenseReport.php @@ -2,9 +2,9 @@ namespace App\Ninja\Reports; +use App\Models\Expense; use Auth; use Utils; -use App\Models\Expense; class ExpenseReport extends AbstractReport { diff --git a/app/Ninja/Reports/InvoiceDetailsReport.php b/app/Ninja/Reports/InvoiceDetailsReport.php index a279145b85d7..a8b8f1a2bcaa 100644 --- a/app/Ninja/Reports/InvoiceDetailsReport.php +++ b/app/Ninja/Reports/InvoiceDetailsReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class InvoiceDetailsReport extends AbstractReport { diff --git a/app/Ninja/Reports/InvoiceReport.php b/app/Ninja/Reports/InvoiceReport.php index 140db87ee460..908e01e96a55 100644 --- a/app/Ninja/Reports/InvoiceReport.php +++ b/app/Ninja/Reports/InvoiceReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class InvoiceReport extends AbstractReport { @@ -14,7 +14,7 @@ class InvoiceReport extends AbstractReport 'amount', 'payment_date', 'paid', - 'method' + 'method', ]; public function run() diff --git a/app/Ninja/Reports/PaymentReport.php b/app/Ninja/Reports/PaymentReport.php index 4f40e4265edf..5df24a1d1659 100644 --- a/app/Ninja/Reports/PaymentReport.php +++ b/app/Ninja/Reports/PaymentReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Payment; +use Auth; class PaymentReport extends AbstractReport { diff --git a/app/Ninja/Reports/ProductReport.php b/app/Ninja/Reports/ProductReport.php index 48fc62033c35..e28ae074dfcf 100644 --- a/app/Ninja/Reports/ProductReport.php +++ b/app/Ninja/Reports/ProductReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class ProductReport extends AbstractReport { diff --git a/app/Ninja/Reports/ProfitAndLossReport.php b/app/Ninja/Reports/ProfitAndLossReport.php index d1108bf90a51..ec76a482eb55 100644 --- a/app/Ninja/Reports/ProfitAndLossReport.php +++ b/app/Ninja/Reports/ProfitAndLossReport.php @@ -2,9 +2,9 @@ namespace App\Ninja\Reports; -use Auth; -use App\Models\Payment; use App\Models\Expense; +use App\Models\Payment; +use Auth; class ProfitAndLossReport extends AbstractReport { @@ -40,7 +40,6 @@ class ProfitAndLossReport extends AbstractReport $this->addToTotals($client->currency_id, 'profit', $payment->getCompletedAmount(), $payment->present()->month); } - $expenses = Expense::scope() ->with('client.contacts') ->withArchived(); @@ -60,7 +59,6 @@ class ProfitAndLossReport extends AbstractReport $this->addToTotals($client->currency_id, 'profit', $expense->amount * -1, $expense->present()->month); } - //$this->addToTotals($client->currency_id, 'paid', $payment ? $payment->getCompletedAmount() : 0); //$this->addToTotals($client->currency_id, 'amount', $invoice->amount); //$this->addToTotals($client->currency_id, 'balance', $invoice->balance); diff --git a/app/Ninja/Reports/TaskReport.php b/app/Ninja/Reports/TaskReport.php index f4e9e37f7cca..803f799a2a6f 100644 --- a/app/Ninja/Reports/TaskReport.php +++ b/app/Ninja/Reports/TaskReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Utils; use App\Models\Task; +use Utils; class TaskReport extends AbstractReport { diff --git a/app/Ninja/Reports/TaxRateReport.php b/app/Ninja/Reports/TaxRateReport.php index 787c37f46596..c4156f8d6216 100644 --- a/app/Ninja/Reports/TaxRateReport.php +++ b/app/Ninja/Reports/TaxRateReport.php @@ -2,8 +2,8 @@ namespace App\Ninja\Reports; -use Auth; use App\Models\Client; +use Auth; class TaxRateReport extends AbstractReport { @@ -70,7 +70,7 @@ class TaxRateReport extends AbstractReport $tax['name'], $tax['rate'] . '%', $account->formatMoney($tax['amount'], $client), - $account->formatMoney($tax['paid'], $client) + $account->formatMoney($tax['paid'], $client), ]; } diff --git a/app/Ninja/Repositories/AccountGatewayRepository.php b/app/Ninja/Repositories/AccountGatewayRepository.php index 03b41be7e92c..f338ccb316cf 100644 --- a/app/Ninja/Repositories/AccountGatewayRepository.php +++ b/app/Ninja/Repositories/AccountGatewayRepository.php @@ -1,4 +1,6 @@ -save(); $user = new User(); - if (!$firstName && !$lastName && !$email && !$password) { + if (! $firstName && ! $lastName && ! $email && ! $password) { $user->password = str_random(RANDOM_KEY_LENGTH); $user->username = str_random(RANDOM_KEY_LENGTH); } else { $user->first_name = $firstName; $user->last_name = $lastName; $user->email = $user->username = $email; - if (!$password) { + if (! $password) { $password = str_random(RANDOM_KEY_LENGTH); } $user->password = bcrypt($password); } - $user->confirmed = !Utils::isNinja(); - $user->registered = !Utils::isNinja() || $email; + $user->confirmed = ! Utils::isNinja(); + $user->registered = ! Utils::isNinja() || $email; - if (!$user->confirmed) { + if (! $user->confirmed) { $user->confirmation_code = str_random(RANDOM_KEY_LENGTH); } @@ -185,11 +187,11 @@ class AccountRepository foreach ($entityTypes as $entityType) { $features[] = [ "new_{$entityType}", - Utils::pluralizeEntityType($entityType) . '/create' + Utils::pluralizeEntityType($entityType) . '/create', ]; $features[] = [ 'list_' . Utils::pluralizeEntityType($entityType), - Utils::pluralizeEntityType($entityType) + Utils::pluralizeEntityType($entityType), ]; } @@ -223,7 +225,7 @@ class AccountRepository $data[] = [ 'value' => trans('texts.' . $feature[0]), 'tokens' => trans('texts.' . $feature[0]), - 'url' => URL::to($feature[1]) + 'url' => URL::to($feature[1]), ]; } @@ -384,7 +386,7 @@ class AccountRepository ->first(); $clientExists = $client ? true : false; - if (!$client) { + if (! $client) { $client = new Client(); $client->public_id = $account->id; $client->account_id = $ninjaAccount->id; @@ -436,11 +438,12 @@ class AccountRepository public function updateUserFromOauth($user, $firstName, $lastName, $email, $providerId, $oauthUserId) { - if (!$user->registered) { + if (! $user->registered) { $rules = ['email' => 'email|required|unique:users,email,'.$user->id.',id']; $validator = Validator::make(['email' => $email], $rules); if ($validator->fails()) { $messages = $validator->messages(); + return $messages->first('email'); } @@ -520,7 +523,7 @@ class AccountRepository public function findUserAccounts($userId1, $userId2 = false) { - if (!Schema::hasTable('user_accounts')) { + if (! Schema::hasTable('user_accounts')) { return false; } @@ -543,12 +546,12 @@ class AccountRepository public function getUserAccounts($record, $with = null) { - if (!$record) { + if (! $record) { return false; } $userIds = []; - for ($i=1; $i<=5; $i++) { + for ($i = 1; $i <= 5; $i++) { $field = "user_id$i"; if ($record->$field) { $userIds[] = $record->$field; @@ -567,7 +570,7 @@ class AccountRepository public function prepareUsersData($record) { - if (!$record) { + if (! $record) { return false; } @@ -592,6 +595,7 @@ class AccountRepository public function loadAccounts($userId) { $record = self::findUserAccounts($userId); + return self::prepareUsersData($record); } @@ -601,7 +605,7 @@ class AccountRepository if ($record) { foreach ([$userId1, $userId2] as $userId) { - if (!$record->hasUserId($userId)) { + if (! $record->hasUserId($userId)) { $record->setUserId($userId); } } @@ -617,7 +621,7 @@ class AccountRepository // Pick the primary user foreach ($users as $user) { - if (!$user->public_id) { + if (! $user->public_id) { $useAsPrimary = false; if (empty($primaryUser)) { $useAsPrimary = true; @@ -632,7 +636,7 @@ class AccountRepository $planLevel = 2; } - if (!$useAsPrimary && ( + if (! $useAsPrimary && ( $planLevel > $primaryUserPlanLevel || ($planLevel == $primaryUserPlanLevel && $planDetails['expires'] > $primaryUserPlanExpires) )) { @@ -651,7 +655,7 @@ class AccountRepository } // Merge other companies into the primary user's company - if (!empty($primaryUser)) { + if (! empty($primaryUser)) { foreach ($users as $user) { if ($user == $primaryUser || $user->public_id) { continue; @@ -690,7 +694,7 @@ class AccountRepository $user = User::whereId($userId)->first(); - if (!$user->public_id && $user->account->hasMultipleAccounts()) { + if (! $user->public_id && $user->account->hasMultipleAccounts()) { $company = Company::create(); $company->save(); $user->account->company_id = $company->id; diff --git a/app/Ninja/Repositories/ActivityRepository.php b/app/Ninja/Repositories/ActivityRepository.php index 10d1465a8659..e8538a988ed6 100644 --- a/app/Ninja/Repositories/ActivityRepository.php +++ b/app/Ninja/Repositories/ActivityRepository.php @@ -1,12 +1,14 @@ -getClassName(); + return new $className(); } /** * @param $entity * @param $type + * * @return string */ private function getEventClass($entity, $type) @@ -102,6 +106,7 @@ class BaseRepository /** * @param $ids * @param $action + * * @return int */ public function bulk($ids, $action) @@ -123,6 +128,7 @@ class BaseRepository /** * @param $ids + * * @return mixed */ public function findByPublicIds($ids) @@ -132,6 +138,7 @@ class BaseRepository /** * @param $ids + * * @return mixed */ public function findByPublicIdsWithTrashed($ids) diff --git a/app/Ninja/Repositories/ClientRepository.php b/app/Ninja/Repositories/ClientRepository.php index f5c893d601f2..f2c3d19a1fcc 100644 --- a/app/Ninja/Repositories/ClientRepository.php +++ b/app/Ninja/Repositories/ClientRepository.php @@ -1,12 +1,14 @@ -account->client_number_counter && empty($data['id_number'])) { $data['id_number'] = Auth::user()->account->getNextNumber(); @@ -130,13 +132,13 @@ class ClientRepository extends BaseRepository if (! $client->wasRecentlyCreated) { foreach ($client->contacts as $contact) { - if (!in_array($contact->public_id, $contactIds)) { + if (! in_array($contact->public_id, $contactIds)) { $contact->delete(); } } } - if (!$publicId || $publicId == '-1') { + if (! $publicId || $publicId == '-1') { event(new ClientWasCreated($client)); } else { event(new ClientWasUpdated($client)); diff --git a/app/Ninja/Repositories/ContactRepository.php b/app/Ninja/Repositories/ContactRepository.php index e3bc389f5d99..51a30bec46d4 100644 --- a/app/Ninja/Repositories/ContactRepository.php +++ b/app/Ninja/Repositories/ContactRepository.php @@ -1,4 +1,6 @@ -send_invoice = true; $contact->client_id = $data['client_id']; diff --git a/app/Ninja/Repositories/CreditRepository.php b/app/Ninja/Repositories/CreditRepository.php index 48fb30ff3ae4..045e556f659c 100644 --- a/app/Ninja/Repositories/CreditRepository.php +++ b/app/Ninja/Repositories/CreditRepository.php @@ -1,9 +1,11 @@ -data = $records; $record->label = trans("texts.{$entityType}s"); $record->lineTension = 0; @@ -94,11 +97,11 @@ class DashboardRepository } } - $data = new stdClass; + $data = new stdClass(); $data->labels = $labels; $data->datasets = $datasets; - $response = new stdClass; + $response = new stdClass(); $response->data = $data; $response->totals = $totals; @@ -167,7 +170,7 @@ class DashboardRepository ->where('invoices.is_recurring', '=', false) ->where('invoices.invoice_type_id', '=', INVOICE_TYPE_STANDARD); - if (!$viewAll) { + if (! $viewAll) { $metrics = $metrics->where(function ($query) use ($userId) { $query->where('invoices.user_id', '=', $userId); $query->orwhere(function ($query) use ($userId) { @@ -197,7 +200,7 @@ class DashboardRepository ->where('payments.is_deleted', '=', false) ->whereNotIn('payments.payment_status_id', [PAYMENT_STATUS_VOIDED, PAYMENT_STATUS_FAILED]); - if (!$viewAll) { + if (! $viewAll) { $paidToDate->where('invoices.user_id', '=', $userId); } @@ -230,7 +233,7 @@ class DashboardRepository ->where('invoices.invoice_type_id', '=', INVOICE_TYPE_STANDARD) ->where('invoices.is_recurring', '=', false); - if (!$viewAll) { + if (! $viewAll) { $averageInvoice->where('invoices.user_id', '=', $userId); } @@ -258,7 +261,7 @@ class DashboardRepository ->groupBy('accounts.id') ->groupBy(DB::raw('CASE WHEN '.DB::getQueryGrammar()->wrap('clients.currency_id', true).' IS NULL THEN CASE WHEN '.DB::getQueryGrammar()->wrap('accounts.currency_id', true).' IS NULL THEN 1 ELSE '.DB::getQueryGrammar()->wrap('accounts.currency_id', true).' END ELSE '.DB::getQueryGrammar()->wrap('clients.currency_id', true).' END')); - if (!$viewAll) { + if (! $viewAll) { $balances->where('clients.user_id', '=', $userId); } @@ -270,7 +273,7 @@ class DashboardRepository $activities = Activity::where('activities.account_id', '=', $accountId) ->where('activities.activity_type_id', '>', 0); - if (!$viewAll) { + if (! $viewAll) { $activities = $activities->where('activities.user_id', '=', $userId); } @@ -296,7 +299,7 @@ class DashboardRepository ->where('contacts.is_primary', '=', true) ->where('invoices.due_date', '<', date('Y-m-d')); - if (!$viewAll) { + if (! $viewAll) { $pastDue = $pastDue->where('invoices.user_id', '=', $userId); } @@ -323,7 +326,7 @@ class DashboardRepository ->where('invoices.due_date', '>=', date('Y-m-d')) ->orderBy('invoices.due_date', 'asc'); - if (!$viewAll) { + if (! $viewAll) { $upcoming = $upcoming->where('invoices.user_id', '=', $userId); } @@ -346,7 +349,7 @@ class DashboardRepository ->where('contacts.is_primary', '=', true) ->whereNotIn('payments.payment_status_id', [PAYMENT_STATUS_VOIDED, PAYMENT_STATUS_FAILED]); - if (!$viewAll) { + if (! $viewAll) { $payments = $payments->where('payments.user_id', '=', $userId); } @@ -372,7 +375,7 @@ class DashboardRepository ->where('accounts.id', '=', $accountId) ->where('expenses.is_deleted', '=', false); - if (!$viewAll) { + if (! $viewAll) { $paidToDate = $paidToDate->where('expenses.user_id', '=', $userId); } diff --git a/app/Ninja/Repositories/DocumentRepository.php b/app/Ninja/Repositories/DocumentRepository.php index 97fd0bf20325..cd575ddcf382 100644 --- a/app/Ninja/Repositories/DocumentRepository.php +++ b/app/Ninja/Repositories/DocumentRepository.php @@ -1,10 +1,12 @@ -getClientOriginalExtension()); - if (empty(Document::$types[$extension]) && !empty(Document::$extraExtensions[$extension])) { + if (empty(Document::$types[$extension]) && ! empty(Document::$extraExtensions[$extension])) { $documentType = Document::$extraExtensions[$extension]; } else { $documentType = $extension; @@ -70,7 +72,7 @@ class DocumentRepository extends BaseRepository $name = $uploaded->getClientOriginalName(); $size = filesize($filePath); - if ($size/1000 > MAX_DOCUMENT_SIZE) { + if ($size / 1000 > MAX_DOCUMENT_SIZE) { return 'File too large'; } @@ -86,28 +88,28 @@ class DocumentRepository extends BaseRepository $document->fill($data); $disk = $document->getDisk(); - if (!$disk->exists($filename)) {// Have we already stored the same file + if (! $disk->exists($filename)) {// Have we already stored the same file $stream = fopen($filePath, 'r'); - $disk->getDriver()->putStream($filename, $stream, ['mimetype'=>$documentTypeData['mime']]); + $disk->getDriver()->putStream($filename, $stream, ['mimetype' => $documentTypeData['mime']]); fclose($stream); } // This is an image; check if we need to create a preview - if (in_array($documentType, ['jpeg','png','gif','bmp','tiff','psd'])) { + if (in_array($documentType, ['jpeg', 'png', 'gif', 'bmp', 'tiff', 'psd'])) { $makePreview = false; $imageSize = getimagesize($filePath); $width = $imageSize[0]; $height = $imageSize[1]; $imgManagerConfig = []; - if (in_array($documentType, ['gif','bmp','tiff','psd'])) { + if (in_array($documentType, ['gif', 'bmp', 'tiff', 'psd'])) { // Needs to be converted $makePreview = true; } elseif ($width > DOCUMENT_PREVIEW_SIZE || $height > DOCUMENT_PREVIEW_SIZE) { $makePreview = true; } - if (in_array($documentType, ['bmp','tiff','psd'])) { - if (!class_exists('Imagick')) { + if (in_array($documentType, ['bmp', 'tiff', 'psd'])) { + if (! class_exists('Imagick')) { // Cant't read this $makePreview = false; } else { @@ -117,13 +119,13 @@ class DocumentRepository extends BaseRepository if ($makePreview) { $previewType = 'jpeg'; - if (in_array($documentType, ['png','gif','tiff','psd'])) { + if (in_array($documentType, ['png', 'gif', 'tiff', 'psd'])) { // Has transparency $previewType = 'png'; } $document->preview = \Auth::user()->account->account_key.'/'.$hash.'.'.$documentType.'.x'.DOCUMENT_PREVIEW_SIZE.'.'.$previewType; - if (!$disk->exists($document->preview)) { + if (! $disk->exists($document->preview)) { // We haven't created a preview yet $imgManager = new ImageManager($imgManagerConfig); @@ -159,7 +161,7 @@ class DocumentRepository extends BaseRepository $document->hash = $hash; $document->name = substr($name, -255); - if (!empty($imageSize)) { + if (! empty($imageSize)) { $document->width = $imageSize[0]; $document->height = $imageSize[1]; } @@ -167,8 +169,8 @@ class DocumentRepository extends BaseRepository $document->save(); $doc_array = $document->toArray(); - if (!empty($base64)) { - $mime = Document::$types[!empty($previewType)?$previewType:$documentType]['mime']; + if (! empty($base64)) { + $mime = Document::$types[! empty($previewType) ? $previewType : $documentType]['mime']; $doc_array['base64'] = 'data:'.$mime.';base64,'.$base64; } @@ -210,7 +212,7 @@ class DocumentRepository extends BaseRepository return link_to( '/client/documents/'.$model->invitation_key.'/'.$model->public_id.'/'.$model->name, $model->name, - ['target'=>'_blank'] + ['target' => '_blank'] )->toHtml(); }) ->addColumn('document_date', function ($model) { diff --git a/app/Ninja/Repositories/ExpenseCategoryRepository.php b/app/Ninja/Repositories/ExpenseCategoryRepository.php index 5242784b5034..8ef629a17487 100644 --- a/app/Ninja/Repositories/ExpenseCategoryRepository.php +++ b/app/Ninja/Repositories/ExpenseCategoryRepository.php @@ -1,8 +1,10 @@ -save(); // Documents - $document_ids = !empty($input['document_ids'])?array_map('intval', $input['document_ids']):[]; + $document_ids = ! empty($input['document_ids']) ? array_map('intval', $input['document_ids']) : []; ; foreach ($document_ids as $document_id) { // check document completed upload before user submitted form diff --git a/app/Ninja/Repositories/InvoiceRepository.php b/app/Ninja/Repositories/InvoiceRepository.php index 11c1b4622424..f9a87902d911 100644 --- a/app/Ninja/Repositories/InvoiceRepository.php +++ b/app/Ninja/Repositories/InvoiceRepository.php @@ -1,19 +1,21 @@ -partial > 0 ? trans('texts.partial_remaining', [ 'partial' => Utils::formatMoney($model->partial, $model->currency_id, $model->country_id), - 'balance' => Utils::formatMoney($model->balance, $model->currency_id, $model->country_id) + 'balance' => Utils::formatMoney($model->balance, $model->currency_id, $model->country_id), ]) : Utils::formatMoney($model->balance, $model->currency_id, $model->country_id); }); @@ -294,8 +296,9 @@ class InvoiceRepository extends BaseRepository } /** - * @param array $data + * @param array $data * @param Invoice|null $invoice + * * @return Invoice|mixed */ public function save(array $data, Invoice $invoice = null) @@ -304,7 +307,7 @@ class InvoiceRepository extends BaseRepository $account = \Auth::user()->account; $publicId = isset($data['public_id']) ? $data['public_id'] : false; - $isNew = !$publicId || $publicId == '-1'; + $isNew = ! $publicId || $publicId == '-1'; if ($invoice) { // do nothing @@ -361,7 +364,7 @@ class InvoiceRepository extends BaseRepository $account->save(); } - if (!empty($data['invoice_number']) && !$invoice->is_recurring) { + if (! empty($data['invoice_number']) && ! $invoice->is_recurring) { $invoice->invoice_number = trim($data['invoice_number']); } @@ -405,7 +408,7 @@ class InvoiceRepository extends BaseRepository $invoice->due_date = $data['due_date']; } } else { - if (!empty($data['due_date']) || !empty($data['due_date_sql'])) { + if (! empty($data['due_date']) || ! empty($data['due_date_sql'])) { $invoice->due_date = isset($data['due_date_sql']) ? $data['due_date_sql'] : Utils::toSqlDate($data['due_date']); } $invoice->frequency_id = 0; @@ -421,11 +424,11 @@ class InvoiceRepository extends BaseRepository $invoice->terms = ''; } - $invoice->invoice_footer = (isset($data['invoice_footer']) && trim($data['invoice_footer'])) ? trim($data['invoice_footer']) : (!$publicId && $account->invoice_footer ? $account->invoice_footer : ''); + $invoice->invoice_footer = (isset($data['invoice_footer']) && trim($data['invoice_footer'])) ? trim($data['invoice_footer']) : (! $publicId && $account->invoice_footer ? $account->invoice_footer : ''); $invoice->public_notes = isset($data['public_notes']) ? trim($data['public_notes']) : ''; // process date variables if not recurring - if (!$invoice->is_recurring) { + if (! $invoice->is_recurring) { $invoice->terms = Utils::processVariables($invoice->terms); $invoice->invoice_footer = Utils::processVariables($invoice->invoice_footer); $invoice->public_notes = Utils::processVariables($invoice->public_notes); @@ -448,7 +451,7 @@ class InvoiceRepository extends BaseRepository foreach ($data['invoice_items'] as $item) { $item = (array) $item; - if (!$item['cost'] && !$item['product_key'] && !$item['notes']) { + if (! $item['cost'] && ! $item['product_key'] && ! $item['notes']) { continue; } @@ -467,9 +470,9 @@ class InvoiceRepository extends BaseRepository if ($invoice->discount > 0) { if ($invoice->is_amount_discount) { - $lineTotal -= round(($lineTotal/$total) * $invoice->discount, 2); + $lineTotal -= round(($lineTotal / $total) * $invoice->discount, 2); } else { - $lineTotal -= round($lineTotal * ($invoice->discount/100), 2); + $lineTotal -= round($lineTotal * ($invoice->discount / 100), 2); } } @@ -487,7 +490,7 @@ class InvoiceRepository extends BaseRepository if ($invoice->is_amount_discount) { $total -= $invoice->discount; } else { - $discount = round($total * ($invoice->discount/100), 2); + $discount = round($total * ($invoice->discount / 100), 2); $total -= $discount; } } @@ -526,10 +529,10 @@ class InvoiceRepository extends BaseRepository $total += $itemTax; // custom fields not charged taxes - if ($invoice->custom_value1 && !$invoice->custom_taxes1) { + if ($invoice->custom_value1 && ! $invoice->custom_taxes1) { $total += $invoice->custom_value1; } - if ($invoice->custom_value2 && !$invoice->custom_taxes2) { + if ($invoice->custom_value2 && ! $invoice->custom_taxes2) { $total += $invoice->custom_value2; } @@ -558,7 +561,7 @@ class InvoiceRepository extends BaseRepository if ($document->invoice_id && $document->invoice_id != $invoice->id) { // From a clone $document = $document->cloneDocument(); - $document_ids[] = $document->public_id;// Don't remove this document + $document_ids[] = $document->public_id; // Don't remove this document } $document->invoice_id = $invoice->id; @@ -569,7 +572,7 @@ class InvoiceRepository extends BaseRepository if (! $invoice->wasRecentlyCreated) { foreach ($invoice->documents as $document) { - if (!in_array($document->public_id, $document_ids)) { + if (! in_array($document->public_id, $document_ids)) { // Removed // Not checking permissions; deleting a document is just editing the invoice if ($document->invoice_id == $invoice->id) { @@ -610,7 +613,7 @@ class InvoiceRepository extends BaseRepository if ($productKey = trim($item['product_key'])) { if (\Auth::user()->account->update_products && ! $invoice->has_tasks && ! $invoice->has_expenses) { $product = Product::findProductByKey($productKey); - if (!$product) { + if (! $product) { if (Auth::user()->can('create', ENTITY_PRODUCT)) { $product = Product::createNew(); $product->product_key = trim($item['product_key']); @@ -656,7 +659,8 @@ class InvoiceRepository extends BaseRepository /** * @param Invoice $invoice - * @param null $quotePublicId + * @param null $quotePublicId + * * @return mixed */ public function cloneInvoice(Invoice $invoice, $quotePublicId = null) @@ -779,7 +783,6 @@ class InvoiceRepository extends BaseRepository //dispatch(new SendInvoiceEmail($invoice)); } - /** * @param Invoice $invoice */ @@ -810,6 +813,7 @@ class InvoiceRepository extends BaseRepository /** * @param $invitationKey + * * @return Invitation|bool */ public function findInvoiceByInvitation($invitationKey) @@ -817,19 +821,19 @@ class InvoiceRepository extends BaseRepository /** @var \App\Models\Invitation $invitation */ $invitation = Invitation::where('invitation_key', '=', $invitationKey)->first(); - if (!$invitation) { + if (! $invitation) { return false; } $invoice = $invitation->invoice; - if (!$invoice || $invoice->is_deleted) { + if (! $invoice || $invoice->is_deleted) { return false; } $invoice->load('user', 'invoice_items', 'documents', 'invoice_design', 'account.country', 'client.contacts', 'client.country'); $client = $invoice->client; - if (!$client || $client->is_deleted) { + if (! $client || $client->is_deleted) { return false; } @@ -838,6 +842,7 @@ class InvoiceRepository extends BaseRepository /** * @param $clientId + * * @return mixed */ public function findOpenInvoices($clientId, $entityType = false) @@ -862,6 +867,7 @@ class InvoiceRepository extends BaseRepository /** * @param Invoice $recurInvoice + * * @return mixed */ public function createRecurringInvoice(Invoice $recurInvoice) @@ -872,11 +878,11 @@ class InvoiceRepository extends BaseRepository return false; } - if (!$recurInvoice->user->confirmed) { + if (! $recurInvoice->user->confirmed) { return false; } - if (!$recurInvoice->shouldSendToday()) { + if (! $recurInvoice->shouldSendToday()) { return false; } @@ -940,7 +946,7 @@ class InvoiceRepository extends BaseRepository $recurInvoice->last_sent_date = date('Y-m-d'); $recurInvoice->save(); - if ($recurInvoice->getAutoBillEnabled() && !$recurInvoice->account->auto_bill_on_due_date) { + if ($recurInvoice->getAutoBillEnabled() && ! $recurInvoice->account->auto_bill_on_due_date) { // autoBillInvoice will check for ACH, so we're not checking here if ($this->paymentService->autoBillInvoice($invoice)) { // update the invoice reference to match its actual state @@ -954,13 +960,14 @@ class InvoiceRepository extends BaseRepository /** * @param Account $account + * * @return mixed */ public function findNeedingReminding(Account $account) { $dates = []; - for ($i=1; $i<=3; $i++) { + for ($i = 1; $i <= 3; $i++) { if ($date = $account->getReminderDate($i)) { $field = $account->{"field_reminder{$i}"} == REMINDER_FIELD_DUE_DATE ? 'due_date' : 'invoice_date'; $dates[] = "$field = '$date'"; diff --git a/app/Ninja/Repositories/NinjaRepository.php b/app/Ninja/Repositories/NinjaRepository.php index d1dc7abede6e..20921ce07934 100644 --- a/app/Ninja/Repositories/NinjaRepository.php +++ b/app/Ninja/Repositories/NinjaRepository.php @@ -1,4 +1,6 @@ -first(); - if (!$account) { + if (! $account) { return; } $company = $account->company; - $company->plan = !empty($data['plan']) && $data['plan'] != PLAN_FREE?$data['plan']:null; - $company->plan_term = !empty($data['plan_term'])?$data['plan_term']:null; - $company->plan_paid = !empty($data['plan_paid'])?$data['plan_paid']:null; - $company->plan_started = !empty($data['plan_started'])?$data['plan_started']:null; - $company->plan_expires = !empty($data['plan_expires'])?$data['plan_expires']:null; + $company->plan = ! empty($data['plan']) && $data['plan'] != PLAN_FREE ? $data['plan'] : null; + $company->plan_term = ! empty($data['plan_term']) ? $data['plan_term'] : null; + $company->plan_paid = ! empty($data['plan_paid']) ? $data['plan_paid'] : null; + $company->plan_started = ! empty($data['plan_started']) ? $data['plan_started'] : null; + $company->plan_expires = ! empty($data['plan_expires']) ? $data['plan_expires'] : null; $company->save(); } diff --git a/app/Ninja/Repositories/PaymentRepository.php b/app/Ninja/Repositories/PaymentRepository.php index 8624cc50a61f..84b0c440b380 100644 --- a/app/Ninja/Repositories/PaymentRepository.php +++ b/app/Ninja/Repositories/PaymentRepository.php @@ -1,10 +1,12 @@ -transaction_reference = trim($input['transaction_reference']); } - if (!$publicId) { + if (! $publicId) { $clientId = $input['client_id']; $amount = Utils::parseFloat($input['amount']); diff --git a/app/Ninja/Repositories/PaymentTermRepository.php b/app/Ninja/Repositories/PaymentTermRepository.php index bde31c20a81d..1632d14d4b65 100644 --- a/app/Ninja/Repositories/PaymentTermRepository.php +++ b/app/Ninja/Repositories/PaymentTermRepository.php @@ -1,4 +1,6 @@ - 0, 'pro' => 0, - 'enterprise' => 0 + 'enterprise' => 0, ]; foreach ($accounts as $account) { diff --git a/app/Ninja/Repositories/TaskRepository.php b/app/Ninja/Repositories/TaskRepository.php index 4dc19f1a2837..e0dbc298ad24 100644 --- a/app/Ninja/Repositories/TaskRepository.php +++ b/app/Ninja/Repositories/TaskRepository.php @@ -1,10 +1,12 @@ -is_running = true; $timeLog[] = [strtotime('now'), false]; } elseif ($data['action'] == 'stop' && $task->is_running) { - $timeLog[count($timeLog)-1][1] = time(); + $timeLog[count($timeLog) - 1][1] = time(); $task->is_running = false; } } diff --git a/app/Ninja/Repositories/TaxRateRepository.php b/app/Ninja/Repositories/TaxRateRepository.php index 52f229afd9af..d16973941b50 100644 --- a/app/Ninja/Repositories/TaxRateRepository.php +++ b/app/Ninja/Repositories/TaxRateRepository.php @@ -1,8 +1,10 @@ -send_invoice = true; $contact->vendor_id = $data['vendor_id']; diff --git a/app/Ninja/Repositories/VendorRepository.php b/app/Ninja/Repositories/VendorRepository.php index db7f81a305fa..0b5364841753 100644 --- a/app/Ninja/Repositories/VendorRepository.php +++ b/app/Ninja/Repositories/VendorRepository.php @@ -1,8 +1,10 @@ -with('vendor_contacts')->firstOrFail(); @@ -82,19 +84,19 @@ class VendorRepository extends BaseRepository $vendor->fill($data); $vendor->save(); - $first = true; - $vendorcontacts = isset($data['vendor_contact']) ? [$data['vendor_contact']] : $data['vendor_contacts']; - $vendorcontactIds = []; + $first = true; + $vendorcontacts = isset($data['vendor_contact']) ? [$data['vendor_contact']] : $data['vendor_contacts']; + $vendorcontactIds = []; foreach ($vendorcontacts as $vendorcontact) { - $vendorcontact = $vendor->addVendorContact($vendorcontact, $first); + $vendorcontact = $vendor->addVendorContact($vendorcontact, $first); $vendorcontactIds[] = $vendorcontact->public_id; - $first = false; + $first = false; } if (! $vendor->wasRecentlyCreated) { foreach ($vendor->vendor_contacts as $contact) { - if (!in_array($contact->public_id, $vendorcontactIds)) { + if (! in_array($contact->public_id, $vendorcontactIds)) { $contact->delete(); } } diff --git a/app/Ninja/Serializers/ArraySerializer.php b/app/Ninja/Serializers/ArraySerializer.php index a759ffc9e69c..071e697ce18a 100644 --- a/app/Ninja/Serializers/ArraySerializer.php +++ b/app/Ninja/Serializers/ArraySerializer.php @@ -1,15 +1,18 @@ - $account_token->name, - 'token' => $account_token->token + 'token' => $account_token->token, ]; } } diff --git a/app/Ninja/Transformers/AccountTransformer.php b/app/Ninja/Transformers/AccountTransformer.php index 434d9e7e3aeb..2dcecfe002c7 100644 --- a/app/Ninja/Transformers/AccountTransformer.php +++ b/app/Ninja/Transformers/AccountTransformer.php @@ -1,9 +1,11 @@ -serializer); + return $this->includeCollection($account->expense_categories, $transformer, 'expense_categories'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeProjects(Account $account) { $transformer = new ProjectTransformer($account, $this->serializer); + return $this->includeCollection($account->projects, $transformer, 'projects'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeUsers(Account $account) { $transformer = new UserTransformer($account, $this->serializer); + return $this->includeCollection($account->users, $transformer, 'users'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeClients(Account $account) { $transformer = new ClientTransformer($account, $this->serializer); + return $this->includeCollection($account->clients, $transformer, 'clients'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeInvoices(Account $account) { $transformer = new InvoiceTransformer($account, $this->serializer); + return $this->includeCollection($account->invoices, $transformer, 'invoices'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeProducts(Account $account) { $transformer = new ProductTransformer($account, $this->serializer); + return $this->includeCollection($account->products, $transformer, 'products'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includeTaxRates(Account $account) { $transformer = new TaxRateTransformer($account, $this->serializer); + return $this->includeCollection($account->tax_rates, $transformer, 'taxRates'); } /** * @param Account $account + * * @return \League\Fractal\Resource\Collection */ public function includePayments(Account $account) { $transformer = new PaymentTransformer($account, $this->serializer); + return $this->includeCollection($account->payments, $transformer, 'payments'); } /** * @param Account $account - * @return array + * * @throws \Laracasts\Presenter\Exceptions\PresenterException + * + * @return array */ public function transform(Account $account) { diff --git a/app/Ninja/Transformers/ActivityTransformer.php b/app/Ninja/Transformers/ActivityTransformer.php index 44a5a712b472..5c0ea3e3ab41 100644 --- a/app/Ninja/Transformers/ActivityTransformer.php +++ b/app/Ninja/Transformers/ActivityTransformer.php @@ -1,22 +1,24 @@ - $this->getTimestamp($activity->updated_at), 'expense_id' => $activity->expense_id ? $activity->expense->public_id : null, 'is_system' => $activity->is_system ? (bool) $activity->is_system : null, - 'contact_id' => $activity->contact_id ? $activity->contact->public_id : null + 'contact_id' => $activity->contact_id ? $activity->contact->public_id : null, ]; } } diff --git a/app/Ninja/Transformers/ClientTransformer.php b/app/Ninja/Transformers/ClientTransformer.php index eb8805b6f168..2986eb73c1fb 100644 --- a/app/Ninja/Transformers/ClientTransformer.php +++ b/app/Ninja/Transformers/ClientTransformer.php @@ -1,42 +1,42 @@ -account, $this->serializer); + return $this->includeCollection($client->contacts, $transformer, ENTITY_CONTACT); } /** * @param Client $client + * * @return \League\Fractal\Resource\Collection */ public function includeInvoices(Client $client) { $transformer = new InvoiceTransformer($this->account, $this->serializer, $client); + return $this->includeCollection($client->invoices, $transformer, ENTITY_INVOICE); } /** * @param Client $client + * * @return \League\Fractal\Resource\Collection */ public function includeCredits(Client $client) { $transformer = new CreditTransformer($this->account, $this->serializer); + return $this->includeCollection($client->credits, $transformer, ENTITY_CREDIT); } /** * @param Client $client + * * @return \League\Fractal\Resource\Collection */ public function includeExpenses(Client $client) { $transformer = new ExpenseTransformer($this->account, $this->serializer); + return $this->includeCollection($client->expenses, $transformer, ENTITY_EXPENSE); } - /** * @param Client $client + * * @return array */ public function transform(Client $client) diff --git a/app/Ninja/Transformers/ContactTransformer.php b/app/Ninja/Transformers/ContactTransformer.php index 279658979ef3..4fd72ffde690 100644 --- a/app/Ninja/Transformers/ContactTransformer.php +++ b/app/Ninja/Transformers/ContactTransformer.php @@ -1,14 +1,17 @@ -getDefaults($document), [ 'id' => (int) $document->public_id, 'name' => $document->name, - 'type' => $document->type, + 'type' => $document->type, 'invoice_id' => isset($document->invoice->public_id) ? (int) $document->invoice->public_id : null, 'expense_id' => isset($document->expense->public_id) ? (int) $document->expense->public_id : null, 'updated_at' => $this->getTimestamp($document->updated_at), diff --git a/app/Ninja/Transformers/EntityTransformer.php b/app/Ninja/Transformers/EntityTransformer.php index e40225af275e..4be378e72fc2 100644 --- a/app/Ninja/Transformers/EntityTransformer.php +++ b/app/Ninja/Transformers/EntityTransformer.php @@ -1,7 +1,9 @@ -getDefaults($expenseCategory), [ diff --git a/app/Ninja/Transformers/ExpenseTransformer.php b/app/Ninja/Transformers/ExpenseTransformer.php index 953eac338aee..0937f25f45f6 100644 --- a/app/Ninja/Transformers/ExpenseTransformer.php +++ b/app/Ninja/Transformers/ExpenseTransformer.php @@ -1,4 +1,6 @@ -account, $this->serializer); + return $this->includeCollection($invoice->invoice_items, $transformer, ENTITY_INVOICE_ITEM); } public function includeInvitations(Invoice $invoice) { $transformer = new InvitationTransformer($this->account, $this->serializer); + return $this->includeCollection($invoice->invitations, $transformer, ENTITY_INVITATION); } public function includePayments(Invoice $invoice) { $transformer = new PaymentTransformer($this->account, $this->serializer, $invoice); + return $this->includeCollection($invoice->payments, $transformer, ENTITY_PAYMENT); } public function includeClient(Invoice $invoice) { $transformer = new ClientTransformer($this->account, $this->serializer); + return $this->includeItem($invoice->client, $transformer, ENTITY_CLIENT); } public function includeExpenses(Invoice $invoice) { $transformer = new ExpenseTransformer($this->account, $this->serializer); + return $this->includeCollection($invoice->expenses, $transformer, ENTITY_EXPENSE); } public function includeDocuments(Invoice $invoice) { $transformer = new DocumentTransformer($this->account, $this->serializer); + return $this->includeCollection($invoice->documents, $transformer, ENTITY_DOCUMENT); } - public function transform(Invoice $invoice) { return array_merge($this->getDefaults($invoice), [ @@ -85,7 +90,7 @@ class InvoiceTransformer extends EntityTransformer 'updated_at' => $this->getTimestamp($invoice->updated_at), 'archived_at' => $this->getTimestamp($invoice->deleted_at), 'invoice_number' => $invoice->invoice_number, - 'discount' => (double) $invoice->discount, + 'discount' => (float) $invoice->discount, 'po_number' => $invoice->po_number, 'invoice_date' => $invoice->invoice_date, 'due_date' => $invoice->due_date, diff --git a/app/Ninja/Transformers/PaymentTransformer.php b/app/Ninja/Transformers/PaymentTransformer.php index ce8826a6c7ac..81e014de4b66 100644 --- a/app/Ninja/Transformers/PaymentTransformer.php +++ b/app/Ninja/Transformers/PaymentTransformer.php @@ -1,21 +1,22 @@ -account, $this->serializer); + return $this->includeItem($payment->invoice, $transformer, 'invoice'); } public function includeClient(Payment $payment) { $transformer = new ClientTransformer($this->account, $this->serializer); + return $this->includeItem($payment->client, $transformer, 'client'); } diff --git a/app/Ninja/Transformers/ProductTransformer.php b/app/Ninja/Transformers/ProductTransformer.php index 00a0a7c06281..fd7e47c039c5 100644 --- a/app/Ninja/Transformers/ProductTransformer.php +++ b/app/Ninja/Transformers/ProductTransformer.php @@ -1,24 +1,24 @@ -getDefaults($product), [ @@ -27,8 +27,8 @@ class ProductTransformer extends EntityTransformer 'notes' => $product->notes, 'cost' => $product->cost, 'qty' => $product->qty, - 'default_tax_rate_id' =>$product->default_tax_rate_id, - 'updated_at' =>$this->getTimestamp($product->updated_at), + 'default_tax_rate_id' => $product->default_tax_rate_id, + 'updated_at' => $this->getTimestamp($product->updated_at), 'archived_at' => $this->getTimestamp($product->deleted_at), ]); } diff --git a/app/Ninja/Transformers/ProjectTransformer.php b/app/Ninja/Transformers/ProjectTransformer.php index e17b3cafcd3f..ae2a1acb92f6 100644 --- a/app/Ninja/Transformers/ProjectTransformer.php +++ b/app/Ninja/Transformers/ProjectTransformer.php @@ -1,22 +1,22 @@ -getDefaults($project), [ diff --git a/app/Ninja/Transformers/TaskTransformer.php b/app/Ninja/Transformers/TaskTransformer.php index eedc06b509e8..d7c695588e36 100644 --- a/app/Ninja/Transformers/TaskTransformer.php +++ b/app/Ninja/Transformers/TaskTransformer.php @@ -1,25 +1,25 @@ -client) { $transformer = new ClientTransformer($this->account, $this->serializer); + return $this->includeItem($task->client, $transformer, 'client'); } else { return null; diff --git a/app/Ninja/Transformers/TaxRateTransformer.php b/app/Ninja/Transformers/TaxRateTransformer.php index fc09b803544c..8e3bf57e69c0 100644 --- a/app/Ninja/Transformers/TaxRateTransformer.php +++ b/app/Ninja/Transformers/TaxRateTransformer.php @@ -1,23 +1,23 @@ -getDefaults($taxRate), [ diff --git a/app/Ninja/Transformers/UserAccountTransformer.php b/app/Ninja/Transformers/UserAccountTransformer.php index 0009b250e4c2..57a8a9f65214 100644 --- a/app/Ninja/Transformers/UserAccountTransformer.php +++ b/app/Ninja/Transformers/UserAccountTransformer.php @@ -1,12 +1,14 @@ -account, $this->serializer); + return $this->includeItem($user, $transformer, 'user'); } diff --git a/app/Ninja/Transformers/UserTransformer.php b/app/Ninja/Transformers/UserTransformer.php index 905fc669f343..af2de116f801 100644 --- a/app/Ninja/Transformers/UserTransformer.php +++ b/app/Ninja/Transformers/UserTransformer.php @@ -1,4 +1,6 @@ -account, $this->serializer); + return $this->includeCollection($vendor->vendor_contacts, $transformer, ENTITY_CONTACT); } public function includeInvoices(Vendor $vendor) { $transformer = new InvoiceTransformer($this->account, $this->serializer); + return $this->includeCollection($vendor->invoices, $transformer, ENTITY_INVOICE); } public function includeExpenses(Vendor $vendor) { $transformer = new ExpenseTransformer($this->account, $this->serializer); + return $this->includeCollection($vendor->expenses, $transformer, ENTITY_EXPENSE); } @@ -82,7 +85,7 @@ class VendorTransformer extends EntityTransformer 'is_deleted' => (bool) $vendor->is_deleted, 'vat_number' => $vendor->vat_number, 'id_number' => $vendor->id_number, - 'currency_id' => (int) $vendor->currency_id + 'currency_id' => (int) $vendor->currency_id, ]); } } diff --git a/app/Policies/AccountGatewayPolicy.php b/app/Policies/AccountGatewayPolicy.php index a7397eedfbeb..48f73f9b307e 100644 --- a/app/Policies/AccountGatewayPolicy.php +++ b/app/Policies/AccountGatewayPolicy.php @@ -5,14 +5,14 @@ namespace App\Policies; use App\Models\User; /** - * Class AccountGatewayPolicy + * Class AccountGatewayPolicy. */ class AccountGatewayPolicy extends EntityPolicy { - /** * @param User $user * @param $item + * * @return bool */ public static function edit(User $user, $item) @@ -22,6 +22,7 @@ class AccountGatewayPolicy extends EntityPolicy /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/BankAccountPolicy.php b/app/Policies/BankAccountPolicy.php index 94831c587ab0..f7cb9f3f394a 100644 --- a/app/Policies/BankAccountPolicy.php +++ b/app/Policies/BankAccountPolicy.php @@ -5,13 +5,14 @@ namespace App\Policies; use App\Models\User; /** - * Class BankAccountPolicy + * Class BankAccountPolicy. */ class BankAccountPolicy extends EntityPolicy { /** * @param User $user * @param $item + * * @return bool */ public static function edit(User $user, $item) @@ -21,6 +22,7 @@ class BankAccountPolicy extends EntityPolicy /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/DocumentPolicy.php b/app/Policies/DocumentPolicy.php index abb440800412..55fb67259f8b 100644 --- a/app/Policies/DocumentPolicy.php +++ b/app/Policies/DocumentPolicy.php @@ -5,22 +5,24 @@ namespace App\Policies; use App\Models\User; /** - * Class DocumentPolicy + * Class DocumentPolicy. */ class DocumentPolicy extends EntityPolicy { /** * @param User $user + * * @return bool */ public static function create(User $user, $item) { - return !empty($user); + return ! empty($user); } /** - * @param User $user + * @param User $user * @param Document $document + * * @return bool */ public static function view(User $user, $document) @@ -32,6 +34,7 @@ class DocumentPolicy extends EntityPolicy if ($document->expense->invoice) { return $user->can('view', $document->expense->invoice); } + return $user->can('view', $document->expense); } if ($document->invoice) { diff --git a/app/Policies/EntityPolicy.php b/app/Policies/EntityPolicy.php index a046e150648b..67b6e58b14b8 100644 --- a/app/Policies/EntityPolicy.php +++ b/app/Policies/EntityPolicy.php @@ -6,7 +6,7 @@ use App\Models\User; use Illuminate\Auth\Access\HandlesAuthorization; /** - * Class EntityPolicy + * Class EntityPolicy. */ class EntityPolicy { @@ -14,6 +14,7 @@ class EntityPolicy /** * @param User $user + * * @return bool */ public static function create(User $user, $item) @@ -58,6 +59,7 @@ class EntityPolicy /** * @param User $user * @param $ownerUserId + * * @return bool */ public static function viewByOwner(User $user, $ownerUserId) @@ -68,6 +70,7 @@ class EntityPolicy /** * @param User $user * @param $ownerUserId + * * @return bool */ public static function editByOwner(User $user, $ownerUserId) diff --git a/app/Policies/ExpenseCategoryPolicy.php b/app/Policies/ExpenseCategoryPolicy.php index b503026b45b6..405897314db5 100644 --- a/app/Policies/ExpenseCategoryPolicy.php +++ b/app/Policies/ExpenseCategoryPolicy.php @@ -6,9 +6,9 @@ use App\Models\User; class ExpenseCategoryPolicy extends EntityPolicy { - /** * @param User $user + * * @return bool */ public static function create(User $user, $item) @@ -41,9 +41,10 @@ class ExpenseCategoryPolicy extends EntityPolicy /** * @param User $user * @param $ownerUserId + * * @return bool */ - public static function viewByOwner(User$user, $ownerUserId) + public static function viewByOwner(User $user, $ownerUserId) { return true; } @@ -51,6 +52,7 @@ class ExpenseCategoryPolicy extends EntityPolicy /** * @param User $user * @param $ownerUserId + * * @return bool */ public static function editByOwner(User $user, $ownerUserId) diff --git a/app/Policies/ExpensePolicy.php b/app/Policies/ExpensePolicy.php index 582713777dfd..df79cba7d71b 100644 --- a/app/Policies/ExpensePolicy.php +++ b/app/Policies/ExpensePolicy.php @@ -8,6 +8,7 @@ class ExpensePolicy extends EntityPolicy { /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/GenericEntityPolicy.php b/app/Policies/GenericEntityPolicy.php index 8d5c6bf438ca..527f6b216b1e 100644 --- a/app/Policies/GenericEntityPolicy.php +++ b/app/Policies/GenericEntityPolicy.php @@ -2,13 +2,13 @@ namespace App\Policies; -use Utils; use App\Models\User; -use Illuminate\Support\Str; use Illuminate\Auth\Access\HandlesAuthorization; +use Illuminate\Support\Str; +use Utils; /** - * Class GenericEntityPolicy + * Class GenericEntityPolicy. */ class GenericEntityPolicy { @@ -18,6 +18,7 @@ class GenericEntityPolicy * @param User $user * @param $entityType * @param $ownerUserId + * * @return bool|mixed */ public static function editByOwner(User $user, $entityType, $ownerUserId) @@ -34,6 +35,7 @@ class GenericEntityPolicy * @param User $user * @param $entityTypee * @param $ownerUserId + * * @return bool|mixed */ public static function viewByOwner(User $user, $entityType, $ownerUserId) @@ -49,6 +51,7 @@ class GenericEntityPolicy /** * @param User $user * @param $entityType + * * @return bool|mixed */ public static function create(User $user, $entityType) @@ -64,6 +67,7 @@ class GenericEntityPolicy /** * @param User $user * @param $entityType + * * @return bool|mixed */ public static function view(User $user, $entityType) @@ -85,6 +89,7 @@ class GenericEntityPolicy } $studly = Str::studly($entityType); + return "App\\Policies\\{$studly}Policy"; } } diff --git a/app/Policies/PaymentTermPolicy.php b/app/Policies/PaymentTermPolicy.php index 054b88d0e289..83d882e0f21c 100644 --- a/app/Policies/PaymentTermPolicy.php +++ b/app/Policies/PaymentTermPolicy.php @@ -5,14 +5,14 @@ namespace App\Policies; use App\Models\User; /** - * Class PaymentTermPolicy + * Class PaymentTermPolicy. */ class PaymentTermPolicy extends EntityPolicy { - /** * @param User $user * @param $item + * * @return mixed */ public static function edit(User $user, $item) @@ -22,6 +22,7 @@ class PaymentTermPolicy extends EntityPolicy /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/ProductPolicy.php b/app/Policies/ProductPolicy.php index bf3c96472ba8..6c40ebc7e15e 100644 --- a/app/Policies/ProductPolicy.php +++ b/app/Policies/ProductPolicy.php @@ -3,7 +3,7 @@ namespace App\Policies; /** - * Class ProductPolicy + * Class ProductPolicy. */ class ProductPolicy extends EntityPolicy { diff --git a/app/Policies/QuotePolicy.php b/app/Policies/QuotePolicy.php index 20909f3df721..e23612a2b431 100644 --- a/app/Policies/QuotePolicy.php +++ b/app/Policies/QuotePolicy.php @@ -8,6 +8,7 @@ class QuotePolicy extends EntityPolicy { /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/TaskPolicy.php b/app/Policies/TaskPolicy.php index d6ab2bba90e0..455418c3232e 100644 --- a/app/Policies/TaskPolicy.php +++ b/app/Policies/TaskPolicy.php @@ -8,6 +8,7 @@ class TaskPolicy extends EntityPolicy { /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/TaxRatePolicy.php b/app/Policies/TaxRatePolicy.php index d2142e375e15..8f344b13d4dc 100644 --- a/app/Policies/TaxRatePolicy.php +++ b/app/Policies/TaxRatePolicy.php @@ -9,6 +9,7 @@ class TaxRatePolicy extends EntityPolicy /** * @param User $user * @param $item + * * @return bool */ public static function edit(User $user, $item) @@ -18,6 +19,7 @@ class TaxRatePolicy extends EntityPolicy /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Policies/VendorPolicy.php b/app/Policies/VendorPolicy.php index 8f993e2ed9b4..c01a67274052 100644 --- a/app/Policies/VendorPolicy.php +++ b/app/Policies/VendorPolicy.php @@ -8,6 +8,7 @@ class VendorPolicy extends EntityPolicy { /** * @param User $user + * * @return bool */ public static function create(User $user, $item) diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 8c6989923e29..9f85ad22ea33 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -1,18 +1,19 @@ -'.$text.''; }); @@ -47,7 +49,7 @@ class AppServiceProvider extends ServiceProvider $types = $type.'s'; $Type = ucfirst($type); $Types = ucfirst($types); - $class = (Request::is($types) || Request::is('*'.$type.'*')) && !Request::is('*settings*') ? ' active' : ''; + $class = (Request::is($types) || Request::is('*'.$type.'*')) && ! Request::is('*settings*') ? ' active' : ''; return ''; } - if (property_exists($model, 'is_deleted') && !$model->is_deleted && $can_edit) { + if (property_exists($model, 'is_deleted') && ! $model->is_deleted && $can_edit) { $dropdown_contents .= "
  • entityType}('delete', {$model->public_id})\">" . mtrans($datatable->entityType, "delete_{$datatable->entityType}") . '
  • '; } - if (!empty($dropdown_contents)) { + if (! empty($dropdown_contents)) { $str .= '