Compare commits

...

24 Commits

Author SHA1 Message Date
Yusuke Arakawa
662f6ac3eb chore: Sort the supported language list of readme.md (#1062) 2022-12-09 09:40:52 +01:00
Attila Kerekes
11257a272e feat: Introduce queue based live stat refresh (#1059) 2022-12-05 16:29:06 +01:00
Attila Kerekes
6b93f8ed5c test: Add item create test (#1058) 2022-12-05 16:28:18 +01:00
Attila Kerekes
8f9b2959b2 feat: Add basic import screen (#1056)
Co-authored-by: Chris Hunt <chris.hunt@kasmweb.com>
2022-12-04 22:12:54 +01:00
Attila Kerekes
45cc84c99c test: Add feature tests 2022-12-04 17:21:03 +00:00
Attila Kerekes
52620bc331 chore: Add laravel ide helper 2022-12-01 09:17:54 +00:00
Attila Kerekes
bd76efc613 chore: Migrate route definition to Laravel 8 format 2022-11-29 21:34:11 +00:00
Attila Kerekes
6dead1c529 fix: Make supportedApps legacy interface compatible 2022-11-29 19:26:07 +00:00
Attila Kerekes
bb5a078f35 feat: Add export import 2022-11-29 17:32:46 +00:00
Attila Kerekes
2ee5d07e48 fix: Make supportedapps compatible with legacy interface 2022-11-29 17:26:40 +00:00
Attila Kerekes
d30edb6749 chore: Add eslint prettier phpcs config PSR2 2022-11-28 19:47:10 +00:00
Chris Hunt
a53192beeb FIx: Blur onauxclick as well 2022-11-28 08:33:05 +00:00
Chris Hunt
ef1ffe880d Update version to 2.5.4 2022-11-28 08:30:34 +00:00
KodeStar
877b31f947 Merge pull request #1041 from linuxserver/bug/links_opening_in_new_tab_keep_focus
Blur tiles after clicking on them
2022-11-26 17:02:45 +00:00
Chris Hunt
827088df76 Blur tiles after clicking on them 2022-11-26 14:48:54 +00:00
Attila Kerekes
a12c1d559d fix: Use correct appTest argument type 2022-11-26 13:31:05 +00:00
KodeStar
f0b60fc19a Merge pull request #1039 from linuxserver/fix/1038
fix: Enter should open search when not tile search is selected
2022-11-26 12:00:43 +00:00
Attila Kerekes
7c4619adb9 fix: Enter should open search when not tile search is selected 2022-11-26 12:22:12 +01:00
KodeStar
aa49a5fb42 Fixes #371 Tagged items when pinning/unpinning (#1036) 2022-11-25 23:21:45 +00:00
Attila Jozsef Kerekes
7565bd4028 chore: Add php code sniffer and apply fixes 2022-11-25 23:05:58 +00:00
Chris Hunt
181b7564e8 Merge branch '2.x' of github.com:linuxserver/Heimdall into 2.x 2022-11-25 16:23:40 +00:00
Chris Hunt
0d3640b67a Fix asset links 2022-11-25 16:23:34 +00:00
Attila Kerekes
82b209d4b5 fix: Test enhanced app with apikey 2022-11-25 16:11:39 +00:00
Chris Hunt
f576a82803 Fix: Change default logging to daily 2022-11-24 22:56:27 +00:00
2073 changed files with 259805 additions and 588 deletions

3
.eslintignore Normal file
View File

@@ -0,0 +1,3 @@
huebee.js
jquery-ui.min.js
bootstrap.js

13
.eslintrc Normal file
View File

@@ -0,0 +1,13 @@
{
"extends": ["airbnb-base", "prettier"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": ["error"]
},
"env": {
"browser": true
},
"globals": {
"$": true
}
}

View File

@@ -41,7 +41,7 @@ jobs:
run: yarn && yarn dev
- name: Run tests
run: ./vendor/bin/phpunit
run: php artisan test
env:
APP_ENV: testing

2080
.phpstorm.meta.php Normal file

File diff suppressed because it is too large Load Diff

20867
_ide_helper.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -2,9 +2,43 @@
namespace App;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* App\Application
*
* @property string $appid
* @property string $name
* @property string|null $sha
* @property string|null $icon
* @property string|null $website
* @property string|null $license
* @property string|null $description
* @property int $enhanced
* @property string $tile_background
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property string|null $class
* @method static Builder|Application newModelQuery()
* @method static Builder|Application newQuery()
* @method static Builder|Application query()
* @method static Builder|Application whereAppid($value)
* @method static Builder|Application whereClass($value)
* @method static Builder|Application whereCreatedAt($value)
* @method static Builder|Application whereDescription($value)
* @method static Builder|Application whereEnhanced($value)
* @method static Builder|Application whereIcon($value)
* @method static Builder|Application whereLicense($value)
* @method static Builder|Application whereName($value)
* @method static Builder|Application whereSha($value)
* @method static Builder|Application whereTileBackground($value)
* @method static Builder|Application whereUpdatedAt($value)
* @method static Builder|Application whereWebsite($value)
*/
class Application extends Model
{
/**
@@ -61,16 +95,14 @@ class Application extends Model
$name = $this->name;
$name = preg_replace('/[^\p{L}\p{N}]/u', '', $name);
$class = '\App\SupportedApps\\'.$name.'\\'.$name;
return $class;
return '\App\SupportedApps\\'.$name.'\\'.$name;
}
/**
* @param $name
* @return string
*/
public static function classFromName($name)
public static function classFromName($name): string
{
$name = preg_replace('/[^\p{L}\p{N}]/u', '', $name);
@@ -80,9 +112,9 @@ class Application extends Model
}
/**
* @return \Illuminate\Support\Collection
* @return Collection
*/
public static function apps(): \Illuminate\Support\Collection
public static function apps(): Collection
{
$json = json_decode(file_get_contents(storage_path('app/supportedapps.json'))) ?? [];
$apps = collect($json->apps);
@@ -110,6 +142,7 @@ class Application extends Model
/**
* @param $appid
* @return mixed|null
* @throws GuzzleException
*/
public static function getApp($appid)
{
@@ -121,13 +154,12 @@ class Application extends Model
$application = ($localapp) ? $localapp : new self;
// Files missing? || app not in db || old sha version
if (
! file_exists(app_path('SupportedApps/'.className($app->name))) ||
if (! file_exists(app_path('SupportedApps/'.className($app->name))) ||
! $localapp ||
$localapp->sha !== $app->sha
) {
$gotFiles = SupportedApps::getFiles($app);
if($gotFiles) {
if ($gotFiles) {
$app = SupportedApps::saveApp($app, $application);
}
}
@@ -147,7 +179,7 @@ class Application extends Model
if ($app === null) {
// Try in db for Private App
$appModel = self::where('appid', $appid)->first();
if($appModel) {
if ($appModel) {
$app = json_decode($appModel->toJson());
}
}
@@ -176,7 +208,7 @@ class Application extends Model
// Check for private apps in the db
$appsListFromDB = self::all(['appid', 'name']);
foreach($appsListFromDB as $app) {
foreach ($appsListFromDB as $app) {
// Already existing keys are overwritten,
// only private apps should be added at the end
$list[$app->appid] = $app->name;

View File

@@ -36,7 +36,7 @@ class RegisterApp extends Command
/**
* Execute the console command.
*
* @return mixed
* @return void
*/
public function handle()
{
@@ -54,7 +54,12 @@ class RegisterApp extends Command
}
}
public function addApp($folder, $remove = false)
/**
* @param $folder
* @param bool $remove
* @return void
*/
public function addApp($folder, bool $remove = false)
{
$json = app_path('SupportedApps/'.$folder.'/app.json');
@@ -88,7 +93,13 @@ class RegisterApp extends Command
$this->info('Application Added - ' . $app->name . ' - ' . $app->appid);
}
private function saveIcon($appFolder, $icon) {
/**
* @param $appFolder
* @param $icon
* @return void
*/
private function saveIcon($appFolder, $icon)
{
$iconPath = app_path('SupportedApps/' . $appFolder . '/' . $icon);
$contents = file_get_contents($iconPath);
Storage::disk('public')->put('icons/'.$icon, $contents);

View File

@@ -19,7 +19,7 @@ class Kernel extends ConsoleKernel
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @param Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)

View File

@@ -2,7 +2,14 @@
use Illuminate\Support\Str;
function format_bytes($bytes, $is_drive_size = true, $beforeunit = '', $afterunit = '')
/**
* @param $bytes
* @param bool $is_drive_size
* @param string $beforeunit
* @param string $afterunit
* @return string
*/
function format_bytes($bytes, bool $is_drive_size = true, string $beforeunit = '', string $afterunit = ''): string
{
$btype = ($is_drive_size === true) ? 1000 : 1024;
$labels = ['B', 'KB', 'MB', 'GB', 'TB'];
@@ -18,7 +25,13 @@ function format_bytes($bytes, $is_drive_size = true, $beforeunit = '', $afteruni
}
}
function str_slug($title, $separator = '-', $language = 'en')
/**
* @param $title
* @param string $separator
* @param string $language
* @return string
*/
function str_slug($title, string $separator = '-', string $language = 'en'): string
{
return Str::slug($title, $separator, $language);
}
@@ -28,17 +41,21 @@ if (! function_exists('str_is')) {
* Determine if a given string matches a given pattern.
*
* @param string|array $pattern
* @param string $value
* @param string $value
* @return bool
*
* @deprecated Str::is() should be used directly instead. Will be removed in Laravel 6.0.
*/
function str_is($pattern, $value)
function str_is($pattern, string $value): bool
{
return Str::is($pattern, $value);
}
}
/**
* @param $hex
* @return float|int
*/
function get_brightness($hex)
{
// returns brightness value from 0 to 255
@@ -56,7 +73,11 @@ function get_brightness($hex)
return (($c_r * 299) + ($c_g * 587) + ($c_b * 114)) / 1000;
}
function title_color($hex)
/**
* @param $hex
* @return string
*/
function title_color($hex): string
{
if (get_brightness($hex) > 130) {
return ' black';
@@ -65,7 +86,10 @@ function title_color($hex)
}
}
function getLinkTargetAttribute()
/**
* @return string
*/
function getLinkTargetAttribute(): string
{
$target = \App\Setting::fetch('window_target');
@@ -76,9 +100,11 @@ function getLinkTargetAttribute()
}
}
/**
* @param $name
* @return array|string|string[]|null
*/
function className($name)
{
$name = preg_replace('/[^\p{L}\p{N}]/u', '', $name);
return $name;
return preg_replace('/[^\p{L}\p{N}]/u', '', $name);
}

View File

@@ -4,11 +4,17 @@ namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\URL;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
class LoginController extends Controller
{
@@ -30,7 +36,7 @@ class LoginController extends Controller
*
* @var string
*/
protected $redirectTo = '/';
protected string $redirectTo = '/';
/**
* Create a new controller instance.
@@ -43,7 +49,10 @@ class LoginController extends Controller
$this->middleware('guest')->except('logout');
}
public function username()
/**
* @return string
*/
public function username(): string
{
return 'username';
}
@@ -51,12 +60,12 @@ class LoginController extends Controller
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
* @param Request $request
* @return Response
*
* @throws \Illuminate\Validation\ValidationException
* @throws ValidationException
*/
public function login(Request $request)
public function login(Request $request): Response
{
$current_user = User::currentUser();
$request->merge(['username' => $current_user->username, 'remember' => true]);
@@ -88,7 +97,11 @@ class LoginController extends Controller
{
}
public function setUser(User $user)
/**
* @param User $user
* @return RedirectResponse
*/
public function setUser(User $user): RedirectResponse
{
Auth::logout();
session(['current_user' => $user]);
@@ -96,7 +109,11 @@ class LoginController extends Controller
return redirect()->route('dash');
}
public function autologin($uuid)
/**
* @param $uuid
* @return RedirectResponse
*/
public function autologin($uuid): RedirectResponse
{
$user = User::where('autologin', $uuid)->first();
Auth::login($user, true);
@@ -108,18 +125,26 @@ class LoginController extends Controller
/**
* Show the application's login form.
*
* @return \Illuminate\Http\Response
* @return Application|Factory|View
*/
public function showLoginForm()
{
return view('auth.login');
}
protected function authenticated(Request $request, $user)
/**
* @param Request $request
* @param $user
* @return RedirectResponse
*/
protected function authenticated(Request $request, $user): RedirectResponse
{
return back();
}
/**
* @return mixed|string
*/
public function redirectTo()
{
return Session::get('url.intended') ? Session::get('url.intended') : $this->redirectTo;

View File

@@ -27,7 +27,7 @@ class RegisterController extends Controller
*
* @var string
*/
protected $redirectTo = '/';
protected string $redirectTo = '/';
/**
* Create a new controller instance.
@@ -45,7 +45,7 @@ class RegisterController extends Controller
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
protected function validator(array $data): \Illuminate\Contracts\Validation\Validator
{
return Validator::make($data, [
'name' => 'required|string|max:255',
@@ -58,7 +58,7 @@ class RegisterController extends Controller
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
* @return User
*/
protected function create(array $data)
{

View File

@@ -25,7 +25,7 @@ class ResetPasswordController extends Controller
*
* @var string
*/
protected $redirectTo = '/';
protected string $redirectTo = '/';
/**
* Create a new controller instance.

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
class ImportController extends Controller
{
/**
* Instantiate a new controller instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
$this->middleware('allowed');
}
/**
* Handle the incoming request.
*
* @param Request $request
* @return View
*/
public function __invoke(Request $request): View
{
return view('items.import');
}
}

View File

@@ -6,17 +6,20 @@ use App\Application;
use App\Item;
use App\Jobs\ProcessApps;
use App\User;
use Artisan;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
class ItemController extends Controller
{
@@ -104,13 +107,21 @@ class ItemController extends Controller
$new = !(((bool)$item->pinned === true));
$item->pinned = $new;
$item->save();
if ($ajax) {
if (is_numeric($tag) && $tag > 0) {
$item = Item::whereId($tag)->first();
$data['apps'] = $item->children()->pinned()->orderBy('order', 'asc')->get();
} else {
$data['apps'] = Item::pinned()->orderBy('order', 'asc')->get();
$item = Item::whereId($tag)->first();
$data['apps'] = new Collection;
if ((int)$tag === 0) {
$tags = Item::where('type', 1)->pinned()->orderBy('order', 'asc')->get();
$data['apps'] = $data['apps']->merge($tags);
}
$apps = $item->children()->pinned()->orderBy('order', 'asc')->get();
$data['apps'] = $data['apps']->merge($apps);
$data['ajax'] = true;
return view('sortable', $data);
@@ -124,9 +135,10 @@ class ItemController extends Controller
/**
* Display a listing of the resource.
*
* @param Request $request
* @return View
*/
public function index(Request $request)
public function index(Request $request): View
{
$trash = (bool) $request->input('trash');
@@ -182,10 +194,10 @@ class ItemController extends Controller
/**
* @param Request $request
* @param $id
* @return void
* @param null $id
* @return Item
*/
public function storelogic(Request $request, $id = null)
public static function storelogic(Request $request, $id = null): Item
{
$application = Application::single($request->input('appid'));
$validatedData = $request->validate([
@@ -199,12 +211,12 @@ class ItemController extends Controller
'icon' => $path,
]);
} elseif (strpos($request->input('icon'), 'http') === 0) {
$options=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
$options = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
);
$contents = file_get_contents($request->input('icon'), false, stream_context_create($options));
if ($application) {
@@ -213,15 +225,15 @@ class ItemController extends Controller
$file = $request->input('icon');
$path_parts = pathinfo($file);
$icon = md5($contents);
$icon .= '.'.$path_parts['extension'];
$icon .= '.' . $path_parts['extension'];
}
$path = 'icons/'.$icon;
$path = 'icons/' . $icon;
// Private apps could have here duplicated icons folder
if (strpos($path, 'icons/icons/') !== false) {
$path = str_replace('icons/icons/','icons/',$path);
$path = str_replace('icons/icons/', 'icons/', $path);
}
if(! Storage::disk('public')->exists($path)) {
if (!Storage::disk('public')->exists($path)) {
Storage::disk('public')->put($path, $contents);
}
$request->merge([
@@ -266,6 +278,7 @@ class ItemController extends Controller
}
$item->parents()->sync($request->tags);
return $item;
}
/**
@@ -276,7 +289,7 @@ class ItemController extends Controller
*/
public function store(Request $request): RedirectResponse
{
$this->storelogic($request);
self::storelogic($request);
$route = route('dash', []);
@@ -304,7 +317,7 @@ class ItemController extends Controller
*/
public function update(Request $request, int $id): RedirectResponse
{
$this->storelogic($request, $id);
self::storelogic($request, $id);
$route = route('dash', []);
return redirect($route)
@@ -346,8 +359,8 @@ class ItemController extends Controller
{
//
Item::withTrashed()
->where('id', $id)
->restore();
->where('id', $id)
->restore();
$route = route('items.index', []);
@@ -360,6 +373,7 @@ class ItemController extends Controller
*
* @param Request $request
* @return string|null
* @throws GuzzleException
*/
public function appload(Request $request): ?string
{
@@ -380,26 +394,30 @@ class ItemController extends Controller
if ((bool) $app->enhanced === true) {
// if(!isset($app->config)) { // class based config
$output['custom'] = className($appdetails->name).'.config';
$output['custom'] = className($appdetails->name) . '.config';
// }
}
$output['colour'] = ($app->tile_background == 'light') ? '#fafbfc' : '#161b1f';
if(strpos($app->icon, '://') !== false) {
if (strpos($app->icon, '://') !== false) {
$output['iconview'] = $app->icon;
} elseif(strpos($app->icon, 'icons/') !== false) {
} elseif (strpos($app->icon, 'icons/') !== false) {
// Private apps have the icon locally
$output['iconview'] = URL::to('/').'/storage/'.$app->icon;
$output['iconview'] = URL::to('/') . '/storage/' . $app->icon;
$output['icon'] = str_replace('icons/', '', $output['icon']);
} else {
$output['iconview'] = config('app.appsource').'icons/'.$app->icon;
$output['iconview'] = config('app.appsource') . 'icons/' . $app->icon;
}
return json_encode($output);
}
/**
* @param Request $request
* @return void
*/
public function testConfig(Request $request)
{
$data = $request->input('data');
@@ -408,7 +426,10 @@ class ItemController extends Controller
$app = $single->class;
// If password is not resubmitted fill it from the database when in edit mode
if ($data['password'] === null && array_key_exists('id', $data)) {
if (array_key_exists('password', $data) &&
$data['password'] === null &&
array_key_exists('id', $data)
) {
$item = Item::find($data['id']);
if ($item) {
$itemConfig = $item->getConfig();
@@ -421,17 +442,22 @@ class ItemController extends Controller
$app_details->test();
}
public function execute($url, $attrs = [], $overridevars = false)
/**
* @param $url
* @param array $attrs
* @param array|bool $overridevars
* @return ResponseInterface|null
* @throws GuzzleException
*/
public function execute($url, array $attrs = [], $overridevars = false): ?ResponseInterface
{
$res = null;
$vars = ($overridevars !== false) ?
$overridevars : [
'http_errors' => false,
'timeout' => 15,
'connect_timeout' => 15,
'verify' => false,
];
$overridevars : [
'http_errors' => false,
'timeout' => 15,
'connect_timeout' => 15,
'verify' => false,
];
$client = new Client($vars);
@@ -446,10 +472,15 @@ class ItemController extends Controller
Log::debug($e->getMessage());
}
return $res;
return null;
}
public function websitelookup($url)
/**
* @param $url
* @return StreamInterface
* @throws GuzzleException
*/
public function websitelookup($url): StreamInterface
{
$url = base64_decode($url);
$data = $this->execute($url);
@@ -457,6 +488,10 @@ class ItemController extends Controller
return $data->getBody();
}
/**
* @param $id
* @return void
*/
public function getStats($id)
{
$item = Item::find($id);
@@ -469,6 +504,9 @@ class ItemController extends Controller
}
}
/**
* @return \Illuminate\Contracts\Foundation\Application|RedirectResponse|Redirector
*/
public function checkAppList()
{
ProcessApps::dispatch();

View File

@@ -0,0 +1,112 @@
<?php
namespace App\Http\Controllers;
use App\Item;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
class ItemRestController extends Controller
{
public function __construct()
{
parent::__construct();
$this->middleware('allowed');
}
/**
* Display a listing of the resource.
*
* @return Collection
*/
public function index()
{
$columns = [
'title',
'colour',
'url',
'description',
'appid',
'appdescription',
];
return Item::select($columns)
->where('deleted_at', null)
->where('type', '0')
->orderBy('order', 'asc')
->get();
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return object
*/
public function store(Request $request): object
{
$item = ItemController::storelogic($request);
if ($item) {
return (object) ['status' => 'OK'];
}
return (object) ['status' => 'FAILED'];
}
/**
* Display the specified resource.
*
* @param Item $item
* @return Response
*/
public function show(Item $item)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param Item $item
* @return Response
*/
public function edit(Item $item)
{
//
}
/**
* Update the specified resource in storage.
*
* @param Request $request
* @param Item $item
* @return Response
*/
public function update(Request $request, Item $item)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param Item $item
* @return Response
*/
public function destroy(Item $item)
{
//
}
}

View File

@@ -3,10 +3,17 @@
namespace App\Http\Controllers;
use App\Search;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
class SearchController extends Controller
{
/**
* @param Request $request
* @return Application|RedirectResponse|Redirector|mixed|void
*/
public function index(Request $request)
{
$requestprovider = $request->input('provider');

View File

@@ -5,6 +5,8 @@ namespace App\Http\Controllers;
use App\Item;
use App\User;
use DB;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -20,7 +22,7 @@ class TagController extends Controller
/**
* Display a listing of the resource.
*
* @return Response
* @return Application|Factory|View
*/
public function index(Request $request)
{
@@ -38,7 +40,7 @@ class TagController extends Controller
/**
* Show the form for creating a new resource.
*
* @return Response
* @return Application|Factory|View
*/
public function create()
{
@@ -155,6 +157,7 @@ class TagController extends Controller
/**
* Remove the specified resource from storage.
*
* @param Request $request
* @param int $id
* @return RedirectResponse
*/

View File

@@ -4,6 +4,8 @@ namespace App\Http\Middleware;
use App\User;
use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Session;
@@ -13,11 +15,12 @@ class CheckAllowed
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param Request $request
* @param Closure $next
* @return mixed
* @throws AuthenticationException
*/
public function handle($request, Closure $next)
public function handle(Request $request, Closure $next)
{
$route = Route::currentRouteName();
$current_user = User::currentUser();

View File

@@ -3,6 +3,7 @@
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
@@ -10,12 +11,12 @@ class RedirectIfAuthenticated
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @param Request $request
* @param Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
public function handle(Request $request, Closure $next, string $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended();

View File

@@ -2,15 +2,81 @@
namespace App;
use Illuminate\Contracts\Routing\UrlGenerator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use stdClass;
use Symfony\Component\ClassLoader\ClassMapGenerator;
/**
* App\Item
*
* @property int $id
* @property string $title
* @property string|null $colour
* @property string|null $icon
* @property string $url
* @property string|null $description
* @property int $pinned
* @property int $order
* @property \Illuminate\Support\Carbon|null $deleted_at
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property int $type
* @property int $user_id
* @property string|null $class
* @property string|null $appid
* @property string|null $appdescription
* @property-read \Illuminate\Database\Eloquent\Collection|Item[] $children
* @property-read int|null $children_count
* @property-read string $droppable
* @property-read \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\UrlGenerator|mixed|string $link
* @property-read string $link_icon
* @property-read string $link_target
* @property-read string $link_type
* @property-read \Illuminate\Database\Eloquent\Collection|Item[] $parents
* @property-read int|null $parents_count
* @property-read \App\User|null $user
* @method static \Database\Factories\ItemFactory factory(...$parameters)
* @method static Builder|Item newModelQuery()
* @method static Builder|Item newQuery()
* @method static Builder|Item ofType($type)
* @method static \Illuminate\Database\Query\Builder|Item onlyTrashed()
* @method static Builder|Item pinned()
* @method static Builder|Item query()
* @method static Builder|Item whereAppdescription($value)
* @method static Builder|Item whereAppid($value)
* @method static Builder|Item whereClass($value)
* @method static Builder|Item whereColour($value)
* @method static Builder|Item whereCreatedAt($value)
* @method static Builder|Item whereDeletedAt($value)
* @method static Builder|Item whereDescription($value)
* @method static Builder|Item whereIcon($value)
* @method static Builder|Item whereId($value)
* @method static Builder|Item whereOrder($value)
* @method static Builder|Item wherePinned($value)
* @method static Builder|Item whereTitle($value)
* @method static Builder|Item whereType($value)
* @method static Builder|Item whereUpdatedAt($value)
* @method static Builder|Item whereUrl($value)
* @method static Builder|Item whereUserId($value)
* @method static \Illuminate\Database\Query\Builder|Item withTrashed()
* @method static \Illuminate\Database\Query\Builder|Item withoutTrashed()
* @mixin \Eloquent
*/
class Item extends Model
{
use SoftDeletes;
use HasFactory;
/**
* @return void
*/
protected static function boot()
{
parent::boot();
@@ -25,9 +91,20 @@ class Item extends Model
});
}
//
protected $fillable = [
'title', 'url', 'colour', 'icon', 'appdescription', 'description', 'pinned', 'order', 'type', 'class', 'user_id', 'tag_id', 'appid',
'title',
'url',
'colour',
'icon',
'appdescription',
'description',
'pinned',
'order',
'type',
'class',
'user_id',
'tag_id',
'appid',
];
@@ -35,10 +112,10 @@ class Item extends Model
/**
* Scope a query to only include pinned items.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
* @param Builder $query
* @return Builder
*/
public function scopePinned($query)
public function scopePinned(Builder $query): Builder
{
return $query->where('pinned', 1);
}
@@ -74,16 +151,25 @@ class Item extends Model
return $tagdetails;
}
public function parents()
/**
* @return BelongsToMany
*/
public function parents(): BelongsToMany
{
return $this->belongsToMany(\App\Item::class, 'item_tag', 'item_id', 'tag_id');
return $this->belongsToMany(Item::class, 'item_tag', 'item_id', 'tag_id');
}
public function children()
/**
* @return BelongsToMany
*/
public function children(): BelongsToMany
{
return $this->belongsToMany(\App\Item::class, 'item_tag', 'tag_id', 'item_id');
return $this->belongsToMany(Item::class, 'item_tag', 'tag_id', 'item_id');
}
/**
* @return \Illuminate\Contracts\Foundation\Application|UrlGenerator|mixed|string
*/
public function getLinkAttribute()
{
if ((int) $this->type === 1) {
@@ -93,7 +179,10 @@ class Item extends Model
}
}
public function getDroppableAttribute()
/**
* @return string
*/
public function getDroppableAttribute(): string
{
if ((int) $this->type === 1) {
return ' droppable';
@@ -102,7 +191,10 @@ class Item extends Model
}
}
public function getLinkTargetAttribute()
/**
* @return string
*/
public function getLinkTargetAttribute(): string
{
$target = Setting::fetch('window_target');
@@ -113,7 +205,10 @@ class Item extends Model
}
}
public function getLinkIconAttribute()
/**
* @return string
*/
public function getLinkIconAttribute(): string
{
if ((int) $this->type === 1) {
return 'fa-tag';
@@ -122,7 +217,10 @@ class Item extends Model
}
}
public function getLinkTypeAttribute()
/**
* @return string
*/
public function getLinkTypeAttribute(): string
{
if ((int) $this->type === 1) {
return 'tags';
@@ -131,6 +229,10 @@ class Item extends Model
}
}
/**
* @param $class
* @return false|mixed|string
*/
public static function nameFromClass($class)
{
$explode = explode('\\', $class);
@@ -139,6 +241,11 @@ class Item extends Model
return $name;
}
/**
* @param $query
* @param $type
* @return mixed
*/
public function scopeOfType($query, $type)
{
switch ($type) {
@@ -153,7 +260,10 @@ class Item extends Model
return $query->where('type', $typeid);
}
public function enhanced()
/**
* @return bool
*/
public function enhanced(): bool
{
/*if(isset($this->class) && !empty($this->class)) {
$app = new $this->class;
@@ -164,16 +274,24 @@ class Item extends Model
return $this->description !== null;
}
public static function isEnhanced($class)
/**
* @param $class
* @return bool
*/
public static function isEnhanced($class): bool
{
if (!class_exists($class, false) || $class === null || $class === 'null') {
return false;
}
$app = new $class;
return (bool) ($app instanceof \App\EnhancedApps);
return (bool) ($app instanceof EnhancedApps);
}
/**
* @param $class
* @return false|mixed
*/
public static function isSearchProvider($class)
{
if (!class_exists($class, false) || $class === null || $class === 'null') {
@@ -181,10 +299,13 @@ class Item extends Model
}
$app = new $class;
return ((bool) ($app instanceof \App\SearchInterface)) ? $app : false;
return ((bool) ($app instanceof SearchInterface)) ? $app : false;
}
public function enabled()
/**
* @return bool
*/
public function enabled(): bool
{
if ($this->enhanced()) {
$config = $this->getconfig();
@@ -196,12 +317,15 @@ class Item extends Model
return false;
}
/**
* @return mixed|stdClass
*/
public function getconfig()
{
// $explode = explode('\\', $this->class);
if (! isset($this->description) || empty($this->description)) {
$config = new \stdClass;
$config = new stdClass;
// $config->name = end($explode);
$config->enabled = false;
$config->override_url = null;
@@ -224,7 +348,11 @@ class Item extends Model
return $config;
}
public static function applicationDetails($class)
/**
* @param $class
* @return Application|null
*/
public static function applicationDetails($class): ?Application
{
if (! empty($class)) {
$name = self::nameFromClass($class);
@@ -234,13 +362,17 @@ class Item extends Model
}
}
return false;
return null;
}
public static function getApplicationDescription($class)
/**
* @param $class
* @return string
*/
public static function getApplicationDescription($class): string
{
$details = self::applicationDetails($class);
if ($details !== false) {
if ($details !== null) {
return $details->description.' - '.$details->license;
}
@@ -249,9 +381,11 @@ class Item extends Model
/**
* Get the user that owns the item.
*
* @return BelongsTo
*/
public function user()
public function user(): BelongsTo
{
return $this->belongsTo(\App\User::class);
return $this->belongsTo(User::class);
}
}

View File

@@ -2,8 +2,26 @@
namespace App;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\Pivot;
/**
* App\ItemTag
*
* @property int $item_id
* @property int $tag_id
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag query()
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag whereItemId($value)
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag whereTagId($value)
* @method static \Illuminate\Database\Eloquent\Builder|ItemTag whereUpdatedAt($value)
* @mixin \Eloquent
*/
class ItemTag extends Pivot
{
use HasFactory;
}

View File

@@ -5,6 +5,7 @@ namespace App\Jobs;
use App\Application;
use App\Item;
use App\SupportedApps;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -32,6 +33,7 @@ class ProcessApps implements ShouldQueue, ShouldBeUnique
* Execute the job.
*
* @return void
* @throws GuzzleException
*/
public function handle()
{

View File

@@ -3,6 +3,7 @@
namespace App\Jobs;
use App\Application;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -30,6 +31,7 @@ class UpdateApps implements ShouldQueue, ShouldBeUnique
* Execute the job.
*
* @return void
* @throws GuzzleException
*/
public function handle()
{

View File

@@ -7,10 +7,13 @@ use App\Jobs\ProcessApps;
use App\Jobs\UpdateApps;
use App\Setting;
use App\User;
use Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class AppServiceProvider extends ServiceProvider
{
@@ -114,6 +117,10 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
if ($this->app->isLocal()) {
$this->app->register(IdeHelperServiceProvider::class);
}
$this->app->singleton('settings', function () {
return new Setting();
});
@@ -123,13 +130,18 @@ class AppServiceProvider extends ServiceProvider
* Check if database needs an update or do first time database setup
*
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function setupDatabase(): void
{
$db_type = config()->get('database.default');
if ($db_type == 'sqlite' && ! is_file(database_path('app.sqlite'))) {
touch(database_path('app.sqlite'));
if ($db_type == 'sqlite') {
$db_file = database_path(env('DB_DATABASE', 'app.sqlite'));
if (! is_file($db_file)) {
touch($db_file);
}
}
if ($this->needsDBUpdate()) {

View File

@@ -12,9 +12,9 @@ class RouteServiceProvider extends ServiceProvider
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
* REMOVED WITH LARAVEL 8 UPGRADE
*/
protected $namespace = 'App\Http\Controllers';
// protected $namespace = 'App\Http\Controllers';
/**
* Define your route model bindings, pattern filters, etc.

View File

@@ -4,6 +4,7 @@ namespace App;
use Cache;
use Form;
use Illuminate\Support\Collection;
use Yaml;
abstract class Search
@@ -11,9 +12,9 @@ abstract class Search
/**
* List of all search providers
*
* @return \Illuminate\Support\Collection
* @return Collection
*/
public static function providers()
public static function providers(): Collection
{
$providers = self::standardProviders();
$providers = $providers + self::appProviders();
@@ -61,7 +62,7 @@ abstract class Search
*
* @return array
*/
public static function appProviders()
public static function appProviders(): array
{
$providers = [];
$userapps = Item::all();
@@ -121,7 +122,15 @@ abstract class Search
$output .= '<option value="'.$key.'"'.$selected.'>'.$searchprovider['name'].'</option>';
}
$output .= '</select>';
$output .= Form::text('q', null, ['class' => 'homesearch', 'autofocus' => 'autofocus', 'placeholder' => __('app.settings.search').'...']);
$output .= Form::text(
'q',
null,
[
'class' => 'homesearch',
'autofocus' => 'autofocus',
'placeholder' => __('app.settings.search').'...'
]
);
$output .= '<button type="submit">'.ucwords(__('app.settings.search')).'</button>';
$output .= '</div>';
$output .= '</form>';

View File

@@ -3,10 +3,46 @@
namespace App;
use Form;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Http\Request;
use Illuminate\Session\SessionManager;
use Illuminate\Session\Store;
use Illuminate\Support\Facades\Input;
/**
* App\Setting
*
* @mixin Builder
* @property int $id
* @property int $group_id
* @property string $key
* @property string $type
* @property string|null $options
* @property string $label
* @property string|null $value
* @property string $order
* @property int $system
* @property-read mixed $edit_value
* @property-read mixed $list_value
* @property-read \App\SettingGroup|null $group
* @property-read \Illuminate\Database\Eloquent\Collection|\App\User[] $users
* @property-read int|null $users_count
* @method static Builder|Setting newModelQuery()
* @method static Builder|Setting newQuery()
* @method static Builder|Setting query()
* @method static Builder|Setting whereGroupId($value)
* @method static Builder|Setting whereId($value)
* @method static Builder|Setting whereKey($value)
* @method static Builder|Setting whereLabel($value)
* @method static Builder|Setting whereOptions($value)
* @method static Builder|Setting whereOrder($value)
* @method static Builder|Setting whereSystem($value)
* @method static Builder|Setting whereType($value)
* @method static Builder|Setting whereValue($value)
*/
class Setting extends Model
{
/**
@@ -57,7 +93,11 @@ class Setting extends Model
switch ($this->type) {
case 'image':
if (! empty($this->value)) {
$value = '<a href="'.asset('storage/'.$this->value).'" title="'.__('app.settings.view').'" target="_blank">'.__('app.settings.view').'</a>';
$value = '<a href="'.asset('storage/'.$this->value).'" title="'.
__('app.settings.view').
'" target="_blank">'.
__('app.settings.view').
'</a>';
} else {
$value = __('app.options.none');
}
@@ -75,7 +115,9 @@ class Setting extends Model
if ($this->key === 'search_provider') {
$options = Search::providers()->pluck('name', 'id')->toArray();
}
$value = (array_key_exists($this->value, $options)) ? __($options[$this->value]) : __('app.options.none');
$value = (array_key_exists($this->value, $options))
? __($options[$this->value])
: __('app.options.none');
} else {
$value = __('app.options.none');
}
@@ -100,11 +142,24 @@ class Setting extends Model
case 'image':
$value = '';
if (isset($this->value) && ! empty($this->value)) {
$value .= '<a class="setting-view-image" href="'.asset('storage/'.$this->value).'" title="'.__('app.settings.view').'" target="_blank"><img src="'.asset('storage/'.$this->value).'" /></a>';
$value .= '<a class="setting-view-image" href="'.
asset('storage/'.$this->value).
'" title="'.
__('app.settings.view').
'" target="_blank"><img src="'.
asset('storage/'.
$this->value).
'" /></a>';
}
$value .= Form::file('value', ['class' => 'form-control']);
if (isset($this->value) && ! empty($this->value)) {
$value .= '<a class="settinglink" href="'.route('settings.clear', $this->id).'" title="'.__('app.settings.remove').'">'.__('app.settings.reset').'</a>';
$value .= '<a class="settinglink" href="'.
route('settings.clear', $this->id).
'" title="'.
__('app.settings.remove').
'">'.
__('app.settings.reset').
'</a>';
}
break;
@@ -143,7 +198,10 @@ class Setting extends Model
return $value;
}
public function group()
/**
* @return BelongsTo
*/
public function group(): BelongsTo
{
return $this->belongsTo(\App\SettingGroup::class, 'group_id');
}
@@ -153,7 +211,7 @@ class Setting extends Model
*
* @return mixed
*/
public static function fetch($key)
public static function fetch(string $key)
{
$user = self::user();
@@ -220,7 +278,7 @@ class Setting extends Model
*
* @return bool
*/
public static function cached($key)
public static function cached($key): bool
{
return array_key_exists($key, self::$cache);
}
@@ -228,11 +286,14 @@ class Setting extends Model
/**
* The users that belong to the setting.
*/
public function users()
public function users(): BelongsToMany
{
return $this->belongsToMany(\App\User::class)->using(\App\SettingUser::class)->withPivot('uservalue');
}
/**
* @return \Illuminate\Contracts\Foundation\Application|SessionManager|Store|mixed
*/
public static function user()
{
return User::currentUser();

View File

@@ -3,7 +3,24 @@
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* App\SettingGroup
*
* @property int $id
* @property string $title
* @property int $order
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Setting[] $settings
* @property-read int|null $settings_count
* @method static \Illuminate\Database\Eloquent\Builder|SettingGroup newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|SettingGroup newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|SettingGroup query()
* @method static \Illuminate\Database\Eloquent\Builder|SettingGroup whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|SettingGroup whereOrder($value)
* @method static \Illuminate\Database\Eloquent\Builder|SettingGroup whereTitle($value)
* @mixin \Eloquent
*/
class SettingGroup extends Model
{
/**
@@ -20,7 +37,10 @@ class SettingGroup extends Model
*/
public $timestamps = false;
public function settings()
/**
* @return HasMany
*/
public function settings(): HasMany
{
return $this->hasMany(\App\Setting::class, 'group_id');
}

View File

@@ -4,6 +4,20 @@ namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
/**
* App\SettingUser
*
* @property int $setting_id
* @property int $user_id
* @property string|null $uservalue
* @method static \Illuminate\Database\Eloquent\Builder|SettingUser newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|SettingUser newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|SettingUser query()
* @method static \Illuminate\Database\Eloquent\Builder|SettingUser whereSettingId($value)
* @method static \Illuminate\Database\Eloquent\Builder|SettingUser whereUserId($value)
* @method static \Illuminate\Database\Eloquent\Builder|SettingUser whereUservalue($value)
* @mixin \Eloquent
*/
class SettingUser extends Pivot
{
//

View File

@@ -3,7 +3,11 @@
namespace App;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Support\Facades\Log;
use Psr\Http\Message\ResponseInterface;
abstract class SupportedApps
{
@@ -13,7 +17,13 @@ abstract class SupportedApps
protected $error;
public function appTest($url, $attrs = [], $overridevars = false)
/**
* @param $url
* @param array $attrs
* @return object
* @throws GuzzleException
*/
public function appTest($url, array $attrs = []): object
{
if (empty($this->config->url)) {
return (object) [
@@ -52,28 +62,41 @@ abstract class SupportedApps
];
}
public function execute($url, $attrs = [], $overridevars = false, $overridemethod = false)
{
/**
* @param $url
* @param array $attrs
* @param array|bool|null $overridevars
* @param string|bool|null $overridemethod
* @return ResponseInterface|null
* @throws GuzzleException
*/
public function execute(
$url,
array $attrs = [],
$overridevars = null,
$overridemethod = null
): ?ResponseInterface {
$res = null;
$vars = ($overridevars !== false) ?
$overridevars : [
$vars = ($overridevars === null || $overridevars === false) ?
[
'http_errors' => false,
'timeout' => 15,
'connect_timeout' => 15,
];
] : $overridevars;
$client = new Client($vars);
$method = ($overridemethod !== false) ? $overridemethod : $this->method;
$method = ($overridemethod === null || $overridemethod === false) ? $this->method : $overridemethod;
try {
return $client->request($method, $url, $attrs);
} catch (\GuzzleHttp\Exception\ConnectException $e) {
} catch (ConnectException $e) {
Log::error('Connection refused');
Log::debug($e->getMessage());
$this->error = 'Connection refused - '.(string) $e->getMessage();
} catch (\GuzzleHttp\Exception\ServerException $e) {
} catch (ServerException $e) {
Log::debug($e->getMessage());
$this->error = (string) $e->getResponse()->getBody();
}
@@ -82,11 +105,19 @@ abstract class SupportedApps
return $res;
}
/**
* @return void
*/
public function login()
{
}
public function normaliseurl($url, $addslash = true)
/**
* @param string $url
* @param bool $addslash
* @return string
*/
public function normaliseurl(string $url, bool $addslash = true): string
{
$url = rtrim($url, '/');
if ($addslash) {
@@ -96,6 +127,11 @@ abstract class SupportedApps
return $url;
}
/**
* @param $status
* @param $data
* @return false|string
*/
public function getLiveStats($status, $data)
{
$className = get_class($this);
@@ -108,7 +144,11 @@ abstract class SupportedApps
//return
}
public static function getList()
/**
* @return ResponseInterface
* @throws GuzzleException
*/
public static function getList(): ResponseInterface
{
// $list_url = 'https://apps.heimdall.site/list';
$list_url = config('app.appsource').'list.json';
@@ -129,7 +169,7 @@ abstract class SupportedApps
/**
* @param $app
* @return bool|false
* @throws \GuzzleHttp\Exception\GuzzleException
* @throws GuzzleException
*/
public static function getFiles($app): bool
{
@@ -165,6 +205,11 @@ abstract class SupportedApps
return true;
}
/**
* @param $details
* @param $app
* @return mixed
*/
public static function saveApp($details, $app)
{
$app->appid = $details->appid;

View File

@@ -2,15 +2,52 @@
namespace App;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
/**
* App\User
*
* @property int $id
* @property string $username
* @property string $email
* @property string|null $avatar
* @property string|null $password
* @property string|null $autologin
* @property int $public_front
* @property string|null $remember_token
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Item[] $items
* @property-read int|null $items_count
* @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
* @property-read int|null $notifications_count
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Setting[] $settings
* @property-read int|null $settings_count
* @method static \Illuminate\Database\Eloquent\Builder|User newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|User newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|User query()
* @method static \Illuminate\Database\Eloquent\Builder|User whereAutologin($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereAvatar($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereEmail($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder|User wherePassword($value)
* @method static \Illuminate\Database\Eloquent\Builder|User wherePublicFront($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereRememberToken($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder|User whereUsername($value)
* @mixin \Eloquent
*/
class User extends Authenticatable
{
use Notifiable;
use HasFactory;
/**
* The attributes that are mass assignable.
*

View File

@@ -23,10 +23,12 @@
"ext-intl": "*"
},
"require-dev": {
"barryvdh/laravel-ide-helper": "^2.12",
"filp/whoops": "~2.0",
"fzaninotto/faker": "~1.4",
"mockery/mockery": "~1.0",
"phpunit/phpunit": "~9.0",
"squizlabs/php_codesniffer": "3.*",
"symfony/thanks": "^1.0"
},
"autoload": {
@@ -51,6 +53,7 @@
"extra": {
"laravel": {
"dont-discover": [
"barryvdh/laravel-ide-helper"
]
}
},
@@ -64,6 +67,11 @@
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"@php artisan ide-helper:generate",
"@php artisan ide-helper:meta"
]
},
"config": {

766
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "5ec4ff397b3937979b48679da0338808",
"content-hash": "23969e2624fec1e93e31a8fa1e94c471",
"packages": [
{
"name": "brick/math",
@@ -1770,16 +1770,16 @@
},
{
"name": "laravel/tinker",
"version": "v2.7.2",
"version": "v2.7.3",
"source": {
"type": "git",
"url": "https://github.com/laravel/tinker.git",
"reference": "dff39b661e827dae6e092412f976658df82dbac5"
"reference": "5062061b4924af3392225dd482ca7b4d85d8b8ef"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/tinker/zipball/dff39b661e827dae6e092412f976658df82dbac5",
"reference": "dff39b661e827dae6e092412f976658df82dbac5",
"url": "https://api.github.com/repos/laravel/tinker/zipball/5062061b4924af3392225dd482ca7b4d85d8b8ef",
"reference": "5062061b4924af3392225dd482ca7b4d85d8b8ef",
"shasum": ""
},
"require": {
@@ -1832,9 +1832,9 @@
],
"support": {
"issues": "https://github.com/laravel/tinker/issues",
"source": "https://github.com/laravel/tinker/tree/v2.7.2"
"source": "https://github.com/laravel/tinker/tree/v2.7.3"
},
"time": "2022-03-23T12:38:24+00:00"
"time": "2022-11-09T15:11:38+00:00"
},
{
"name": "laravel/ui",
@@ -2513,25 +2513,25 @@
},
{
"name": "nette/schema",
"version": "v1.2.2",
"version": "v1.2.3",
"source": {
"type": "git",
"url": "https://github.com/nette/schema.git",
"reference": "9a39cef03a5b34c7de64f551538cbba05c2be5df"
"reference": "abbdbb70e0245d5f3bf77874cea1dfb0c930d06f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nette/schema/zipball/9a39cef03a5b34c7de64f551538cbba05c2be5df",
"reference": "9a39cef03a5b34c7de64f551538cbba05c2be5df",
"url": "https://api.github.com/repos/nette/schema/zipball/abbdbb70e0245d5f3bf77874cea1dfb0c930d06f",
"reference": "abbdbb70e0245d5f3bf77874cea1dfb0c930d06f",
"shasum": ""
},
"require": {
"nette/utils": "^2.5.7 || ^3.1.5 || ^4.0",
"php": ">=7.1 <8.2"
"php": ">=7.1 <8.3"
},
"require-dev": {
"nette/tester": "^2.3 || ^2.4",
"phpstan/phpstan-nette": "^0.12",
"phpstan/phpstan-nette": "^1.0",
"tracy/tracy": "^2.7"
},
"type": "library",
@@ -2569,9 +2569,9 @@
],
"support": {
"issues": "https://github.com/nette/schema/issues",
"source": "https://github.com/nette/schema/tree/v1.2.2"
"source": "https://github.com/nette/schema/tree/v1.2.3"
},
"time": "2021-10-15T11:40:02+00:00"
"time": "2022-10-13T01:24:26+00:00"
},
{
"name": "nette/utils",
@@ -7100,6 +7100,562 @@
}
],
"packages-dev": [
{
"name": "barryvdh/laravel-ide-helper",
"version": "v2.12.3",
"source": {
"type": "git",
"url": "https://github.com/barryvdh/laravel-ide-helper.git",
"reference": "3ba1e2573b38f72107b8aacc4ee177fcab30a550"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/barryvdh/laravel-ide-helper/zipball/3ba1e2573b38f72107b8aacc4ee177fcab30a550",
"reference": "3ba1e2573b38f72107b8aacc4ee177fcab30a550",
"shasum": ""
},
"require": {
"barryvdh/reflection-docblock": "^2.0.6",
"composer/pcre": "^1 || ^2 || ^3",
"doctrine/dbal": "^2.6 || ^3",
"ext-json": "*",
"illuminate/console": "^8 || ^9",
"illuminate/filesystem": "^8 || ^9",
"illuminate/support": "^8 || ^9",
"nikic/php-parser": "^4.7",
"php": "^7.3 || ^8.0",
"phpdocumentor/type-resolver": "^1.1.0"
},
"require-dev": {
"ext-pdo_sqlite": "*",
"friendsofphp/php-cs-fixer": "^2",
"illuminate/config": "^8 || ^9",
"illuminate/view": "^8 || ^9",
"mockery/mockery": "^1.4",
"orchestra/testbench": "^6 || ^7",
"phpunit/phpunit": "^8.5 || ^9",
"spatie/phpunit-snapshot-assertions": "^3 || ^4",
"vimeo/psalm": "^3.12"
},
"suggest": {
"illuminate/events": "Required for automatic helper generation (^6|^7|^8|^9)."
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.12-dev"
},
"laravel": {
"providers": [
"Barryvdh\\LaravelIdeHelper\\IdeHelperServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Barryvdh\\LaravelIdeHelper\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Barry vd. Heuvel",
"email": "barryvdh@gmail.com"
}
],
"description": "Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.",
"keywords": [
"autocomplete",
"codeintel",
"helper",
"ide",
"laravel",
"netbeans",
"phpdoc",
"phpstorm",
"sublime"
],
"support": {
"issues": "https://github.com/barryvdh/laravel-ide-helper/issues",
"source": "https://github.com/barryvdh/laravel-ide-helper/tree/v2.12.3"
},
"funding": [
{
"url": "https://fruitcake.nl",
"type": "custom"
},
{
"url": "https://github.com/barryvdh",
"type": "github"
}
],
"time": "2022-03-06T14:33:42+00:00"
},
{
"name": "barryvdh/reflection-docblock",
"version": "v2.1.0",
"source": {
"type": "git",
"url": "https://github.com/barryvdh/ReflectionDocBlock.git",
"reference": "bf44b757feb8ba1734659029357646466ded673e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/barryvdh/ReflectionDocBlock/zipball/bf44b757feb8ba1734659029357646466ded673e",
"reference": "bf44b757feb8ba1734659029357646466ded673e",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "^8.5.14|^9"
},
"suggest": {
"dflydev/markdown": "~1.0",
"erusev/parsedown": "~1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"psr-0": {
"Barryvdh": [
"src/"
]
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mike van Riel",
"email": "mike.vanriel@naenius.com"
}
],
"support": {
"source": "https://github.com/barryvdh/ReflectionDocBlock/tree/v2.1.0"
},
"time": "2022-10-31T15:35:43+00:00"
},
{
"name": "composer/pcre",
"version": "3.1.0",
"source": {
"type": "git",
"url": "https://github.com/composer/pcre.git",
"reference": "4bff79ddd77851fe3cdd11616ed3f92841ba5bd2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/pcre/zipball/4bff79ddd77851fe3cdd11616ed3f92841ba5bd2",
"reference": "4bff79ddd77851fe3cdd11616ed3f92841ba5bd2",
"shasum": ""
},
"require": {
"php": "^7.4 || ^8.0"
},
"require-dev": {
"phpstan/phpstan": "^1.3",
"phpstan/phpstan-strict-rules": "^1.1",
"symfony/phpunit-bridge": "^5"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"autoload": {
"psr-4": {
"Composer\\Pcre\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"description": "PCRE wrapping library that offers type-safe preg_* replacements.",
"keywords": [
"PCRE",
"preg",
"regex",
"regular expression"
],
"support": {
"issues": "https://github.com/composer/pcre/issues",
"source": "https://github.com/composer/pcre/tree/3.1.0"
},
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://github.com/composer",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/composer/composer",
"type": "tidelift"
}
],
"time": "2022-11-17T09:50:14+00:00"
},
{
"name": "doctrine/cache",
"version": "2.2.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/cache.git",
"reference": "1ca8f21980e770095a31456042471a57bc4c68fb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/cache/zipball/1ca8f21980e770095a31456042471a57bc4c68fb",
"reference": "1ca8f21980e770095a31456042471a57bc4c68fb",
"shasum": ""
},
"require": {
"php": "~7.1 || ^8.0"
},
"conflict": {
"doctrine/common": ">2.2,<2.4"
},
"require-dev": {
"cache/integration-tests": "dev-master",
"doctrine/coding-standard": "^9",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"psr/cache": "^1.0 || ^2.0 || ^3.0",
"symfony/cache": "^4.4 || ^5.4 || ^6",
"symfony/var-exporter": "^4.4 || ^5.4 || ^6"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Common\\Cache\\": "lib/Doctrine/Common/Cache"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"description": "PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.",
"homepage": "https://www.doctrine-project.org/projects/cache.html",
"keywords": [
"abstraction",
"apcu",
"cache",
"caching",
"couchdb",
"memcached",
"php",
"redis",
"xcache"
],
"support": {
"issues": "https://github.com/doctrine/cache/issues",
"source": "https://github.com/doctrine/cache/tree/2.2.0"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fcache",
"type": "tidelift"
}
],
"time": "2022-05-20T20:07:39+00:00"
},
{
"name": "doctrine/dbal",
"version": "3.5.1",
"source": {
"type": "git",
"url": "https://github.com/doctrine/dbal.git",
"reference": "f38ee8aaca2d58ee88653cb34a6a3880c23f38a5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/dbal/zipball/f38ee8aaca2d58ee88653cb34a6a3880c23f38a5",
"reference": "f38ee8aaca2d58ee88653cb34a6a3880c23f38a5",
"shasum": ""
},
"require": {
"composer-runtime-api": "^2",
"doctrine/cache": "^1.11|^2.0",
"doctrine/deprecations": "^0.5.3|^1",
"doctrine/event-manager": "^1|^2",
"php": "^7.4 || ^8.0",
"psr/cache": "^1|^2|^3",
"psr/log": "^1|^2|^3"
},
"require-dev": {
"doctrine/coding-standard": "10.0.0",
"jetbrains/phpstorm-stubs": "2022.2",
"phpstan/phpstan": "1.8.10",
"phpstan/phpstan-strict-rules": "^1.4",
"phpunit/phpunit": "9.5.25",
"psalm/plugin-phpunit": "0.17.0",
"squizlabs/php_codesniffer": "3.7.1",
"symfony/cache": "^5.4|^6.0",
"symfony/console": "^4.4|^5.4|^6.0",
"vimeo/psalm": "4.29.0"
},
"suggest": {
"symfony/console": "For helpful console commands such as SQL execution and import of files."
},
"bin": [
"bin/doctrine-dbal"
],
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\DBAL\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
}
],
"description": "Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.",
"homepage": "https://www.doctrine-project.org/projects/dbal.html",
"keywords": [
"abstraction",
"database",
"db2",
"dbal",
"mariadb",
"mssql",
"mysql",
"oci8",
"oracle",
"pdo",
"pgsql",
"postgresql",
"queryobject",
"sasql",
"sql",
"sqlite",
"sqlserver",
"sqlsrv"
],
"support": {
"issues": "https://github.com/doctrine/dbal/issues",
"source": "https://github.com/doctrine/dbal/tree/3.5.1"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdbal",
"type": "tidelift"
}
],
"time": "2022-10-24T07:26:18+00:00"
},
{
"name": "doctrine/deprecations",
"version": "v1.0.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/deprecations.git",
"reference": "0e2a4f1f8cdfc7a92ec3b01c9334898c806b30de"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/deprecations/zipball/0e2a4f1f8cdfc7a92ec3b01c9334898c806b30de",
"reference": "0e2a4f1f8cdfc7a92ec3b01c9334898c806b30de",
"shasum": ""
},
"require": {
"php": "^7.1|^8.0"
},
"require-dev": {
"doctrine/coding-standard": "^9",
"phpunit/phpunit": "^7.5|^8.5|^9.5",
"psr/log": "^1|^2|^3"
},
"suggest": {
"psr/log": "Allows logging deprecations via PSR-3 logger implementation"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Deprecations\\": "lib/Doctrine/Deprecations"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.",
"homepage": "https://www.doctrine-project.org/",
"support": {
"issues": "https://github.com/doctrine/deprecations/issues",
"source": "https://github.com/doctrine/deprecations/tree/v1.0.0"
},
"time": "2022-05-02T15:47:09+00:00"
},
{
"name": "doctrine/event-manager",
"version": "1.2.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/event-manager.git",
"reference": "95aa4cb529f1e96576f3fda9f5705ada4056a520"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/event-manager/zipball/95aa4cb529f1e96576f3fda9f5705ada4056a520",
"reference": "95aa4cb529f1e96576f3fda9f5705ada4056a520",
"shasum": ""
},
"require": {
"doctrine/deprecations": "^0.5.3 || ^1",
"php": "^7.1 || ^8.0"
},
"conflict": {
"doctrine/common": "<2.9"
},
"require-dev": {
"doctrine/coding-standard": "^9 || ^10",
"phpstan/phpstan": "~1.4.10 || ^1.8.8",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"vimeo/psalm": "^4.24"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Common\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
},
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com"
}
],
"description": "The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.",
"homepage": "https://www.doctrine-project.org/projects/event-manager.html",
"keywords": [
"event",
"event dispatcher",
"event manager",
"event system",
"events"
],
"support": {
"issues": "https://github.com/doctrine/event-manager/issues",
"source": "https://github.com/doctrine/event-manager/tree/1.2.0"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fevent-manager",
"type": "tidelift"
}
],
"time": "2022-10-12T20:51:15+00:00"
},
{
"name": "doctrine/instantiator",
"version": "1.4.1",
@@ -7519,17 +8075,125 @@
"time": "2022-02-21T01:04:05+00:00"
},
{
"name": "phpunit/php-code-coverage",
"version": "9.2.18",
"name": "phpdocumentor/reflection-common",
"version": "2.2.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "12fddc491826940cf9b7e88ad9664cf51f0f6d0a"
"url": "https://github.com/phpDocumentor/ReflectionCommon.git",
"reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/12fddc491826940cf9b7e88ad9664cf51f0f6d0a",
"reference": "12fddc491826940cf9b7e88ad9664cf51f0f6d0a",
"url": "https://api.github.com/repos/phpDocumentor/ReflectionCommon/zipball/1d01c49d4ed62f25aa84a747ad35d5a16924662b",
"reference": "1d01c49d4ed62f25aa84a747ad35d5a16924662b",
"shasum": ""
},
"require": {
"php": "^7.2 || ^8.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-2.x": "2.x-dev"
}
},
"autoload": {
"psr-4": {
"phpDocumentor\\Reflection\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jaap van Otterdijk",
"email": "opensource@ijaap.nl"
}
],
"description": "Common reflection classes used by phpdocumentor to reflect the code structure",
"homepage": "http://www.phpdoc.org",
"keywords": [
"FQSEN",
"phpDocumentor",
"phpdoc",
"reflection",
"static analysis"
],
"support": {
"issues": "https://github.com/phpDocumentor/ReflectionCommon/issues",
"source": "https://github.com/phpDocumentor/ReflectionCommon/tree/2.x"
},
"time": "2020-06-27T09:03:43+00:00"
},
{
"name": "phpdocumentor/type-resolver",
"version": "1.6.2",
"source": {
"type": "git",
"url": "https://github.com/phpDocumentor/TypeResolver.git",
"reference": "48f445a408c131e38cab1c235aa6d2bb7a0bb20d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpDocumentor/TypeResolver/zipball/48f445a408c131e38cab1c235aa6d2bb7a0bb20d",
"reference": "48f445a408c131e38cab1c235aa6d2bb7a0bb20d",
"shasum": ""
},
"require": {
"php": "^7.4 || ^8.0",
"phpdocumentor/reflection-common": "^2.0"
},
"require-dev": {
"ext-tokenizer": "*",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan": "^1.8",
"phpstan/phpstan-phpunit": "^1.1",
"phpunit/phpunit": "^9.5",
"rector/rector": "^0.13.9",
"vimeo/psalm": "^4.25"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-1.x": "1.x-dev"
}
},
"autoload": {
"psr-4": {
"phpDocumentor\\Reflection\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Mike van Riel",
"email": "me@mikevanriel.com"
}
],
"description": "A PSR-5 based resolver of Class names, Types and Structural Element Names",
"support": {
"issues": "https://github.com/phpDocumentor/TypeResolver/issues",
"source": "https://github.com/phpDocumentor/TypeResolver/tree/1.6.2"
},
"time": "2022-10-14T12:47:21+00:00"
},
{
"name": "phpunit/php-code-coverage",
"version": "9.2.19",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "c77b56b63e3d2031bd8997fcec43c1925ae46559"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/c77b56b63e3d2031bd8997fcec43c1925ae46559",
"reference": "c77b56b63e3d2031bd8997fcec43c1925ae46559",
"shasum": ""
},
"require": {
@@ -7585,7 +8249,7 @@
],
"support": {
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.18"
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/9.2.19"
},
"funding": [
{
@@ -7593,7 +8257,7 @@
"type": "github"
}
],
"time": "2022-10-27T13:35:33+00:00"
"time": "2022-11-18T07:47:47+00:00"
},
{
"name": "phpunit/php-file-iterator",
@@ -8902,6 +9566,62 @@
],
"time": "2020-09-28T06:39:44+00:00"
},
{
"name": "squizlabs/php_codesniffer",
"version": "3.7.1",
"source": {
"type": "git",
"url": "https://github.com/squizlabs/PHP_CodeSniffer.git",
"reference": "1359e176e9307e906dc3d890bcc9603ff6d90619"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/squizlabs/PHP_CodeSniffer/zipball/1359e176e9307e906dc3d890bcc9603ff6d90619",
"reference": "1359e176e9307e906dc3d890bcc9603ff6d90619",
"shasum": ""
},
"require": {
"ext-simplexml": "*",
"ext-tokenizer": "*",
"ext-xmlwriter": "*",
"php": ">=5.4.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0"
},
"bin": [
"bin/phpcs",
"bin/phpcbf"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.x-dev"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Greg Sherwood",
"role": "lead"
}
],
"description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.",
"homepage": "https://github.com/squizlabs/PHP_CodeSniffer",
"keywords": [
"phpcs",
"standards"
],
"support": {
"issues": "https://github.com/squizlabs/PHP_CodeSniffer/issues",
"source": "https://github.com/squizlabs/PHP_CodeSniffer",
"wiki": "https://github.com/squizlabs/PHP_CodeSniffer/wiki"
},
"time": "2022-06-18T07:21:10+00:00"
},
{
"name": "symfony/thanks",
"version": "v1.2.10",

View File

@@ -14,7 +14,7 @@ return [
*/
'name' => env('APP_NAME', 'Heimdall'),
'version' => '2.5.0',
'version' => '2.5.4',
/*
|--------------------------------------------------------------------------

View File

@@ -17,7 +17,7 @@ return [
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
'default' => env('LOG_CHANNEL', 'daily'),
/*
|--------------------------------------------------------------------------

View File

@@ -0,0 +1,29 @@
<?php
namespace Database\Factories;
use App\Item;
use Illuminate\Database\Eloquent\Factories\Factory;
class ItemFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Item::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition(): array
{
return [
'title' => $this->faker->unique()->text(),
'url' => $this->faker->unique()->url(),
];
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Database\Factories;
use App\Item;
use App\ItemTag;
use Illuminate\Database\Eloquent\Factories\Factory;
class ItemTagFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = ItemTag::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition(): array
{
return [];
}
}

View File

@@ -2,11 +2,19 @@
namespace Database\Factories;
use App\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
@@ -15,10 +23,10 @@ class UserFactory extends Factory
public function definition()
{
return [
'name' => $this->faker->name(),
'username' => $this->faker->name(),
'email' => $this->faker->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'public_front' => 1,
'remember_token' => Str::random(10),
];
}

1325
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -7,10 +7,16 @@
"watch-poll": "mix watch -- --watch-options-poll=1000",
"hot": "mix watch --hot",
"prod": "npm run production",
"production": "mix --production"
"production": "mix --production",
"lint": "eslint 'resources/assets/js/*'"
},
"devDependencies": {
"bootstrap-sass": "^3.4.3",
"eslint": "^8.28.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-prettier": "^4.2.1",
"jquery": "^3.6.1",
"laravel-mix": "^6.0.49",
"sass": "^1.56.1",

23
phpcs.xml Normal file
View File

@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
<description>The coding standard for our project.</description>
<rule ref="PSR2"/>
<file>app</file>
<file>bootstrap</file>
<file>config</file>
<file>database</file>
<file>resources</file>
<file>routes</file>
<file>tests</file>
<exclude-pattern>bootstrap/cache/*</exclude-pattern>
<exclude-pattern>bootstrap/autoload.php</exclude-pattern>
<exclude-pattern>*/migrations/*</exclude-pattern>
<exclude-pattern>*/seeds/*</exclude-pattern>
<exclude-pattern>*.blade.php</exclude-pattern>
<exclude-pattern>*.js</exclude-pattern>
<!-- Show progression -->
<arg value="p"/>
</ruleset>

2
public/css/app.css vendored

File diff suppressed because one or more lines are too long

2
public/js/app.js vendored

File diff suppressed because one or more lines are too long

View File

@@ -483,10 +483,14 @@ var icons = {
"arrow-rotate-right": [512, 512, [8635, "arrow-right-rotate", "arrow-rotate-forward", "redo"], "f01e", "M496 48V192c0 17.69-14.31 32-32 32H320c-17.69 0-32-14.31-32-32s14.31-32 32-32h63.39c-29.97-39.7-77.25-63.78-127.6-63.78C167.7 96.22 96 167.9 96 256s71.69 159.8 159.8 159.8c34.88 0 68.03-11.03 95.88-31.94c14.22-10.53 34.22-7.75 44.81 6.375c10.59 14.16 7.75 34.22-6.375 44.81c-39.03 29.28-85.36 44.86-134.2 44.86C132.5 479.9 32 379.4 32 256s100.5-223.9 223.9-223.9c69.15 0 134 32.47 176.1 86.12V48c0-17.69 14.31-32 32-32S496 30.31 496 48z"],
"ban": [512, 512, [], "f05e", "M256 8C119.034 8 8 119.033 8 256s111.034 248 248 248 248-111.034 248-248S392.967 8 256 8zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676zM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676z"],
"check": [512, 512, [], "f00c", "M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"],
"circle-check": [512, 512, [61533, "check-circle"], "f058", ["M0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256zM371.8 211.8C382.7 200.9 382.7 183.1 371.8 172.2C360.9 161.3 343.1 161.3 332.2 172.2L224 280.4L179.8 236.2C168.9 225.3 151.1 225.3 140.2 236.2C129.3 247.1 129.3 264.9 140.2 275.8L204.2 339.8C215.1 350.7 232.9 350.7 243.8 339.8L371.8 211.8z", "M371.8 172.2C382.7 183.1 382.7 200.9 371.8 211.8L243.8 339.8C232.9 350.7 215.1 350.7 204.2 339.8L140.2 275.8C129.3 264.9 129.3 247.1 140.2 236.2C151.1 225.3 168.9 225.3 179.8 236.2L224 280.4L332.2 172.2C343.1 161.3 360.9 161.3 371.8 172.2V172.2z"]],
"circle-xmark": [512, 512, [61532, "times-circle", "xmark-circle"], "f057", ["M0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256zM175 208.1L222.1 255.1L175 303C165.7 312.4 165.7 327.6 175 336.1C184.4 346.3 199.6 346.3 208.1 336.1L255.1 289.9L303 336.1C312.4 346.3 327.6 346.3 336.1 336.1C346.3 327.6 346.3 312.4 336.1 303L289.9 255.1L336.1 208.1C346.3 199.6 346.3 184.4 336.1 175C327.6 165.7 312.4 165.7 303 175L255.1 222.1L208.1 175C199.6 165.7 184.4 165.7 175 175C165.7 184.4 165.7 199.6 175 208.1V208.1z", "M255.1 222.1L303 175C312.4 165.7 327.6 165.7 336.1 175C346.3 184.4 346.3 199.6 336.1 208.1L289.9 255.1L336.1 303C346.3 312.4 346.3 327.6 336.1 336.1C327.6 346.3 312.4 346.3 303 336.1L255.1 289.9L208.1 336.1C199.6 346.3 184.4 346.3 175 336.1C165.7 327.6 165.7 312.4 175 303L222.1 255.1L175 208.1C165.7 199.6 165.7 184.4 175 175C184.4 165.7 199.6 165.7 208.1 175L255.1 222.1z"]],
"cloud-download": [640, 512, [], "f0ed", "M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zm-139.9 93L305 412.3c-9.4 9.4-24.6 9.4-33.9 0l-92.7-92.7c-9.4-9.4-9.4-24.6 0-33.9l10.8-10.8c9.6-9.6 25.2-9.3 34.5.5l32.4 34.5V184c0-13.3 10.7-24 24-24h16c13.3 0 24 10.7 24 24v125.9l32.4-34.5c9.3-9.9 24.9-10.1 34.5-.5l10.8 10.8c9.2 9.3 9.2 24.5-.1 33.9z"],
"cogs": [640, 512, [], "f085", "M512.1 191l-8.2 14.3c-3 5.3-9.4 7.5-15.1 5.4-11.8-4.4-22.6-10.7-32.1-18.6-4.6-3.8-5.8-10.5-2.8-15.7l8.2-14.3c-6.9-8-12.3-17.3-15.9-27.4h-16.5c-6 0-11.2-4.3-12.2-10.3-2-12-2.1-24.6 0-37.1 1-6 6.2-10.4 12.2-10.4h16.5c3.6-10.1 9-19.4 15.9-27.4l-8.2-14.3c-3-5.2-1.9-11.9 2.8-15.7 9.5-7.9 20.4-14.2 32.1-18.6 5.7-2.1 12.1.1 15.1 5.4l8.2 14.3c10.5-1.9 21.2-1.9 31.7 0L552 6.3c3-5.3 9.4-7.5 15.1-5.4 11.8 4.4 22.6 10.7 32.1 18.6 4.6 3.8 5.8 10.5 2.8 15.7l-8.2 14.3c6.9 8 12.3 17.3 15.9 27.4h16.5c6 0 11.2 4.3 12.2 10.3 2 12 2.1 24.6 0 37.1-1 6-6.2 10.4-12.2 10.4h-16.5c-3.6 10.1-9 19.4-15.9 27.4l8.2 14.3c3 5.2 1.9 11.9-2.8 15.7-9.5 7.9-20.4 14.2-32.1 18.6-5.7 2.1-12.1-.1-15.1-5.4l-8.2-14.3c-10.4 1.9-21.2 1.9-31.7 0zm-10.5-58.8c38.5 29.6 82.4-14.3 52.8-52.8-38.5-29.7-82.4 14.3-52.8 52.8zM386.3 286.1l33.7 16.8c10.1 5.8 14.5 18.1 10.5 29.1-8.9 24.2-26.4 46.4-42.6 65.8-7.4 8.9-20.2 11.1-30.3 5.3l-29.1-16.8c-16 13.7-34.6 24.6-54.9 31.7v33.6c0 11.6-8.3 21.6-19.7 23.6-24.6 4.2-50.4 4.4-75.9 0-11.5-2-20-11.9-20-23.6V418c-20.3-7.2-38.9-18-54.9-31.7L74 403c-10 5.8-22.9 3.6-30.3-5.3-16.2-19.4-33.3-41.6-42.2-65.7-4-10.9.4-23.2 10.5-29.1l33.3-16.8c-3.9-20.9-3.9-42.4 0-63.4L12 205.8c-10.1-5.8-14.6-18.1-10.5-29 8.9-24.2 26-46.4 42.2-65.8 7.4-8.9 20.2-11.1 30.3-5.3l29.1 16.8c16-13.7 34.6-24.6 54.9-31.7V57.1c0-11.5 8.2-21.5 19.6-23.5 24.6-4.2 50.5-4.4 76-.1 11.5 2 20 11.9 20 23.6v33.6c20.3 7.2 38.9 18 54.9 31.7l29.1-16.8c10-5.8 22.9-3.6 30.3 5.3 16.2 19.4 33.2 41.6 42.1 65.8 4 10.9.1 23.2-10 29.1l-33.7 16.8c3.9 21 3.9 42.5 0 63.5zm-117.6 21.1c59.2-77-28.7-164.9-105.7-105.7-59.2 77 28.7 164.9 105.7 105.7zm243.4 182.7l-8.2 14.3c-3 5.3-9.4 7.5-15.1 5.4-11.8-4.4-22.6-10.7-32.1-18.6-4.6-3.8-5.8-10.5-2.8-15.7l8.2-14.3c-6.9-8-12.3-17.3-15.9-27.4h-16.5c-6 0-11.2-4.3-12.2-10.3-2-12-2.1-24.6 0-37.1 1-6 6.2-10.4 12.2-10.4h16.5c3.6-10.1 9-19.4 15.9-27.4l-8.2-14.3c-3-5.2-1.9-11.9 2.8-15.7 9.5-7.9 20.4-14.2 32.1-18.6 5.7-2.1 12.1.1 15.1 5.4l8.2 14.3c10.5-1.9 21.2-1.9 31.7 0l8.2-14.3c3-5.3 9.4-7.5 15.1-5.4 11.8 4.4 22.6 10.7 32.1 18.6 4.6 3.8 5.8 10.5 2.8 15.7l-8.2 14.3c6.9 8 12.3 17.3 15.9 27.4h16.5c6 0 11.2 4.3 12.2 10.3 2 12 2.1 24.6 0 37.1-1 6-6.2 10.4-12.2 10.4h-16.5c-3.6 10.1-9 19.4-15.9 27.4l8.2 14.3c3 5.2 1.9 11.9-2.8 15.7-9.5 7.9-20.4 14.2-32.1 18.6-5.7 2.1-12.1-.1-15.1-5.4l-8.2-14.3c-10.4 1.9-21.2 1.9-31.7 0zM501.6 431c38.5 29.6 82.4-14.3 52.8-52.8-38.5-29.6-82.4 14.3-52.8 52.8z"],
"edit": [576, 512, [], "f044", "M402.6 83.2l90.2 90.2c3.8 3.8 3.8 10 0 13.8L274.4 405.6l-92.8 10.3c-12.4 1.4-22.9-9.1-21.5-21.5l10.3-92.8L388.8 83.2c3.8-3.8 10-3.8 13.8 0zm162-22.9l-48.8-48.8c-15.2-15.2-39.9-15.2-55.2 0l-35.4 35.4c-3.8 3.8-3.8 10 0 13.8l90.2 90.2c3.8 3.8 10 3.8 13.8 0l35.4-35.4c15.2-15.3 15.2-40 0-55.2zM384 346.2V448H64V128h229.8c3.2 0 6.2-1.3 8.5-3.5l40-40c7.6-7.6 2.2-20.5-8.5-20.5H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V306.2c0-10.7-12.9-16-20.5-8.5l-40 40c-2.2 2.3-3.5 5.3-3.5 8.5z"],
"exchange": [512, 512, [], "f0ec", "M0 168v-16c0-13.255 10.745-24 24-24h381.97l-30.467-27.728c-9.815-9.289-10.03-24.846-.474-34.402l10.84-10.84c9.373-9.373 24.568-9.373 33.941 0l82.817 82.343c12.497 12.497 12.497 32.758 0 45.255l-82.817 82.343c-9.373 9.373-24.569 9.373-33.941 0l-10.84-10.84c-9.556-9.556-9.341-25.114.474-34.402L405.97 192H24c-13.255 0-24-10.745-24-24zm488 152H106.03l30.467-27.728c9.815-9.289 10.03-24.846.474-34.402l-10.84-10.84c-9.373-9.373-24.568-9.373-33.941 0L9.373 329.373c-12.497 12.497-12.497 32.758 0 45.255l82.817 82.343c9.373 9.373 24.569 9.373 33.941 0l10.84-10.84c9.556-9.556 9.341-25.113-.474-34.402L106.03 384H488c13.255 0 24-10.745 24-24v-16c0-13.255-10.745-24-24-24z"],
"file-arrow-down": [384, 512, ["file-download"], "f56d", ["M256 128V0H48C21.49 0 0 21.49 0 48v416C0 490.5 21.49 512 48 512h288c26.51 0 48-21.49 48-48V128H256zM288.1 360.1l-80 80c-9.375 9.375-24.56 9.375-33.94 0l-80-80c-9.375-9.375-9.375-24.56 0-33.94C99.72 322.3 105.8 320 112 320s12.28 2.344 16.97 7.031L168 366.1V248C168 234.8 178.8 224 192 224s24 10.75 24 24v118.1l39.03-39.03c9.375-9.375 24.56-9.375 33.94 0S298.3 351.6 288.1 360.1z", "M256 0v128h128L256 0zM255 327L216 366.1V248C216 234.8 205.3 224 192 224S168 234.8 168 248v118.1l-39.03-39.03C124.3 322.3 118.2 320 112 320s-12.28 2.344-16.97 7.031c-9.375 9.375-9.375 24.56 0 33.94l80 80c9.375 9.375 24.56 9.375 33.94 0l80-80c9.375-9.375 9.375-24.56 0-33.94S264.4 317.7 255 327z"]],
"file-arrow-up": [384, 512, ["file-upload"], "f574", ["M256 128V0H48C21.49 0 0 21.49 0 48v416C0 490.5 21.49 512 48 512h288c26.51 0 48-21.49 48-48V128H256zM288.1 344.1C284.3 349.7 278.2 352 272 352s-12.28-2.344-16.97-7.031L216 305.9V424c0 13.25-10.75 24-24 24s-24-10.75-24-24V305.9l-39.03 39.03c-9.375 9.375-24.56 9.375-33.94 0s-9.375-24.56 0-33.94l80-80c9.375-9.375 24.56-9.375 33.94 0l80 80C298.3 320.4 298.3 335.6 288.1 344.1z", "M256 0v128h128L256 0zM208.1 231c-9.375-9.375-24.56-9.375-33.94 0l-80 80c-9.375 9.375-9.375 24.56 0 33.94s24.56 9.375 33.94 0L168 305.9V424C168 437.3 178.8 448 192 448s24-10.75 24-24V305.9l39.03 39.03C259.7 349.7 265.8 352 272 352s12.28-2.344 16.97-7.031c9.375-9.375 9.375-24.56 0-33.94L208.1 231z"]],
"list": [512, 512, [], "f03a", "M128 116V76c0-8.837 7.163-16 16-16h352c8.837 0 16 7.163 16 16v40c0 8.837-7.163 16-16 16H144c-8.837 0-16-7.163-16-16zm16 176h352c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H144c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h352c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H144c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zM16 144h64c8.837 0 16-7.163 16-16V64c0-8.837-7.163-16-16-16H16C7.163 48 0 55.163 0 64v64c0 8.837 7.163 16 16 16zm0 160h64c8.837 0 16-7.163 16-16v-64c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v64c0 8.837 7.163 16 16 16zm0 160h64c8.837 0 16-7.163 16-16v-64c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v64c0 8.837 7.163 16 16 16z"],
"pencil": [512, 512, [], "f040", "M497.9 142.1l-46.1 46.1c-4.7 4.7-12.3 4.7-17 0l-111-111c-4.7-4.7-4.7-12.3 0-17l46.1-46.1c18.7-18.7 49.1-18.7 67.9 0l60.1 60.1c18.8 18.7 18.8 49.1 0 67.9zM284.2 99.8L21.6 362.4.4 483.9c-2.9 16.4 11.4 30.6 27.8 27.8l121.5-21.3 262.6-262.6c4.7-4.7 4.7-12.3 0-17l-111-111c-4.8-4.7-12.4-4.7-17.1 0zM88 424h48v36.3l-64.5 11.3-31.1-31.1L51.7 376H88v48z"],
"plus": [448, 512, [], "f067", "M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z"],

View File

@@ -1,4 +1,4 @@
{
"/css/app.css": "/css/app.css?id=9a25947db63214edd4e6f459200dfa62",
"/js/app.js": "/js/app.js?id=6d4db31cf508e4b9c767ec2710c256ff"
"/css/app.css": "/css/app.css?id=910562b0b11f9731ff1cdded5e57f7b5",
"/js/app.js": "/js/app.js?id=86f896ef6c2066036a4e2b946e07750d"
}

View File

@@ -83,27 +83,27 @@ When you are finished, create a pull request.
Currently added languages are
- English
- Breton
- Chinese
- Danish
- German
- Greek
- Spanish
- Dutch
- English
- Finnish
- French
- German
- Greek
- Hungarian
- Italian
- Korean
- Lombard
- Dutch
- Norwegian
- Polish
- Portuguese
- Russian
- Slovenian
- Spanish
- Swedish
- Turkish
- Chinese
## Web Server Configuration

View File

@@ -1,120 +1,40 @@
$.when( $.ready ).then(function() {
$.when($.ready).then(() => {
const base = (document.querySelector("base") || {}).href;
var base = (document.querySelector('base') || {}).href;
const itemID = $("form[data-item-id]").data("item-id");
const fakePassword = "*****";
var itemID = $('form[data-item-id]').data('item-id');
var fakePassword = '*****';
// If in edit mode and password field is present, fill it with stars
if (itemID) {
const passwordField = $('input[name="config[password]"]').first();
// If in edit mode and password field is present, fill it with stars
if (itemID) {
var passwordField = $('input[name="config[password]"]').first();
if (passwordField.length > 0) {
passwordField.attr('value', fakePassword);
}
if (passwordField.length > 0) {
passwordField.attr("value", fakePassword);
}
}
if($('.message-container').length) {
setTimeout(
function()
{
$('.message-container').fadeOut();
}, 3500);
if ($(".message-container").length) {
setTimeout(() => {
$(".message-container").fadeOut();
}, 3500);
}
function readURL(input) {
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = function (e) {
$("#appimage img").attr("src", e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
// from https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var livestatsRefreshTimeouts = [];
var livestatsFuncs = [];
var livestatsContainers = $('.livestats-container');
function stopLivestatsRefresh() {
for (var timeoutId of livestatsRefreshTimeouts) {
window.clearTimeout(timeoutId);
}
}
function startLivestatsRefresh() {
for (var fun of livestatsFuncs) {
fun();
}
}
if (livestatsContainers.length > 0) {
if (typeof document.addEventListener === "undefined" || hidden === undefined) {
console.log("This browser does not support visibilityChange");
} else {
document.addEventListener(visibilityChange, function() {
if (document[hidden]) {
stopLivestatsRefresh();
} else {
startLivestatsRefresh();
}
}, false);
}
livestatsContainers.each(function(index){
var id = $(this).data('id');
var dataonly = $(this).data('dataonly');
var increaseby = (dataonly == 1) ? 20000 : 1000;
var container = $(this);
var max_timer = 30000;
var timer = 5000;
var fun = function worker() {
$.ajax({
url: base+'get_stats/'+id,
dataType: 'json',
success: function(data) {
container.html(data.html);
if(data.status == 'active') timer = increaseby;
else {
if(timer < max_timer) timer += 2000;
}
},
complete: function(jqXHR) {
if (jqXHR.status > 299) {
// Stop polling when we get errors
return;
}
// Schedule the next request when the current one's complete
livestatsRefreshTimeouts[index] = window.setTimeout(worker, timer);
}
});
};
livestatsFuncs[index] = fun;
fun();
});
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#appimage img').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
$('#upload').change(function() {
readURL(this);
});
/*$(".droppable").droppable({
$("#upload").change(function () {
readURL(this);
});
/* $(".droppable").droppable({
tolerance: "intersect",
drop: function( event, ui ) {
var tag = $( this ).data('id');
@@ -129,153 +49,160 @@ $.when( $.ready ).then(function() {
});
}
});*/
}); */
$( '#sortable' ).sortable({
stop: function (event, ui) {
var idsInOrder = $('#sortable').sortable('toArray', {
attribute: 'data-id'
});
$.post(
base+'order',
{ order:idsInOrder }
);
}
$("#sortable").sortable({
stop() {
const idsInOrder = $("#sortable").sortable("toArray", {
attribute: "data-id",
});
$.post(`${base}order`, { order: idsInOrder });
},
});
$("#sortable").sortable("disable");
});
$('#sortable').sortable('disable');
$('#main').on('mouseenter', '#sortable.ui-sortable-disabled .item', function () {
$(this).siblings('.tooltip').addClass('active')
$('.refresh', this).addClass('active')
}).on('mouseleave', '.item', function () {
$(this).siblings('.tooltip').removeClass('active')
$('.refresh', this).removeClass('active')
$("#main")
.on("mouseenter", "#sortable.ui-sortable-disabled .item", function () {
$(this).siblings(".tooltip").addClass("active");
$(".refresh", this).addClass("active");
})
$('#config-buttons').on('mouseenter', 'a', function () {
$('.tooltip', this).addClass('active');
}).on('mouseleave', 'a', function () {
$('.tooltip', this).removeClass('active');
.on("mouseleave", ".item", function () {
$(this).siblings(".tooltip").removeClass("active");
$(".refresh", this).removeClass("active");
});
$("#config-buttons")
.on("mouseenter", "a", function () {
$(".tooltip", this).addClass("active");
})
$('.searchform > form').on('submit', function (event) {
if ($('#search-container select[name=provider]').val() === 'tiles') {
event.preventDefault();
}
.on("mouseleave", "a", function () {
$(".tooltip", this).removeClass("active");
});
$('#search-container').on('input', 'input[name=q]', function () {
const search = this.value
const items = $('#sortable').children('.item-container')
if($('#search-container select[name=provider]').val() === 'tiles') {
if(search.length > 0) {
items.hide()
items.filter(function () {
const name = $(this).data('name').toLowerCase();
return name.includes(search.toLowerCase())
}).show()
} else {
items.show()
}
$(".searchform > form").on("submit", (event) => {
if ($("#search-container select[name=provider]").val() === "tiles") {
event.preventDefault();
}
});
$("#search-container")
.on("input", "input[name=q]", function () {
const search = this.value;
const items = $("#sortable").children(".item-container");
if ($("#search-container select[name=provider]").val() === "tiles") {
if (search.length > 0) {
items.hide();
items
.filter(function () {
const name = $(this).data("name").toLowerCase();
return name.includes(search.toLowerCase());
})
.show();
} else {
items.show()
}
}).on('change', 'select[name=provider]', function () {
const items = $('#sortable').children('.item-container')
if($(this).val() === 'tiles') {
$('#search-container button').hide()
const search = $('#search-container input[name=q]').val()
if(search.length > 0) {
items.hide()
items.filter(function () {
const name = $(this).data('name').toLowerCase();
return name.includes(search.toLowerCase())
}).show()
} else {
items.show()
}
} else {
$('#search-container button').show()
items.show()
items.show();
}
} else {
items.show();
}
})
$('#app').on('click', '#config-button', function(e) {
e.preventDefault();
var app = $('#app');
var active = (app.hasClass('header'));
app.toggleClass('header');
if(active) {
$('.add-item').hide();
$('.item-edit').hide();
$('#app').removeClass('sidebar');
$('#sortable .tooltip').css('display', '')
$('#sortable').sortable('disable');
.on("change", "select[name=provider]", function () {
const items = $("#sortable").children(".item-container");
if ($(this).val() === "tiles") {
$("#search-container button").hide();
const search = $("#search-container input[name=q]").val();
if (search.length > 0) {
items.hide();
items
.filter(function () {
const name = $(this).data("name").toLowerCase();
return name.includes(search.toLowerCase());
})
.show();
} else {
$('#sortable .tooltip').css('display', 'none')
$('#sortable').sortable('enable');
setTimeout(function() {
$('.add-item').fadeIn();
$('.item-edit').fadeIn();
}, 350);
}
}).on('click', '#add-item, #pin-item', function(e) {
e.preventDefault();
var app = $('#app');
var active = (app.hasClass('sidebar'));
app.toggleClass('sidebar');
}).on('click', '.close-sidenav', function(e) {
e.preventDefault();
var app = $('#app');
app.removeClass('sidebar');
}).on('click', '#test_config', function(e) {
e.preventDefault();
var apiurl = $('#create input[name=url]').val();
var override_url = $('#sapconfig input[name="config[override_url]"]').val();
if(override_url.length && override_url != '') {
apiurl = override_url;
}
var data = {};
data['url'] = apiurl;
$('.config-item').each(function(index){
var config = $(this).data('config');
data[config] = $(this).val();
});
data['id'] = $('form[data-item-id]').data('item-id');
if (data.password && data.password === fakePassword) {
data.password = '';
}
$.post(base+'test_config', { data: data }, function(data) {
alert(data);
});
});
$('#pinlist').on('click', 'a', function(e) {
e.preventDefault();
var current = $(this);
var id = current.data('id');
var tag = current.data('tag');
$.get(base+'items/pintoggle/'+id+'/true/'+tag, function(data) {
var inner = $(data).filter('#sortable').html();
$('#sortable').html(inner);
current.toggleClass('active');
});
});
$('#itemform').on('submit', function(e) {
var passwordField = $('input[name="config[password]"]').first();
if (passwordField.length > 0) {
if (passwordField.attr('value') === fakePassword) {
passwordField.attr('value', '');
}
items.show();
}
} else {
$("#search-container button").show();
items.show();
}
});
$("#app")
.on("click", "#config-button", (e) => {
e.preventDefault();
const app = $("#app");
const active = app.hasClass("header");
app.toggleClass("header");
if (active) {
$(".add-item").hide();
$(".item-edit").hide();
$("#app").removeClass("sidebar");
$("#sortable .tooltip").css("display", "");
$("#sortable").sortable("disable");
} else {
$("#sortable .tooltip").css("display", "none");
$("#sortable").sortable("enable");
setTimeout(() => {
$(".add-item").fadeIn();
$(".item-edit").fadeIn();
}, 350);
}
})
.on("click", "#add-item, #pin-item", (e) => {
e.preventDefault();
const app = $("#app");
// const active = app.hasClass("sidebar");
app.toggleClass("sidebar");
})
.on("click", ".close-sidenav", (e) => {
e.preventDefault();
const app = $("#app");
app.removeClass("sidebar");
})
.on("click", "#test_config", (e) => {
e.preventDefault();
let apiurl = $("#create input[name=url]").val();
const overrideUrl = $(
'#sapconfig input[name="config[override_url]"]'
).val();
if (overrideUrl.length && overrideUrl !== "") {
apiurl = overrideUrl;
}
const data = {};
data.url = apiurl;
$(".config-item").each(function () {
const config = $(this).data("config");
data[config] = $(this).val();
});
data.id = $("form[data-item-id]").data("item-id");
if (data.password && data.password === fakePassword) {
data.password = "";
}
$.post(`${base}test_config`, { data }, (responseData) => {
alert(responseData);
});
});
$("#pinlist").on("click", "a", function (e) {
e.preventDefault();
const current = $(this);
const id = current.data("id");
const tag = current.data("tag");
$.get(`${base}items/pintoggle/${id}/true/${tag}`, (data) => {
const inner = $(data).filter("#sortable").html();
$("#sortable").html(inner);
current.toggleClass("active");
});
});
$("#itemform").on("submit", () => {
const passwordField = $('input[name="config[password]"]').first();
if (passwordField.length > 0) {
if (passwordField.attr("value") === fakePassword) {
passwordField.attr("value", "");
}
}
});
});

48
resources/assets/js/itemExport.js vendored Normal file
View File

@@ -0,0 +1,48 @@
const EXPORT_FILE_NAME = "HeimdallExport.json";
const EXPORT_API_URL = "api/item";
/**
*
* @param {string} fileName
* @param {string} data
*/
function triggerFileDownload(fileName, data) {
const a = document.createElement("a");
const file = new Blob([data], {
type: "text/plain",
});
a.href = URL.createObjectURL(file);
a.download = EXPORT_FILE_NAME;
a.click();
}
/**
*
* @param {Event} event
*/
const exportItems = (event) => {
event.preventDefault();
fetch(EXPORT_API_URL)
.then((response) => {
if (response.status !== 200) {
window.alert("An error occurred while exporting...");
}
return response.json();
})
.then((data) => {
const exportedJson = JSON.stringify(data, null, 2);
triggerFileDownload(EXPORT_FILE_NAME, exportedJson);
});
};
const exportButton = document.querySelector("#item-export");
if (exportButton) {
exportButton.addEventListener("click", exportItems);
}

176
resources/assets/js/itemImport.js vendored Normal file
View File

@@ -0,0 +1,176 @@
const IMPORT_API_URL = "api/item";
const APP_LOAD_URL = "appload";
/**
*
* @param {object} item
* @param {array} errors
*/
const updateStatus = ({ item, errors }) => {
console.log(item, errors);
let statusLine;
if (errors.length === 0) {
statusLine = `<li class="success"><i class="fas fa-circle-check"></i> Imported: ${item.title} </li>`;
} else {
statusLine = `<li class="fail"><i class="fas fa-circle-xmark"></i> Failed: ${item.title} - ${errors[0]} </li>`;
}
document.querySelector(".import-status").innerHTML += statusLine;
};
/**
*
*/
function clearStatus() {
const statusContainer = document.querySelector(".import-status");
statusContainer.innerHTML = "";
}
/**
*
* @param {object} data
* @param {string} csrfToken
*/
const postToApi = (data, csrfToken) =>
fetch(IMPORT_API_URL, {
method: "POST",
cache: "no-cache",
redirect: "follow",
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": csrfToken,
},
body: JSON.stringify(data),
});
/**
*
* @returns {string}
*/
const getCSRFToken = () => {
const tokenSelector = 'input[name="_token"]';
return document.querySelector(tokenSelector).value;
};
/**
*
* @param {object} item
* @param {object} appDetails
* @returns {object}
*/
const mergeItemWithAppDetails = (item, appDetails) => ({
pinned: 1,
tags: [0],
appid: item.appid,
title: item.title,
colour: item.colour,
url: item.url,
appdescription: item.appdescription
? item.appdescription
: appDetails.description,
website: appDetails.website,
icon: appDetails.iconview,
config: item.description ? JSON.parse(item.description) : null,
});
/**
*
* @param {string|null} appId
* @returns {Promise<{}>|Promise<any>}
*/
const fetchAppDetails = (appId) => {
if (appId === null || appId === "null") {
return Promise.resolve({});
}
return fetch(APP_LOAD_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ app: appId }),
}).then((response) => response.json());
};
/**
*
* @param {array} items
*/
const importItems = (items) => {
items.forEach((item) => {
const errors = [];
fetchAppDetails(item.appid)
.catch(() =>
errors.push(new Error(`Failed to find app id: ${item.appid}`))
)
.then((appDetails) => {
const itemWithAppDetails = mergeItemWithAppDetails(item, appDetails);
const csrfToken = getCSRFToken();
return postToApi(itemWithAppDetails, csrfToken);
})
.catch(() =>
errors.push(new Error(`Failed to create item: ${item.title}`))
)
.finally(() => {
updateStatus({
item,
errors,
});
});
});
};
/**
*
* @param {Blob} file
* @returns {Promise<unknown>}
*/
const readJSON = (file) =>
new Promise((resolve, reject) => {
try {
const reader = new FileReader();
reader.onload = (event) => {
const contents = event.target.result;
resolve(JSON.parse(contents));
};
reader.readAsText(file);
} catch (e) {
reject(new Error("Unable to read file"));
}
});
/**
*
* @param {Event} event
*/
const openFileForImport = (file) => {
clearStatus();
return readJSON(file)
.catch((error) => {
console.error(error);
})
.then(importItems);
};
const fileInput = document.querySelector("input[name='import']");
const importButton = document.querySelectorAll(".import-button");
if (fileInput && importButton) {
importButton.forEach((importButton) => {
importButton.addEventListener("click", () => {
const file = fileInput.files[0];
if (!file) {
return;
}
openFileForImport(file);
});
});
fileInput.addEventListener("change", openFileForImport, false);
}

View File

@@ -1,35 +1,45 @@
const focusSearch = event => {
const searchInput = document.querySelector('input[name="q"]');
if (searchInput) {
event.preventDefault();
searchInput.focus();
}
const focusSearch = (event) => {
const searchInput = document.querySelector('input[name="q"]');
if (searchInput) {
event.preventDefault();
searchInput.focus();
}
};
const openFirstNonHiddenItem = event => {
if (event.target !== document.querySelector('input[name="q"]')) {
return;
}
const openFirstNonHiddenItem = (event) => {
if (event.target !== document.querySelector('input[name="q"]')) {
return;
}
const item = document.querySelector('#sortable section.item-container:not([style="display: none;"]) a');
const providerSelect = document.querySelector(
"#search-container select[name=provider]"
);
if ('href' in item) {
event.preventDefault();
window.open(item.href);
}
if (providerSelect.value !== "tiles") {
return;
}
const item = document.querySelector(
'#sortable section.item-container:not([style="display: none;"]) a'
);
if ("href" in item) {
event.preventDefault();
window.open(item.href);
}
};
const KEY_BINDINGS = {
'/': focusSearch,
'Enter': openFirstNonHiddenItem
"/": focusSearch,
Enter: openFirstNonHiddenItem,
};
document.addEventListener('keydown', function (event) {
try {
if (event.key in KEY_BINDINGS) {
KEY_BINDINGS[event.key](event);
}
} catch (e) {
document.addEventListener("keydown", (event) => {
try {
if (event.key in KEY_BINDINGS) {
KEY_BINDINGS[event.key](event);
}
});
} catch (e) {
// Nothing to do
}
});

100
resources/assets/js/liveStatRefresh.js vendored Normal file
View File

@@ -0,0 +1,100 @@
const REFRESH_INTERVAL_SMALL = 5000;
const REFRESH_INTERVAL_BIG = 30000;
const QUEUE_PROCESSING_INTERVAL = 1000;
const CONTAINER_SELECTOR = ".livestats-container";
/**
* @returns {*[]}
*/
function createQueue() {
const queue = [];
let suspended = false;
function processQueue() {
if (queue.length === 0 || suspended === true) {
return;
}
const next = queue.shift();
next();
}
document.addEventListener("visibilitychange", () => {
suspended = document.hidden;
});
setInterval(processQueue, QUEUE_PROCESSING_INTERVAL);
return queue;
}
/**
* @returns {NodeListOf<Element>}
*/
function getContainers() {
return document.querySelectorAll(CONTAINER_SELECTOR);
}
/**
*
* @param {boolean} dataOnly
* @param {boolean} active
* @returns {number}
*/
function getQueueInterval(dataOnly, active) {
if (dataOnly) {
return REFRESH_INTERVAL_BIG;
}
if (active) {
return REFRESH_INTERVAL_SMALL;
}
return REFRESH_INTERVAL_BIG;
}
/**
* @param {HTMLElement} container
* @param {array} queue
* @returns {function(): Promise<Response>}
*/
function createUpdateJob(container, queue) {
const id = container.getAttribute("data-id");
// Data only attribute seems to indicate that the item should not be updated that often
const isDataOnly = container.getAttribute("data-dataonly") === "1";
return () =>
fetch(`get_stats/${id}`)
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error(`Network response was not ok: ${response.status}`);
})
.then((data) => {
// eslint-disable-next-line no-param-reassign
container.innerHTML = data.html;
const isActive = data.status === "active";
if (queue) {
setTimeout(() => {
queue.push(createUpdateJob(container, queue));
}, getQueueInterval(isDataOnly, isActive));
}
})
.catch((error) => {
console.error(error);
});
}
const livestatContainers = getContainers();
if (livestatContainers.length > 0) {
const myQueue = createQueue();
livestatContainers.forEach((container) => {
createUpdateJob(container, myQueue)();
});
}

View File

@@ -1141,4 +1141,22 @@ select:-webkit-autofill:focus {
a:not(:focus-within) {
opacity: 0.4;
}
}
.import-status {
list-style: none;
li {
display: flex;
align-items: center;
margin: 6px 0;
svg {
margin-right: 8px;
}
&.success svg {
color: $app-green;
}
&.fail svg {
color: $app-red;
}
}
}

View File

@@ -72,6 +72,7 @@ return array (
'apps.only_admin_account' => 'Only if you have admin-account!',
'apps.autologin_url' => 'Auto login url',
'apps.show_deleted' => 'Showing Deleted Applications',
'app.import' => 'Import',
'dashboard' => 'Home dashboard',
'user.user_list' => 'Users',
'user.add_user' => 'Add user',
@@ -86,6 +87,8 @@ return array (
'delete' => 'Delete',
'optional' => 'Optional',
'restore' => 'Restore',
'export' => 'Export',
'import' => 'Import',
'alert.success.item_created' => 'Item created successfully',
'alert.success.item_updated' => 'Item updated successfully',
'alert.success.item_deleted' => 'Item deleted successfully',

View File

@@ -13,7 +13,7 @@
<div data-id="{{ $app->id }}" data-dataonly="{{ $app->getconfig()->dataonly ?? '0' }}" class="livestats-container{{ title_color($app->colour) }}"></div>
@endif
</div>
<a rel="noopener noreferrer" class="link{{ title_color($app->colour) }}"{!! $app->link_target !!} href="{{ $app->link }}"><i class="fas {{ $app->link_icon }}"></i></a>
<a rel="noopener noreferrer" onauxclick="this.blur();" onclick="this.blur();" class="link{{ title_color($app->colour) }}"{!! $app->link_target !!} href="{{ $app->link }}"><i class="fas {{ $app->link_icon }}"></i></a>
<?php /*
@if($app->enhanced() === true && (bool)$app->getConfig()->enabled === true)
<div class="tile-actions refresh">

View File

@@ -0,0 +1,38 @@
@extends('layouts.app')
@section('content')
<section class="module-container">
<header>
<div class="section-title">{{ __('app.import') }}</div>
<div class="module-actions">
<button type="submit" class="button import-button"><i class="fa fa-save"></i><span>{{ __('import') }}</span></button>
<a href="{{ route('settings.index', []) }}" class="button"><i class="fa fa-ban"></i><span>{{ __('app.buttons.cancel') }}</span></a>
</div>
</header>
<div class="create">
{!! csrf_field() !!}
<div class="input">
<input class="form-control" name="import" type="file">
</div>
<div>
<ul class="import-status" style="display: block">
</ul>
</div>
</div>
<footer>
<div class="section-title">&nbsp;</div>
<div class="module-actions">
<button type="submit" class="button import-button"><i class="fa fa-save"></i><span>{{ __('import') }}</span></button>
<a href="{{ route('settings.index', []) }}" class="button"><i class="fa fa-ban"></i><span>{{ __('app.buttons.cancel') }}</span></a>
</div>
</footer>
</section>
@endsection

View File

@@ -25,7 +25,7 @@
<meta name="theme-color" content="#ffffff">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="{{ mix('css/app.css') }}" type="text/css" />
<link rel="stylesheet" href="{{ asset(mix('css/app.css')) }}" type="text/css" />
<link rel="stylesheet" href="{{ asset('css/all.min.css?v='.config('app.version')) }}" type="text/css" />
<script src="{{ asset('js/fontawesome.js') }}"></script>
@if(config('app.url') !== 'http://localhost')
@@ -116,7 +116,7 @@
</div>
<script src="{{ asset('js/jquery-3.6.0.min.js') }}"></script>
<script src="{{ asset('js/jquery-ui.min.js') }}"></script>
<script src="{{ mix('js/app.js') }}"></script>
<script src="{{ asset(mix('js/app.js')) }}"></script>
@yield('scripts')
<script id="custom_js">

View File

@@ -2,13 +2,18 @@
@section('content')
@foreach ($groups as $group)
@foreach ($groups as $index => $group)
<section class="module-container">
<header>
<div class="section-title">
{{ __($group->title) }}
</div>
@if($index === 0)
<div class="module-actions">
<a href="{{ route('items.import', []) }}" id="item-import" class="button"><i class="fas fa-file-arrow-up"></i><span>{{ __('import') }}</span></a>
<a href="#export" id="item-export" class="button"><i class="fas fa-file-arrow-down"></i><span>{{ __('export') }}</span></a>
</div>
@endif
</header>
<table class="table table-hover">

View File

@@ -1,6 +1,18 @@
<?php
use Illuminate\Http\Request;
use App\Application;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ImportController;
use App\Http\Controllers\ItemController;
use App\Http\Controllers\ItemRestController;
use App\Http\Controllers\SearchController;
use App\Http\Controllers\SettingsController;
use App\Http\Controllers\TagController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
@@ -17,37 +29,54 @@ if (config('app.url') !== 'http://localhost') {
URL::forceRootUrl(config('app.url'));
}
Route::get('/userselect/{user}', 'Auth\LoginController@setUser')->name('user.set');
Route::get('/userselect', 'UserController@selectUser')->name('user.select');
Route::get('/autologin/{uuid}', 'Auth\LoginController@autologin')->name('user.autologin');
Route::get('/userselect/{user}', [LoginController::class, 'setUser'])->name('user.set');
Route::get('/userselect', [UserController::class, 'selectUser'])->name('user.select');
Route::get('/autologin/{uuid}', [LoginController::class, 'autologin'])->name('user.autologin');
Route::get('/', [ItemController::class,'dash'])->name('dash');
Route::get('check_app_list', [ItemController::class,'checkAppList'])->name('applist');
Route::get('/', 'ItemController@dash')->name('dash');
Route::get('check_app_list', 'ItemController@checkAppList')->name('applist');
Route::get('single/{appid}', function ($appid) {
return json_encode(\App\Application::single($appid));
return json_encode(Application::single($appid));
})->name('single');
Route::resources([
'items' => 'ItemController',
'tags' => 'TagController',
]);
/**
* Tag Routes
*/
Route::resource('tags', TagController::class);
Route::get('tag/{slug}', 'TagController@show')->name('tags.show');
Route::get('tag/add/{tag}/{item}', 'TagController@add')->name('tags.add');
Route::get('tag/restore/{id}', 'TagController@restore')->name('tags.restore');
Route::group([
'as' => 'tags.',
'prefix' => 'tag',
], function () {
Route::get('/{slug}', [TagController::class, 'show'])->name('show');
Route::get('/add/{tag}/{item}', [TagController::class, 'add'])->name('add');
Route::get('/restore/{id}', [TagController::class, 'restore'])->name('restore');
});
Route::get('items/websitelookup/{url}', 'ItemController@websitelookup')->name('items.lookup');
Route::get('items/pin/{id}', 'ItemController@pin')->name('items.pin');
Route::get('items/restore/{id}', 'ItemController@restore')->name('items.restore');
Route::get('items/unpin/{id}', 'ItemController@unpin')->name('items.unpin');
Route::get('items/pintoggle/{id}/{ajax?}/{tag?}', 'ItemController@pinToggle')->name('items.pintoggle');
Route::post('order', 'ItemController@setOrder')->name('items.order');
Route::post('appload', 'ItemController@appload')->name('appload');
Route::post('test_config', 'ItemController@testConfig')->name('test_config');
Route::get('get_stats/{id}', 'ItemController@getStats')->name('get_stats');
/**
* Item Routes
*/
Route::resource('items', ItemController::class);
Route::get('/search', 'SearchController@index')->name('search');
Route::group([
'as' => 'items.',
'prefix' => 'items',
], function () {
Route::get('/websitelookup/{url}', [ItemController::class, 'websitelookup'])->name('lookup');
Route::get('/pin/{id}', [ItemController::class, 'pin'])->name('pin');
Route::get('/restore/{id}', [ItemController::class, 'restore'])->name('restore');
Route::get('/unpin/{id}', [ItemController::class, 'unpin'])->name('unpin');
Route::get('/pintoggle/{id}/{ajax?}/{tag?}', [ItemController::class, 'pinToggle'])->name('pintoggle');
});
Route::post('order', [ItemController::class,'setOrder'])->name('items.order');
Route::post('appload', [ItemController::class,'appload'])->name('appload');
Route::post('test_config', [ItemController::class,'testConfig'])->name('test_config');
Route::get('get_stats/{id}', [ItemController::class,'getStats'])->name('get_stats');
Route::get('/search', [SearchController::class,'index'])->name('search');
Route::get('view/{name_view}', function ($name_view) {
return view('SupportedApps::'.$name_view)->render();
@@ -58,9 +87,10 @@ Route::get('titlecolour', function (Request $request) {
if ($color) {
return title_color($color);
}
return '';
})->name('titlecolour');
Route::resource('users', 'UserController');
Route::resource('users', UserController::class);
/**
* Settings.
@@ -69,15 +99,15 @@ Route::group([
'as' => 'settings.',
'prefix' => 'settings',
], function () {
Route::get('/', 'SettingsController@index')
->name('index');
Route::get('edit/{id}', 'SettingsController@edit')
->name('edit');
Route::get('clear/{id}', 'SettingsController@clear')
->name('clear');
Route::patch('edit/{id}', 'SettingsController@update');
Route::get('/', [SettingsController::class,'index'])->name('index');
Route::get('edit/{id}', [SettingsController::class,'edit'])->name('edit');
Route::get('clear/{id}', [SettingsController::class,'clear'])->name('clear');
Route::patch('edit/{id}', [SettingsController::class,'update']);
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/home', [HomeController::class,'index'])->name('home');
Route::resource('api/item', ItemRestController::class);
Route::get('import', ImportController::class)->name('items.import');

File diff suppressed because one or more lines are too long

50
tests/.env.testing Normal file
View File

@@ -0,0 +1,50 @@
APP_NAME=Heimdall
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=daily
DB_CONNECTION=sqlite
DB_DATABASE=test.sqlite
#DB_CONNECTION=<mysql | pgsql>
#DB_HOST=<hostname | ip>
#DB_PORT=<port number>
#DB_DATABASE=<database>
#DB_USERNAME=<user>
#DB_PASSWORD=<password>
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

View File

@@ -15,6 +15,8 @@ trait CreatesApplication
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->loadEnvironmentFrom('tests/.env.testing');
$app->make(Kernel::class)->bootstrap();
return $app;

View File

@@ -0,0 +1,83 @@
<?php
namespace Tests\Feature;
use App\Item;
use App\ItemTag;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class DashTest extends TestCase
{
use RefreshDatabase;
/**
* Helpers
*/
private function addPinnedItemWithTitleToDB($title)
{
$item = Item::factory()
->create([
'title' => $title,
'pinned' => 1,
]);
ItemTag::factory()->create([
'item_id' => $item->id,
'tag_id' => 0,
]);
}
private function addTagWithTitleToDB($title)
{
Item::factory()
->create([
'title' => $title,
'type' => 1,
]);
}
/**
* Test Cases
*/
public function test_loads_empty_dash()
{
$this->seed();
$response = $this->get('/');
$response->assertStatus(200);
}
public function test_displays_items_on_the_dash()
{
$this->seed();
$this->addPinnedItemWithTitleToDB('Item 1');
$this->addPinnedItemWithTitleToDB('Item 2');
$this->addPinnedItemWithTitleToDB('Item 3');
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Item 1');
$response->assertSee('Item 2');
$response->assertSee('Item 3');
}
public function test_displays_tags_on_the_dash()
{
$this->seed();
$this->addTagWithTitleToDB('Tag 1');
$this->addTagWithTitleToDB('Tag 2');
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Tag 1');
$response->assertSee('Tag 2');
}
}

View File

@@ -1,21 +0,0 @@
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ItemCreateTest extends TestCase
{
use RefreshDatabase;
public function test_displays_the_item_create_page()
{
$this->seed();
$response = $this->get('/items/create');
$response->assertStatus(200);
}
public function test_display_the_home_dashboard_tag()
{
$this->seed();
$response = $this->get('/items/create');
$response->assertSee('Home dashboard');
}
public function test_creates_a_new_item()
{
$this->seed();
$item = [
'pinned' => 1,
'appid' => 'null',
'website' => null,
'title' => 'Item A',
'colour' => '#00f',
'url' => 'http://10.0.1.1',
'tags' => [0],
];
$response = $this->post('/items', $item);
$response->assertStatus(302);
$response->assertSee('Redirecting to');
}
public function test_redirects_to_dash_when_adding_a_new_item()
{
$this->seed();
$item = [
'pinned' => 1,
'appid' => 'null',
'website' => null,
'title' => 'Item A',
'colour' => '#00f',
'url' => 'http://10.0.1.1',
'tags' => [0],
];
$response = $this->post('/items', $item);
$response->assertStatus(302);
$response->assertSee('Redirecting to http://localhost');
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Tests\Feature;
use App\Item;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ItemDeleteTest extends TestCase
{
use RefreshDatabase;
public function test_deletes_an_item()
{
$this->seed();
$item = Item::factory()
->create([
'title' => 'Item A',
]);
$response = $this->post('/items/'.$item->id, ['_method' => 'DELETE']);
$response->assertStatus(302);
}
public function test_redirects_to_item_list_page_when_deleting_an_item()
{
$this->seed();
$item = Item::factory()
->create([
'title' => 'Item A',
]);
$response = $this->post('/items/'.$item->id, ['_method' => 'DELETE']);
$response->assertStatus(302);
$response->assertSee('Redirecting to http://localhost/items');
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace Tests\Feature;
use App\Item;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Date;
use Tests\TestCase;
class ItemExportTest extends TestCase
{
use RefreshDatabase;
public function test_returns_empty_jsonarray_when_there_are_no_items_in_the_db()
{
$response = $this->get('api/item');
$response->assertJsonCount(0);
}
public function test_returns_exactly_the_defined_fields()
{
$exampleItem = [
"appdescription" => "Description",
"appid" => "123",
"colour" => "#000",
"description" => "Description",
"title" => "Item Title",
"url" => "http://gorczany.com/nihil-rerum-distinctio-voluptate-assumenda-accusantium-exercitationem"
];
Item::factory()
->create($exampleItem);
$response = $this->get('api/item');
$response->assertExactJson([(object)$exampleItem]);
}
public function test_returns_all_items()
{
Item::factory()
->count(3)
->create();
$response = $this->get('api/item');
$response->assertJsonCount(3);
}
public function test_does_not_return_deleted_item()
{
Item::factory()
->create([
'deleted_at' => Date::create('1970')
]);
Item::factory()
->create();
$response = $this->get('api/item');
$response->assertJsonCount(1);
}
public function test_does_not_return_tags()
{
Item::factory()
->create([
'type' => 1
]);
Item::factory()
->create();
$response = $this->get('api/item');
$response->assertJsonCount(1);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Tests\Feature;
use App\Item;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ItemListTest extends TestCase
{
use RefreshDatabase;
protected function addItemWithTitleToDB($title)
{
Item::factory()
->create([
'title' => $title
]);
}
public function test_displays_items_on_the_item_list_page()
{
$this->addItemWithTitleToDB('Item 1');
$this->addItemWithTitleToDB('Item 2');
$this->addItemWithTitleToDB('Item 3');
$response = $this->get('/items');
$response->assertStatus(200);
$response->assertSee('Item 1');
$response->assertSee('Item 2');
$response->assertSee('Item 3');
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SettingsTest extends TestCase
{
use RefreshDatabase;
public function test_displays_the_settings_page()
{
$this->seed();
$response = $this->get('/settings');
$response->assertStatus(200);
$response->assertSeeInOrder([
'Version',
'Language',
'Support',
'Donate',
'Background Image',
'Homepage Search',
'Default Search Provider',
'Link opens in',
'Custom CSS',
'Custom JavaScript',
]);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Tests\Feature;
use App\Item;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class TagListTest extends TestCase
{
use RefreshDatabase;
private function addTagWithTitleToDB($title)
{
Item::factory()
->create([
'title' => $title,
'type' => 1,
]);
}
public function test_displays_the_tags_on_the_tag_list_page()
{
$this->addTagWithTitleToDB('Tag 1');
$this->addTagWithTitleToDB('Tag 2');
$this->addTagWithTitleToDB('Tag 3');
$response = $this->get('/tags');
$response->assertStatus(200);
$response->assertSee('Tag 1');
$response->assertSee('Tag 2');
$response->assertSee('Tag 3');
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Tests\Feature;
use App\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class UserListTest extends TestCase
{
use RefreshDatabase;
protected function addUserWithNameToDB($name)
{
User::factory()
->create([
'username' => $name
]);
}
public function test_displays_admin_on_user_list_page_when_default_install()
{
$this->seed();
$response = $this->get('/users');
$response->assertStatus(200);
$response->assertSee('admin');
}
public function test_displays_users_on_user_list_page()
{
$this->seed();
$this->addUserWithNameToDB('User 1');
$response = $this->get('/users');
$response->assertStatus(200);
$response->assertSee('User 1');
}
}

View File

@@ -12,7 +12,7 @@ class SettingsSeederTest extends TestCase
*
* @return void
*/
public function testReturnsAJSONMapWithSameAmountOfItemsAsLanguageDirectoriesPresent()
public function test_returns_a_jsonmap_with_same_amount_of_items_as_language_directories_present()
{
$languageDirectories = array_filter(glob(resource_path().'/lang/*'), 'is_dir');

View File

@@ -11,7 +11,7 @@ class LangTest extends TestCase
*
* @return void
*/
public function testAllLanguageKeysAreDefined()
public function test_all_language_keys_are_defined()
{
$this->markTestSkipped('2022-11-14 Lot of keys missing. Enable this test to see them all.');
$languageDirectories = array_filter(glob(resource_path().'/lang/*'), 'is_dir');

View File

@@ -0,0 +1,15 @@
; This file is for unifying the coding style for different editors and IDEs.
; More information at http://editorconfig.org
root = true
[*]
charset = utf-8
indent_size = 4
indent_style = space
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false

View File

@@ -0,0 +1,63 @@
<?php
// Share common rules between non-test and test files
return [
'@PSR12' => true,
'blank_line_after_opening_tag' => true,
'braces' => [
'allow_single_line_anonymous_class_with_empty_body' => true,
],
'compact_nullable_typehint' => true,
'declare_equal_normalize' => true,
'lowercase_cast' => true,
'lowercase_static_reference' => true,
'new_with_braces' => true,
'no_blank_lines_after_class_opening' => true,
'no_leading_import_slash' => true,
'no_whitespace_in_blank_line' => true,
'ordered_class_elements' => [
'order' => [
'use_trait',
],
],
'ordered_imports' => [
'imports_order' => [
'class',
'function',
'const',
],
'sort_algorithm' => 'alpha',
],
'return_type_declaration' => true,
'short_scalar_cast' => true,
'single_blank_line_before_namespace' => true,
'single_trait_insert_per_statement' => true,
'ternary_operator_spaces' => true,
'visibility_required' => [
'elements' => [
'const',
'method',
'property',
],
],
// Further quality-of-life improvements
'array_syntax' => [
'syntax' => 'short',
],
'concat_space' => [
'spacing' => 'one',
],
'fully_qualified_strict_types' => true,
'native_function_invocation' => [
'include' => [],
'strict' => true,
],
'no_unused_imports' => true,
'single_quote' => true,
'space_after_semicolon' => true,
'trailing_comma_in_multiline_array' => true,
'trim_array_spaces' => true,
'unary_operator_spaces' => true,
'whitespace_after_comma_in_array' => true,
];

View File

@@ -0,0 +1,14 @@
<?php
require __DIR__ . '/vendor/autoload.php';
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude('tests');
$config = require __DIR__ . '/.php_cs.common.php';
return PhpCsFixer\Config::create()
->setFinder($finder)
->setRules($config)
->setRiskyAllowed(true)
->setCacheFile(__DIR__ . '/.php_cs.cache');

View File

@@ -0,0 +1,22 @@
<?php
require __DIR__ . '/vendor/autoload.php';
$finder = PhpCsFixer\Finder::create()
->in(__DIR__ . '/tests')
->exclude('__snapshots__');
$config = require __DIR__ . '/.php_cs.common.php';
// Additional rules for tests
$config = array_merge(
$config,
[
'declare_strict_types' => true,
]
);
return PhpCsFixer\Config::create()
->setFinder($finder)
->setRules($config)
->setRiskyAllowed(true)
->setCacheFile(__DIR__ . '/.php_cs.tests.cache');

View File

@@ -0,0 +1,175 @@
# Changelog
All notable changes to this project will be documented in this file.
[Next release](https://github.com/barryvdh/laravel-ide-helper/compare/v2.12.3...master)
--------------
2022-03-06, 2.12.3
------------------
### Fixed
- Fix date and datetime handling for attributes that set a serialization format option for the Carbon instance [#1324 / FLeudts](https://github.com/barryvdh/laravel-ide-helper/pull/1324)
- Fix composer conflict with composer/pcre version 2/3. [#1327 / barryvdh](https://github.com/barryvdh/laravel-ide-helper/pull/1327)
2022-02-08, 2.12.2
------------------
### Fixed
- Remove composer dependecy, use copy of ClassMapGenerator [#1313 / barryvdh](https://github.com/barryvdh/laravel-ide-helper/pull/1313)
2022-01-24, 2.12.1
------------------
### Fixed
- Properly handle `Castable`s without return type. [#1306 / binotaliu](https://github.com/barryvdh/laravel-ide-helper/pull/1306)
2022-01-23, 2.12.0
------------------
### Added
- Add support for custom casts that using `Castable` [#1287 / binotaliu](https://github.com/barryvdh/laravel-ide-helper/pull/1287)
- Added Laravel 9 support [#1297 / rcerljenko](https://github.com/barryvdh/laravel-ide-helper/pull/1297)
2022-01-03, 2.11.0
------------------
### Added
- Add support for Laravel 8.77 Attributes [\#1289 / SimonJnsson](https://github.com/barryvdh/laravel-ide-helper/pull/1289)
- Add support for cast types `decimal:*`, `encrypted:*`, `immutable_date`, `immutable_datetime`, `custom_datetime`, and `immutable_custom_datetime` [#1262 / miken32](https://github.com/barryvdh/laravel-ide-helper/pull/1262)
- Add support of variadic parameters in `ide-helper:models` [\#1234 / shaffe-fr](https://github.com/barryvdh/laravel-ide-helper/pull/1234)
- Add support of custom casts without properties [\#1267 / sparclex](https://github.com/barryvdh/laravel-ide-helper/pull/1267)
### Fixed
- Fix recursively searching for `HasFactory` and `Macroable` traits [\#1216 / daniel-de-wit](https://github.com/barryvdh/laravel-ide-helper/pull/1216)
- Use platformName to determine db type when casting boolean types [\#1212 / stockalexander](https://github.com/barryvdh/laravel-ide-helper/pull/1212)
### Changed
- Move default models helper filename to config [\#1241 / wimski](https://github.com/barryvdh/laravel-ide-helper/pull/1241)
2021-06-18, 2.10.1
------------------
### Added
- Added Type registration according to [Custom Mapping Types documentation](https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#custom-mapping-types) [\#1228 / wimski](https://github.com/barryvdh/laravel-ide-helper/pull/1241)
### Fixed
- Fixing issue where configured custom_db_types could cause a DBAL exception to be thrown while running `ide-helper:models` [\#1228 / wimski](https://github.com/barryvdh/laravel-ide-helper/pull/1241)
2021-04-09, 2.10.0
------------------
### Added
- Allowing Methods to be set or unset in ModelHooks [\#1198 / jenga201](https://github.com/barryvdh/laravel-ide-helper/pull/1198)\
Note: the visibility of `\Barryvdh\LaravelIdeHelper\Console\ModelsCommand::setMethod` has been changed to **public**!
### Fixed
- Fixing issue where incorrect autoloader unregistered [\#1210 / tezhm](https://github.com/barryvdh/laravel-ide-helper/pull/1210)
2021-04-02, 2.9.3
-----------------
### Fixed
- Support both customized namespace factories as well as default resolvable ones [\#1201 / wimski](https://github.com/barryvdh/laravel-ide-helper/pull/1201)
2021-04-01, 2.9.2
-----------------
### Added
- Model hooks for adding custom information from external sources to model classes through the ModelsCommand [\#945 / wimski](https://github.com/barryvdh/laravel-ide-helper/pull/945)
### Fixed
- Fix ide-helper:models exception if model doesn't have factory [\#1196 / ahmed-aliraqi](https://github.com/barryvdh/laravel-ide-helper/pull/1196)
- Running tests triggering post_migrate hooks [\#1193 / netpok](https://github.com/barryvdh/laravel-ide-helper/pull/1193)
- Array_merge error when config is cached prior to package install [\#1184 / netpok](https://github.com/barryvdh/laravel-ide-helper/pull/1184)
2021-03-15, 2.9.1
-----------------
### Added
- Generate PHPDoc for Laravel 8.x factories [\#1074 / ahmed-aliraqi](https://github.com/barryvdh/laravel-ide-helper/pull/1074)
- Add a comment to a property like table columns [\#1168 / biiiiiigmonster](https://github.com/barryvdh/laravel-ide-helper/pull/1168)
- Added `post_migrate` hook to run commands after a migration [\#1163 / netpok](https://github.com/barryvdh/laravel-ide-helper/pull/1163)
- Allow for PhpDoc for macros with union types [\#1148 / riesjart](https://github.com/barryvdh/laravel-ide-helper/pull/1148)
### Fixed
- Error when generating helper for invokable classes [\#1124 / standaniels](https://github.com/barryvdh/laravel-ide-helper/pull/1124)
- Fix broken ReflectionUnionTypes [\#1132 / def-studio](https://github.com/barryvdh/laravel-ide-helper/pull/1132)
- Relative class names are not converted to fully-qualified class names [\#1005 / SavKS](https://github.com/barryvdh/laravel-ide-helper/pull/1005)
2020-12-30, 2.9.0
-----------------
### Changed
- Dropped support for Laravel 6 and Laravel 7, as well as support for PHP 7.2 and added support for doctrine/dbal:^3 [\#1114 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/1114)
### Fixed
- `Macro::initPhpDoc()` will save original docblock if present [\#1116 / LastDragon-ru](https://github.com/barryvdh/laravel-ide-helper/pull/1116)
- `Alias` will grab macros from `\Illuminate\Database\Eloquent\Builder` too [\#1118 / LastDragon-ru](https://github.com/barryvdh/laravel-ide-helper/pull/1118)
2020-12-08, 2.8.2
-----------------
### Added
- Fix phpdoc generate for custom cast with parameter [\#986 / artelkr](https://github.com/barryvdh/laravel-ide-helper/pull/986)
- Created a possibility to add custom relation type [\#987 / efinder2](https://github.com/barryvdh/laravel-ide-helper/pull/987)
- Added `@see` with macro/mixin definition location to PhpDoc [\#1054 / riesjart](https://github.com/barryvdh/laravel-ide-helper/pull/1054)
- Initial compatibility for PHP8 [\#1106 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/1106)
### Changed
- Implement DeferrableProvider [\#914 / kon-shou](https://github.com/barryvdh/laravel-ide-helper/pull/914)
### Fixed
- Compatibility with Lumen [\#1043 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/1043)
- Allow model_locations to have glob patterns [\#1059 / saackearl](https://github.com/barryvdh/laravel-ide-helper/pull/1059)
- Error when generating helper for macroable classes which are not facades and contain a "fake" method [\#1066 / domkrm] (https://github.com/barryvdh/laravel-ide-helper/pull/1066)
- Casts with a return type of `static` or `$this` now resolve to an instance of the cast [\#1103 / riesjart](https://github.com/barryvdh/laravel-ide-helper/pull/1103)
### Removed
- Removed format and broken generateJsonHelper [\#1053 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/1053)
2020-09-07, 2.8.1
-----------------
### Added
- Support Laravel 8 [\#1022 / barryvdh](https://github.com/barryvdh/laravel-ide-helper/pull/1022)
- Add option to force usage of FQN [\#1031 / edvordo](https://github.com/barryvdh/laravel-ide-helper/pull/1031)
- Add support for macros of all macroable classes [\#1006 / domkrm](https://github.com/barryvdh/laravel-ide-helper/pull/1006)
2020-08-11, 2.8.0
-----------------
### Added
- Add static return type to builder methods [\#924 / dmason30](https://github.com/barryvdh/laravel-ide-helper/pull/924)
- Add `optonal` to meta generator for PhpStorm [\#932 / halaei](https://github.com/barryvdh/laravel-ide-helper/pull/932)
- Decimal columns as string in Models [\#948 / fgibaux](https://github.com/barryvdh/laravel-ide-helper/pull/948)
- Simplify full namespaces for already included resources [\#954 / LANGERGabriel](https://github.com/barryvdh/laravel-ide-helper/pull/954)
- Make writing relation count properties optional [\#969 / AegirLeet](https://github.com/barryvdh/laravel-ide-helper/pull/969)
- Add more methods able to resolve container instances [\#996 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/996)
### Fixed
- Test `auth` is bound before detect Auth driver [\#946 / zhwei](https://github.com/barryvdh/laravel-ide-helper/pull/946)
- Fix inline doc-block for final models [\#944 / Gummibeer](https://github.com/barryvdh/laravel-ide-helper/pull/955)
2020-04-22, 2.7.0
-----------------
### Added
- Add `ignored_models` as config option [\#890 / pataar](https://github.com/barryvdh/laravel-ide-helper/pull/890)
- Infer return type from reflection if no phpdoc given [\#906 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/906)
- Add custom collection support for get and all methods [\#903 / dmason30](https://github.com/barryvdh/laravel-ide-helper/pull/903)
- if a model implements interfaces, include them in the stub [\#920 / mr-feek](https://github.com/barryvdh/laravel-ide-helper/pull/920)
- Generate noinspections PHPStorm tags [\#905 / mzglinski](https://github.com/barryvdh/laravel-ide-helper/pull/905)
- Added support for Laravel 7 custom casts [\#913 / belamov](https://github.com/barryvdh/laravel-ide-helper/pull/913)
- Ability to use patterns for model_locations [\#921 / 4n70w4](https://github.com/barryvdh/laravel-ide-helper/pull/921)
### Fixed
- MorphToMany relations with query not working [\#894 / UksusoFF](https://github.com/barryvdh/laravel-ide-helper/pull/894)
- Fix camelCase duplicated properties generator [\#881 / bop10](https://github.com/barryvdh/laravel-ide-helper/pull/881)
- Prevent generation of invalid code for certain parameter default values [\#901 / loilo](https://github.com/barryvdh/laravel-ide-helper/pull/901)
- Make hasOne and morphOne nullable [\#864 / leo108](https://github.com/barryvdh/laravel-ide-helper/pull/864)
- Remove unnecessary and wrong definition of SoftDelete methods [\#918 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/918)
- Unregister meta command custom autoloader when it is no longer needed [\#919 / mr-feek](https://github.com/barryvdh/laravel-ide-helper/pull/919)
2020-02-25, 2.6.7
-----------------
### Added
- Support for Laravel 7 [commit by barryvdh](https://github.com/barryvdh/laravel-ide-helper/commit/edd69c5e0508972c81f1f7173236de2459c45814)
2019-12-02, 2.6.6
-----------------
### Added
- Add splat operator (...) support [\#860 / ngmy](https://github.com/barryvdh/laravel-ide-helper/pull/860)
- Add support for custom date class via Date::use() [\#859 / mfn](https://github.com/barryvdh/laravel-ide-helper/pull/859)
### Fixed
- Prevent undefined property errors [\#877 / matt-allan](https://github.com/barryvdh/laravel-ide-helper/pull/877)
----
Missing an older changelog? Feel free to submit a PR!

View File

@@ -0,0 +1,21 @@
# The MIT License (MIT)
Copyright (c) Barry vd. Heuvel <barryvdh@gmail.com>
> Permission is hereby granted, free of charge, to any person obtaining a copy
> of this software and associated documentation files (the "Software"), to deal
> in the Software without restriction, including without limitation the rights
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
> copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in
> all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
> THE SOFTWARE.

View File

@@ -0,0 +1,442 @@
# Laravel IDE Helper Generator
[![Tests](https://github.com/barryvdh/laravel-ide-helper/actions/workflows/run-tests.yml/badge.svg)](https://github.com/barryvdh/laravel-ide-helper/actions)
[![Packagist License](https://poser.pugx.org/barryvdh/laravel-ide-helper/license.png)](http://choosealicense.com/licenses/mit/)
[![Latest Stable Version](https://poser.pugx.org/barryvdh/laravel-ide-helper/version.png)](https://packagist.org/packages/barryvdh/laravel-ide-helper)
[![Total Downloads](https://poser.pugx.org/barryvdh/laravel-ide-helper/d/total.png)](https://packagist.org/packages/barryvdh/laravel-ide-helper)
[![Fruitcake](https://img.shields.io/badge/Powered%20By-Fruitcake-b2bc35.svg)](https://fruitcake.nl/)
**Complete PHPDocs, directly from the source**
This package generates helper files that enable your IDE to provide accurate autocompletion.
Generation is done based on the files in your project, so they are always up-to-date.
- [Installation](#installation)
- [Usage](#usage)
- [Automatic PHPDoc generation for Laravel Facades](#automatic-phpdoc-generation-for-laravel-facades)
- [Automatic PHPDocs for models](#automatic-phpdocs-for-models)
- [Model Directories](#model-directories)
- [Ignore Models](#ignore-models)
- [Model Hooks](#model-hooks)
- [Automatic PHPDocs generation for Laravel Fluent methods](#automatic-phpdocs-generation-for-laravel-fluent-methods)
- [Auto-completion for factory builders](#auto-completion-for-factory-builders)
- [PhpStorm Meta for Container instances](#phpstorm-meta-for-container-instances)
- [Usage with Lumen](#usage-with-lumen)
- [Enabling Facades](#enabling-facades)
- [Adding the Service Provider](#adding-the-service-provider)
- [Adding Additional Facades](#adding-additional-facades)
- [License](#license)
## Installation
Require this package with composer using the following command:
```bash
composer require --dev barryvdh/laravel-ide-helper
```
This package makes use of [Laravels package auto-discovery mechanism](https://medium.com/@taylorotwell/package-auto-discovery-in-laravel-5-5-ea9e3ab20518), which means if you don't install dev dependencies in production, it also won't be loaded.
If for some reason you want manually control this:
- add the package to the `extra.laravel.dont-discover` key in `composer.json`, e.g.
```json
"extra": {
"laravel": {
"dont-discover": [
"barryvdh/laravel-ide-helper"
]
}
}
```
- Add the following class to the `providers` array in `config/app.php`:
```php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
```
If you want to manually load it only in non-production environments, instead you can add this to your `AppServiceProvider` with the `register()` method:
```php
public function register()
{
if ($this->app->isLocal()) {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
// ...
}
```
> Note: Avoid caching the configuration in your development environment, it may cause issues after installing this package; respectively clear the cache beforehand via `php artisan cache:clear` if you encounter problems when running the commands
## Usage
_Check out [this Laracasts video](https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/15) for a quick introduction/explanation!_
- `php artisan ide-helper:generate` - [PHPDoc generation for Laravel Facades ](#automatic-phpdoc-generation-for-laravel-facades)
- `php artisan ide-helper:models` - [PHPDocs for models](#automatic-PHPDocs-for-models)
- `php artisan ide-helper:meta` - [PhpStorm Meta file](#phpstorm-meta-for-container-instances)
Note: You do need CodeComplice for Sublime Text: https://github.com/spectacles/CodeComplice
### Automatic PHPDoc generation for Laravel Facades
You can now re-generate the docs yourself (for future updates)
```bash
php artisan ide-helper:generate
```
Note: `bootstrap/compiled.php` has to be cleared first, so run `php artisan clear-compiled` before generating.
This will generate the file `_ide_helper.php` which is expected to be additionally parsed by your IDE for autocomplete. You can use the config `filename` to change its name.
You can configure your `composer.json` to do this each time you update your dependencies:
```js
"scripts": {
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"@php artisan ide-helper:generate",
"@php artisan ide-helper:meta"
]
},
```
You can also publish the config file to change implementations (ie. interface to specific class) or set defaults for `--helpers`.
```bash
php artisan vendor:publish --provider="Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider" --tag=config
```
The generator tries to identify the real class, but if it cannot be found, you can define it in the config file.
Some classes need a working database connection. If you do not have a default working connection, some facades will not be included.
You can use an in-memory SQLite driver by adding the `-M` option.
You can choose to include helper files. This is not enabled by default, but you can override it with the `--helpers (-H)` option.
The `Illuminate/Support/helpers.php` is already set up, but you can add/remove your own files in the config file.
### Automatic PHPDoc generation for macros and mixins
This package can generate PHPDocs for macros and mixins which will be added to the `_ide_helper.php` file.
But this only works if you use type hinting when declaring a macro.
```php
Str::macro('concat', function(string $str1, string $str2) : string {
return $str1 . $str2;
});
```
### Automatic PHPDocs for models
If you don't want to write your properties yourself, you can use the command `php artisan ide-helper:models` to generate
PHPDocs, based on table columns, relations and getters/setters.
> Note: this command requires a working database connection to introspect the table of each model
By default, you are asked to overwrite or write to a separate file (`_ide_helper_models.php`).
You can write the comments directly to your Model file, using the `--write (-W)` option, or
force to not write with `--nowrite (-N)`.
Alternatively using the `--write-mixin (-M)` option will only add a mixin tag to your Model file,
writing the rest in (`_ide_helper_models.php`).
The class name will be different from the model, avoiding the IDE duplicate annoyance.
> Please make sure to back up your models, before writing the info.
Writing to the models should keep the existing comments and only append new properties/methods.
The existing PHPDoc is replaced, or added if not found.
With the `--reset (-R)` option, the existing PHPDocs are ignored, and only the newly found columns/relations are saved as PHPDocs.
```bash
php artisan ide-helper:models "App\Models\Post"
```
```php
/**
* App\Models\Post
*
* @property integer $id
* @property integer $author_id
* @property string $title
* @property string $text
* @property \Illuminate\Support\Carbon $created_at
* @property \Illuminate\Support\Carbon $updated_at
* @property-read \User $author
* @property-read \Illuminate\Database\Eloquent\Collection|\Comment[] $comments
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post newQuery()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post query()
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post whereTitle($value)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post forAuthors(\User ...$authors)
* …
*/
```
With the `--write-mixin (-M)` option
```php
/**
* …
* @mixin IdeHelperPost
*/
```
#### Model Directories
By default, models in `app/models` are scanned. The optional argument tells what models to use (also outside app/models).
```bash
php artisan ide-helper:models "App\Models\Post" "App\Models\User"
```
You can also scan a different directory, using the `--dir` option (relative from the base path):
```bash
php artisan ide-helper:models --dir="path/to/models" --dir="app/src/Model"
```
You can publish the config file (`php artisan vendor:publish`) and set the default directories.
#### Ignore Models
Models can be ignored using the `--ignore (-I)` option
```bash
php artisan ide-helper:models --ignore="App\Models\Post,App\Models\User"
```
Or can be ignored by setting the `ignored_models` config
```php
'ignored_models' => [
App\Post::class,
Api\User::class
],
```
#### Magic `where*` methods
Eloquent allows calling `where<Attribute>` on your models, e.g. `Post::whereTitle(…)` and automatically translates this to e.g. `Post::where('title', '=', '…')`.
If for some reason it's undesired to have them generated (one for each column), you can disable this via config `write_model_magic_where` and setting it to `false`.
#### Magic `*_count` properties
You may use the [`::withCount`](https://laravel.com/docs/master/eloquent-relationships#counting-related-models) method to count the number results from a relationship without actually loading them. Those results are then placed in attributes following the `<columname>_count` convention.
By default, these attributes are generated in the phpdoc. You can turn them off by setting the config `write_model_relation_count_properties` to `false`.
#### Support `@comment` based on DocBlock
In order to better support IDEs, relations and getters/setters can also add a comment to a property like table columns. Therefore a custom docblock `@comment` is used:
```php
class Users extends Model
{
/**
* @comment Get User's full name
*
* @return string
*/
public function getFullNameAttribute(): string
{
return $this->first_name . ' ' .$this->last_name ;
}
}
// => after generate models
/**
* App\Models\Users
*
* @property-read string $full_name Get User's full name
* …
*/
```
#### Dedicated Eloquent Builder methods
A new method to the eloquent models was added called `newEloquentBuilder` [Reference](https://timacdonald.me/dedicated-eloquent-model-query-builders/) where we can
add support for creating a new dedicated class instead of using local scopes in the model itself.
If for some reason it's undesired to have them generated (one for each column), you can disable this via config `write_model_external_builder_methods` and setting it to `false`.
#### Unsupported or custom database types
Common column types (e.g. varchar, integer) are correctly mapped to PHP types (`string`, `int`).
But sometimes you may want to use custom column types in your database like `geography`, `jsonb`, `citext`, `bit`, etc. which may throw an "Unknown database type"-Exception.
For those special cases, you can map them via the config `custom_db_types`. Example:
```php
'custom_db_types' => [
'mysql' => [
'geography' => 'array',
'point' => 'array',
],
'postgresql' => [
'jsonb' => 'string',
'_int4' => 'array',
],
],
```
#### Model Hooks
If you need additional information on your model from sources that are not handled by default, you can hook in to the
generation process with model hooks to add extra information on the fly.
Simply create a class that implements `ModelHookInterface` and add it to the `model_hooks` array in the config:
```php
'model_hooks' => [
MyCustomHook::class,
],
```
The `run` method will be called during generation for every model and receives the current running `ModelsCommand` and the current `Model`, e.g.:
```php
class MyCustomHook implements ModelHookInterface
{
public function run(ModelsCommand $command, Model $model): void
{
if (! $model instanceof MyModel) {
return;
}
$command->setProperty('custom', 'string', true, false, 'My custom property');
$command->unsetMethod('method');
$command->setMethod('method', $command->getMethodType($model, '\Some\Class'), ['$param']);
}
}
```
```php
/**
* MyModel
*
* @property integer $id
* @property-read string $custom
```
### Automatic PHPDocs generation for Laravel Fluent methods
If you need PHPDocs support for Fluent methods in migration, for example
```php
$table->string("somestring")->nullable()->index();
```
After publishing vendor, simply change the `include_fluent` line your `config/ide-helper.php` file into:
```php
'include_fluent' => true,
```
Then run `php artisan ide-helper:generate`, you will now see all Fluent methods recognized by your IDE.
### Auto-completion for factory builders
If you would like the `factory()->create()` and `factory()->make()` methods to return the correct model class,
you can enable custom factory builders with the `include_factory_builders` line your `config/ide-helper.php` file.
Deprecated for Laravel 8 or latest.
```php
'include_factory_builders' => true,
```
For this to work, you must also publish the PhpStorm Meta file (see below).
## PhpStorm Meta for Container instances
It's possible to generate a PhpStorm meta file to [add support for factory design pattern](https://www.jetbrains.com/help/phpstorm/ide-advanced-metadata.html).
For Laravel, this means we can make PhpStorm understand what kind of object we are resolving from the IoC Container.
For example, `events` will return an `Illuminate\Events\Dispatcher` object,
so with the meta file you can call `app('events')` and it will autocomplete the Dispatcher methods.
```bash
php artisan ide-helper:meta
```
```php
app('events')->fire();
\App::make('events')->fire();
/** @var \Illuminate\Foundation\Application $app */
$app->make('events')->fire();
// When the key is not found, it uses the argument as class name
app('App\SomeClass');
// Also works with
app(App\SomeClass::class);
```
> Note: You might need to restart PhpStorm and make sure `.phpstorm.meta.php` is indexed.
>
> Note: When you receive a FatalException: class not found, check your config
> (for example, remove S3 as cloud driver when you don't have S3 configured. Remove Redis ServiceProvider when you don't use it).
You can change the generated filename via the config `meta_filename`. This can be useful for cases you want to take advantage the PhpStorm also supports the _directory_ `.phpstorm.meta.php/` which would parse any file places there, should your want provide additional files to PhpStorm.
## Usage with Lumen
This package is focused on Laravel development, but it can also be used in Lumen with some workarounds.
Because Lumen works a little different, as it is like a bare bone version of Laravel and the main configuration
parameters are instead located in `bootstrap/app.php`, some alterations must be made.
### Enabling Facades
While Laravel IDE Helper can generate automatically default Facades for code hinting,
Lumen doesn't come with Facades activated. If you plan in using them, you must enable
them under the `Create The Application` section, uncommenting this line:
```php
// $app->withFacades();
```
From there, you should be able to use the `create_alias()` function to add additional Facades into your application.
### Adding the Service Provider
You can install Laravel IDE Helper in `app/Providers/AppServiceProvider.php`,
and uncommenting this line that registers the App Service Providers, so it can properly load.
```php
// $app->register(App\Providers\AppServiceProvider::class);
```
If you are not using that line, that is usually handy to manage gracefully multiple Laravel/Lumen installations,
you will have to add this line of code under the `Register Service Providers` section of your `bootstrap/app.php`.
```php
if ($app->environment() !== 'production') {
$app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
```
After that, Laravel IDE Helper should work correctly. During the generation process,
the script may throw exceptions saying that some Class(s) doesn't exist or there are some undefined indexes.
This is normal, as Lumen has some default packages stripped away, like Cookies, Storage and Session.
If you plan to add these packages, you will have to add them manually and create additional Facades if needed.
### Adding Additional Facades
Currently, Lumen IDE Helper doesn't take into account additional Facades created under `bootstrap/app.php` using `create_alias()`,
so you need to create a `config/app.php` file and add your custom aliases under an `aliases` array again, like so:
```php
return [
'aliases' => [
'CustomAliasOne' => Example\Support\Facades\CustomAliasOne::class,
'CustomAliasTwo' => Example\Support\Facades\CustomAliasTwo::class,
//...
]
];
```
After you run `php artisan ide-helper:generate`, it's recommended (but not mandatory) to rename `config/app.php` to something else,
until you have to re-generate the docs or after passing to production environment.
Lumen 5.1+ will read this file for configuration parameters if it is present, and may overlap some configurations if it is completely populated.
## License
The Laravel IDE Helper Generator is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)

View File

@@ -0,0 +1,91 @@
{
"name": "barryvdh/laravel-ide-helper",
"description": "Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.",
"license": "MIT",
"keywords": [
"laravel",
"autocomplete",
"ide",
"helper",
"phpstorm",
"netbeans",
"sublime",
"codeintel",
"phpdoc"
],
"authors": [
{
"name": "Barry vd. Heuvel",
"email": "barryvdh@gmail.com"
}
],
"require": {
"php": "^7.3 || ^8.0",
"ext-json": "*",
"barryvdh/reflection-docblock": "^2.0.6",
"composer/pcre": "^1 || ^2 || ^3",
"doctrine/dbal": "^2.6 || ^3",
"illuminate/console": "^8 || ^9",
"illuminate/filesystem": "^8 || ^9",
"illuminate/support": "^8 || ^9",
"nikic/php-parser": "^4.7",
"phpdocumentor/type-resolver": "^1.1.0"
},
"require-dev": {
"ext-pdo_sqlite": "*",
"friendsofphp/php-cs-fixer": "^2",
"illuminate/config": "^8 || ^9",
"illuminate/view": "^8 || ^9",
"mockery/mockery": "^1.4",
"orchestra/testbench": "^6 || ^7",
"phpunit/phpunit": "^8.5 || ^9",
"spatie/phpunit-snapshot-assertions": "^3 || ^4",
"vimeo/psalm": "^3.12"
},
"suggest": {
"illuminate/events": "Required for automatic helper generation (^6|^7|^8|^9)."
},
"minimum-stability": "dev",
"prefer-stable": true,
"autoload": {
"psr-4": {
"Barryvdh\\LaravelIdeHelper\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Barryvdh\\LaravelIdeHelper\\Tests\\": "tests"
}
},
"config": {
"allow-plugins": {
"composer/package-versions-deprecated": true
},
"sort-packages": true
},
"extra": {
"branch-alias": {
"dev-master": "2.12-dev"
},
"laravel": {
"providers": [
"Barryvdh\\LaravelIdeHelper\\IdeHelperServiceProvider"
]
}
},
"scripts": {
"analyze": "psalm",
"check-style": [
"php-cs-fixer fix --diff --diff-format=udiff --dry-run",
"php-cs-fixer fix --diff --diff-format=udiff --dry-run --config=.php_cs.tests.php"
],
"fix-style": [
"php-cs-fixer fix",
"php-cs-fixer fix --config=.php_cs.tests.php"
],
"psalm-set-baseline": "psalm --set-baseline=psalm-baseline.xml",
"test": "phpunit",
"test-ci": "phpunit -d --without-creating-snapshots",
"test-regenerate": "phpunit -d --update-snapshots"
}
}

View File

@@ -0,0 +1,319 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Filename & Format
|--------------------------------------------------------------------------
|
| The default filename
|
*/
'filename' => '_ide_helper.php',
/*
|--------------------------------------------------------------------------
| Models filename
|--------------------------------------------------------------------------
|
| The default filename for the models helper file
|
*/
'models_filename' => '_ide_helper_models.php',
/*
|--------------------------------------------------------------------------
| Where to write the PhpStorm specific meta file
|--------------------------------------------------------------------------
|
| PhpStorm also supports the directory `.phpstorm.meta.php/` with arbitrary
| files in it, should you need additional files for your project; e.g.
| `.phpstorm.meta.php/laravel_ide_Helper.php'.
|
*/
'meta_filename' => '.phpstorm.meta.php',
/*
|--------------------------------------------------------------------------
| Fluent helpers
|--------------------------------------------------------------------------
|
| Set to true to generate commonly used Fluent methods
|
*/
'include_fluent' => false,
/*
|--------------------------------------------------------------------------
| Factory Builders
|--------------------------------------------------------------------------
|
| Set to true to generate factory generators for better factory()
| method auto-completion.
|
| Deprecated for Laravel 8 or latest.
|
*/
'include_factory_builders' => false,
/*
|--------------------------------------------------------------------------
| Write Model Magic methods
|--------------------------------------------------------------------------
|
| Set to false to disable write magic methods of model
|
*/
'write_model_magic_where' => true,
/*
|--------------------------------------------------------------------------
| Write Model External Eloquent Builder methods
|--------------------------------------------------------------------------
|
| Set to false to disable write external eloquent builder methods
|
*/
'write_model_external_builder_methods' => true,
/*
|--------------------------------------------------------------------------
| Write Model relation count properties
|--------------------------------------------------------------------------
|
| Set to false to disable writing of relation count properties to model DocBlocks.
|
*/
'write_model_relation_count_properties' => true,
/*
|--------------------------------------------------------------------------
| Write Eloquent Model Mixins
|--------------------------------------------------------------------------
|
| This will add the necessary DocBlock mixins to the model class
| contained in the Laravel Framework. This helps the IDE with
| auto-completion.
|
| Please be aware that this setting changes a file within the /vendor directory.
|
*/
'write_eloquent_model_mixins' => false,
/*
|--------------------------------------------------------------------------
| Helper files to include
|--------------------------------------------------------------------------
|
| Include helper files. By default not included, but can be toggled with the
| -- helpers (-H) option. Extra helper files can be included.
|
*/
'include_helpers' => false,
'helper_files' => [
base_path() . '/vendor/laravel/framework/src/Illuminate/Support/helpers.php',
],
/*
|--------------------------------------------------------------------------
| Model locations to include
|--------------------------------------------------------------------------
|
| Define in which directories the ide-helper:models command should look
| for models.
|
| glob patterns are supported to easier reach models in sub-directories,
| e.g. `app/Services/* /Models` (without the space)
|
*/
'model_locations' => [
'app',
],
/*
|--------------------------------------------------------------------------
| Models to ignore
|--------------------------------------------------------------------------
|
| Define which models should be ignored.
|
*/
'ignored_models' => [
],
/*
|--------------------------------------------------------------------------
| Models hooks
|--------------------------------------------------------------------------
|
| Define which hook classes you want to run for models to add custom information
|
| Hooks should implement Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface.
|
*/
'model_hooks' => [
// App\Support\IdeHelper\MyModelHook::class
],
/*
|--------------------------------------------------------------------------
| Extra classes
|--------------------------------------------------------------------------
|
| These implementations are not really extended, but called with magic functions
|
*/
'extra' => [
'Eloquent' => ['Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'],
'Session' => ['Illuminate\Session\Store'],
],
'magic' => [],
/*
|--------------------------------------------------------------------------
| Interface implementations
|--------------------------------------------------------------------------
|
| These interfaces will be replaced with the implementing class. Some interfaces
| are detected by the helpers, others can be listed below.
|
*/
'interfaces' => [
],
/*
|--------------------------------------------------------------------------
| Support for custom DB types
|--------------------------------------------------------------------------
|
| This setting allow you to map any custom database type (that you may have
| created using CREATE TYPE statement or imported using database plugin
| / extension to a Doctrine type.
|
| Each key in this array is a name of the Doctrine2 DBAL Platform. Currently valid names are:
| 'postgresql', 'db2', 'drizzle', 'mysql', 'oracle', 'sqlanywhere', 'sqlite', 'mssql'
|
| This name is returned by getName() method of the specific Doctrine/DBAL/Platforms/AbstractPlatform descendant
|
| The value of the array is an array of type mappings. Key is the name of the custom type,
| (for example, "jsonb" from Postgres 9.4) and the value is the name of the corresponding Doctrine2 type (in
| our case it is 'json_array'. Doctrine types are listed here:
| https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html#types
|
| So to support jsonb in your models when working with Postgres, just add the following entry to the array below:
|
| "postgresql" => array(
| "jsonb" => "json_array",
| ),
|
*/
'custom_db_types' => [
],
/*
|--------------------------------------------------------------------------
| Support for camel cased models
|--------------------------------------------------------------------------
|
| There are some Laravel packages (such as Eloquence) that allow for accessing
| Eloquent model properties via camel case, instead of snake case.
|
| Enabling this option will support these packages by saving all model
| properties as camel case, instead of snake case.
|
| For example, normally you would see this:
|
| * @property \Illuminate\Support\Carbon $created_at
| * @property \Illuminate\Support\Carbon $updated_at
|
| With this enabled, the properties will be this:
|
| * @property \Illuminate\Support\Carbon $createdAt
| * @property \Illuminate\Support\Carbon $updatedAt
|
| Note, it is currently an all-or-nothing option.
|
*/
'model_camel_case_properties' => false,
/*
|--------------------------------------------------------------------------
| Property Casts
|--------------------------------------------------------------------------
|
| Cast the given "real type" to the given "type".
|
*/
'type_overrides' => [
'integer' => 'int',
'boolean' => 'bool',
],
/*
|--------------------------------------------------------------------------
| Include DocBlocks from classes
|--------------------------------------------------------------------------
|
| Include DocBlocks from classes to allow additional code inspection for
| magic methods and properties.
|
*/
'include_class_docblocks' => false,
/*
|--------------------------------------------------------------------------
| Force FQN usage
|--------------------------------------------------------------------------
|
| Use the fully qualified (class) name in docBlock,
| event if class exists in a given file
| or there is an import (use className) of a given class
|
*/
'force_fqn' => false,
/*
|--------------------------------------------------------------------------
| Additional relation types
|--------------------------------------------------------------------------
|
| Sometimes it's needed to create custom relation types. The key of the array
| is the Relationship Method name. The value of the array is the canonical class
| name of the Relationship, e.g. `'relationName' => RelationShipClass::class`.
|
*/
'additional_relation_types' => [],
/*
|--------------------------------------------------------------------------
| Run artisan commands after migrations to generate model helpers
|--------------------------------------------------------------------------
|
| The specified commands should run after migrations are finished running.
|
*/
'post_migrate' => [
// 'ide-helper:models --nowrite',
],
];

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="3.15@de6e7f324f44dde540ebe7ebd4eb481b97c86f30">
<file src="src/Factories.php">
<UndefinedClass occurrences="2">
<code>Factory</code>
<code>Factory</code>
</UndefinedClass>
</file>
<file src="src/Generator.php">
<UndefinedClass occurrences="7">
<code>\Auth</code>
<code>\DB</code>
<code>\Cache</code>
<code>\Cache</code>
<code>\Queue</code>
<code>\SSH</code>
<code>\Storage</code>
</UndefinedClass>
</file>
</files>

View File

@@ -0,0 +1,16 @@
<?xml version="1.0"?>
<psalm
errorLevel="7"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
errorBaseline="psalm-baseline.xml"
>
<projectFiles>
<directory name="src" />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
</psalm>

View File

@@ -0,0 +1,115 @@
<?= '<?php' ?>
<?php
/**
* @var \Barryvdh\LaravelIdeHelper\Alias[][] $namespaces_by_alias_ns
* @var \Barryvdh\LaravelIdeHelper\Alias[][] $namespaces_by_extends_ns
* @var bool $include_fluent
* @var string $helpers
*/
?>
// @formatter:off
// phpcs:ignoreFile
/**
* A helper file for Laravel, to provide autocomplete information to your IDE
* Generated for Laravel <?= $version ?>.
*
* This file should not be included in your code, only analyzed by your IDE!
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @see https://github.com/barryvdh/laravel-ide-helper
*/
<?php foreach ($namespaces_by_extends_ns as $namespace => $aliases) : ?>
<?php if ($namespace == '\Illuminate\Database\Eloquent') :
continue;
endif; ?>
namespace <?= $namespace == '__root' ? '' : trim($namespace, '\\') ?> {
<?php foreach ($aliases as $alias) : ?>
<?= trim($alias->getDocComment(' ')) ?>
<?= $alias->getClassType() ?> <?= $alias->getExtendsClass() ?> {
<?php foreach ($alias->getMethods() as $method) : ?>
<?= trim($method->getDocComment(' ')) ?>
public static function <?= $method->getName() ?>(<?= $method->getParamsWithDefault() ?>)
{<?php if ($method->getDeclaringClass() !== $method->getRoot()) : ?>
//Method inherited from <?= $method->getDeclaringClass() ?>
<?php endif; ?>
<?php if ($method->isInstanceCall()) : ?>
/** @var <?=$method->getRoot()?> $instance */
<?php endif?>
<?= $method->shouldReturn() ? 'return ' : '' ?><?= $method->getRootMethodCall() ?>;
}
<?php endforeach; ?>
}
<?php endforeach; ?>
}
<?php endforeach; ?>
<?php foreach ($namespaces_by_alias_ns as $namespace => $aliases) : ?>
namespace <?= $namespace == '__root' ? '' : trim($namespace, '\\') ?> {
<?php foreach ($aliases as $alias) : ?>
<?= $alias->getClassType() ?> <?= $alias->getShortName() ?> extends <?= $alias->getExtends() ?> {<?php if ($alias->getExtendsNamespace() == '\Illuminate\Database\Eloquent') : ?>
<?php foreach ($alias->getMethods() as $method) : ?>
<?= trim($method->getDocComment(' ')) ?>
public static function <?= $method->getName() ?>(<?= $method->getParamsWithDefault() ?>)
{<?php if ($method->getDeclaringClass() !== $method->getRoot()) : ?>
//Method inherited from <?= $method->getDeclaringClass() ?>
<?php endif; ?>
<?php if ($method->isInstanceCall()) : ?>
/** @var <?=$method->getRoot()?> $instance */
<?php endif?>
<?= $method->shouldReturn() ? 'return ' : '' ?><?= $method->getRootMethodCall() ?>;
}
<?php endforeach; ?>
<?php endif; ?>}
<?php endforeach; ?>
}
<?php endforeach; ?>
<?php if ($helpers) : ?>
namespace {
<?= $helpers ?>
}
<?php endif; ?>
<?php if ($include_fluent) : ?>
namespace Illuminate\Support {
/**
* Methods commonly used in migrations
*
* @method Fluent after(string $column) Add the after modifier
* @method Fluent charset(string $charset) Add the character set modifier
* @method Fluent collation(string $collation) Add the collation modifier
* @method Fluent comment(string $comment) Add comment
* @method Fluent default($value) Add the default modifier
* @method Fluent first() Select first row
* @method Fluent index(string $name = null) Add the in dex clause
* @method Fluent on(string $table) `on` of a foreign key
* @method Fluent onDelete(string $action) `on delete` of a foreign key
* @method Fluent onUpdate(string $action) `on update` of a foreign key
* @method Fluent primary() Add the primary key modifier
* @method Fluent references(string $column) `references` of a foreign key
* @method Fluent nullable(bool $value = true) Add the nullable modifier
* @method Fluent unique(string $name = null) Add unique index clause
* @method Fluent unsigned() Add the unsigned modifier
* @method Fluent useCurrent() Add the default timestamp value
* @method Fluent change() Add the change modifier
*/
class Fluent {}
}
<?php endif ?>
<?php foreach ($factories as $factory) : ?>
namespace <?=$factory->getNamespaceName()?> {
/**
* @method \Illuminate\Database\Eloquent\Collection|<?=$factory->getShortName()?>[]|<?=$factory->getShortName()?> create($attributes = [])
* @method \Illuminate\Database\Eloquent\Collection|<?=$factory->getShortName()?>[]|<?=$factory->getShortName()?> make($attributes = [])
*/
class <?=$factory->getShortName()?>FactoryBuilder extends \Illuminate\Database\Eloquent\FactoryBuilder {}
}
<?php endforeach; ?>

View File

@@ -0,0 +1,62 @@
<?= '<?php' ?>
// @formatter:off
namespace PHPSTORM_META {
/**
* PhpStorm Meta file, to provide autocomplete information for PhpStorm
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @see https://github.com/barryvdh/laravel-ide-helper
*/
<?php foreach ($methods as $method) : ?>
override(<?= $method ?>, map([
'' => '@',
<?php foreach ($bindings as $abstract => $class) : ?>
'<?= $abstract ?>' => \<?= $class ?>::class,
<?php endforeach; ?>
]));
<?php endforeach; ?>
<?php if (count($factories)) : ?>
override(\factory(0), map([
'' => '@FactoryBuilder',
<?php foreach ($factories as $factory) : ?>
'<?= $factory->getName() ?>' => \<?= $factory->getName() ?>FactoryBuilder::class,
<?php endforeach; ?>
]));
<?php endif; ?>
override(\Illuminate\Support\Arr::add(0), type(0));
override(\Illuminate\Support\Arr::except(0), type(0));
override(\Illuminate\Support\Arr::first(0), elementType(0));
override(\Illuminate\Support\Arr::last(0), elementType(0));
override(\Illuminate\Support\Arr::get(0), elementType(0));
override(\Illuminate\Support\Arr::only(0), type(0));
override(\Illuminate\Support\Arr::prepend(0), type(0));
override(\Illuminate\Support\Arr::pull(0), elementType(0));
override(\Illuminate\Support\Arr::set(0), type(0));
override(\Illuminate\Support\Arr::shuffle(0), type(0));
override(\Illuminate\Support\Arr::sort(0), type(0));
override(\Illuminate\Support\Arr::sortRecursive(0), type(0));
override(\Illuminate\Support\Arr::where(0), type(0));
override(\array_add(0), type(0));
override(\array_except(0), type(0));
override(\array_first(0), elementType(0));
override(\array_last(0), elementType(0));
override(\array_get(0), elementType(0));
override(\array_only(0), type(0));
override(\array_prepend(0), type(0));
override(\array_pull(0), elementType(0));
override(\array_set(0), type(0));
override(\array_sort(0), type(0));
override(\array_sort_recursive(0), type(0));
override(\array_where(0), type(0));
override(\head(0), elementType(0));
override(\last(0), elementType(0));
override(\with(0), type(0));
override(\tap(0), type(0));
override(\optional(0), type(0));
}

View File

@@ -0,0 +1,473 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag\MethodTag;
use Closure;
use Illuminate\Config\Repository as ConfigRepository;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\Facades\Facade;
use ReflectionClass;
class Alias
{
protected $alias;
/** @psalm-var class-string $facade */
protected $facade;
protected $extends = null;
protected $extendsClass = null;
protected $extendsNamespace = null;
protected $classType = 'class';
protected $short;
protected $namespace = '__root';
protected $root = null;
protected $classes = [];
protected $methods = [];
protected $usedMethods = [];
protected $valid = false;
protected $magicMethods = [];
protected $interfaces = [];
protected $phpdoc = null;
protected $classAliases = [];
/** @var ConfigRepository */
protected $config;
/**
* @param ConfigRepository $config
* @param string $alias
* @psalm-param class-string $facade
* @param string $facade
* @param array $magicMethods
* @param array $interfaces
*/
public function __construct($config, $alias, $facade, $magicMethods = [], $interfaces = [])
{
$this->alias = $alias;
$this->magicMethods = $magicMethods;
$this->interfaces = $interfaces;
$this->config = $config;
// Make the class absolute
$facade = '\\' . ltrim($facade, '\\');
$this->facade = $facade;
$this->detectRoot();
if (!$this->root || $this->isTrait()) {
return;
}
$this->valid = true;
$this->addClass($this->root);
$this->detectFake();
$this->detectNamespace();
$this->detectClassType();
$this->detectExtendsNamespace();
if (!empty($this->namespace)) {
$this->classAliases = (new UsesResolver())->loadFromClass($this->root);
//Create a DocBlock and serializer instance
$this->phpdoc = new DocBlock(new ReflectionClass($alias), new Context($this->namespace, $this->classAliases));
}
if ($facade === '\Illuminate\Database\Eloquent\Model') {
$this->usedMethods = ['decrement', 'increment'];
}
}
/**
* Add one or more classes to analyze
*
* @param array|string $classes
*/
public function addClass($classes)
{
$classes = (array)$classes;
foreach ($classes as $class) {
if (class_exists($class) || interface_exists($class)) {
$this->classes[] = $class;
} else {
echo "Class not exists: $class\r\n";
}
}
}
/**
* Check if this class is valid to process.
* @return bool
*/
public function isValid()
{
return $this->valid;
}
/**
* Get the classtype, 'interface' or 'class'
*
* @return string
*/
public function getClasstype()
{
return $this->classType;
}
/**
* Get the class which this alias extends
*
* @return null|string
*/
public function getExtends()
{
return $this->extends;
}
/**
* Get the class short name which this alias extends
*
* @return null|string
*/
public function getExtendsClass()
{
return $this->extendsClass;
}
/**
* Get the namespace of the class which this alias extends
*
* @return null|string
*/
public function getExtendsNamespace()
{
return $this->extendsNamespace;
}
/**
* Get the Alias by which this class is called
*
* @return string
*/
public function getAlias()
{
return $this->alias;
}
/**
* Return the short name (without namespace)
*/
public function getShortName()
{
return $this->short;
}
/**
* Get the namespace from the alias
*
* @return string
*/
public function getNamespace()
{
return $this->namespace;
}
/**
* Get the methods found by this Alias
*
* @return array|Method[]
*/
public function getMethods()
{
if (count($this->methods) > 0) {
return $this->methods;
}
$this->addMagicMethods();
$this->detectMethods();
return $this->methods;
}
/**
* Detect class returned by ::fake()
*/
protected function detectFake()
{
$facade = $this->facade;
if (!is_subclass_of($facade, Facade::class)) {
return;
}
if (!method_exists($facade, 'fake')) {
return;
}
$real = $facade::getFacadeRoot();
try {
$facade::fake();
$fake = $facade::getFacadeRoot();
if ($fake !== $real) {
$this->addClass(get_class($fake));
}
} finally {
$facade::swap($real);
}
}
/**
* Detect the namespace
*/
protected function detectNamespace()
{
if (strpos($this->alias, '\\')) {
$nsParts = explode('\\', $this->alias);
$this->short = array_pop($nsParts);
$this->namespace = implode('\\', $nsParts);
} else {
$this->short = $this->alias;
}
}
/**
* Detect the extends namespace
*/
protected function detectExtendsNamespace()
{
if (strpos($this->extends, '\\') !== false) {
$nsParts = explode('\\', $this->extends);
$this->extendsClass = array_pop($nsParts);
$this->extendsNamespace = implode('\\', $nsParts);
}
}
/**
* Detect the class type
*/
protected function detectClassType()
{
//Some classes extend the facade
if (interface_exists($this->facade)) {
$this->classType = 'interface';
$this->extends = $this->facade;
} else {
$this->classType = 'class';
if (class_exists($this->facade)) {
$this->extends = $this->facade;
}
}
}
/**
* Get the real root of a facade
*
* @return bool|string
*/
protected function detectRoot()
{
$facade = $this->facade;
try {
//If possible, get the facade root
if (method_exists($facade, 'getFacadeRoot')) {
$root = get_class($facade::getFacadeRoot());
} else {
$root = $facade;
}
//If it doesn't exist, skip it
if (!class_exists($root) && !interface_exists($root)) {
return;
}
$this->root = $root;
//When the database connection is not set, some classes will be skipped
} catch (\PDOException $e) {
$this->error(
'PDOException: ' . $e->getMessage() .
"\nPlease configure your database connection correctly, or use the sqlite memory driver (-M)." .
" Skipping $facade."
);
} catch (\Exception $e) {
$this->error('Exception: ' . $e->getMessage() . "\nSkipping $facade.");
}
}
/**
* Detect if this class is a trait or not.
*
* @return bool
*/
protected function isTrait()
{
// Check if the facade is not a Trait
return trait_exists($this->facade);
}
/**
* Add magic methods, as defined in the configuration files
*/
protected function addMagicMethods()
{
foreach ($this->magicMethods as $magic => $real) {
list($className, $name) = explode('::', $real);
if ((!class_exists($className) && !interface_exists($className)) || !method_exists($className, $name)) {
continue;
}
$method = new \ReflectionMethod($className, $name);
$class = new \ReflectionClass($className);
if (!in_array($magic, $this->usedMethods)) {
if ($class !== $this->root) {
$this->methods[] = new Method($method, $this->alias, $class, $magic, $this->interfaces, $this->classAliases);
}
$this->usedMethods[] = $magic;
}
}
}
/**
* Get the methods for one or multiple classes.
*
* @return string
*/
protected function detectMethods()
{
foreach ($this->classes as $class) {
$reflection = new \ReflectionClass($class);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if ($methods) {
foreach ($methods as $method) {
if (!in_array($method->name, $this->usedMethods)) {
// Only add the methods to the output when the root is not the same as the class.
// And don't add the __*() methods
if ($this->extends !== $class && substr($method->name, 0, 2) !== '__') {
$this->methods[] = new Method(
$method,
$this->alias,
$reflection,
$method->name,
$this->interfaces,
$this->classAliases
);
}
$this->usedMethods[] = $method->name;
}
}
}
// Check if the class is macroable
// (Eloquent\Builder is also macroable but doesn't use Macroable trait)
$traits = collect($reflection->getTraitNames());
if ($traits->contains('Illuminate\Support\Traits\Macroable') || $class === EloquentBuilder::class) {
$properties = $reflection->getStaticProperties();
$macros = isset($properties['macros']) ? $properties['macros'] : [];
foreach ($macros as $macro_name => $macro_func) {
if (!in_array($macro_name, $this->usedMethods)) {
// Add macros
$this->methods[] = new Macro(
$this->getMacroFunction($macro_func),
$this->alias,
$reflection,
$macro_name,
$this->interfaces,
$this->classAliases
);
$this->usedMethods[] = $macro_name;
}
}
}
}
}
/**
* @param $macro_func
*
* @return \ReflectionFunctionAbstract
* @throws \ReflectionException
*/
protected function getMacroFunction($macro_func)
{
if (is_array($macro_func) && is_callable($macro_func)) {
return new \ReflectionMethod($macro_func[0], $macro_func[1]);
}
if (is_object($macro_func) && is_callable($macro_func) && !$macro_func instanceof Closure) {
return new \ReflectionMethod($macro_func, '__invoke');
}
return new \ReflectionFunction($macro_func);
}
/*
* Get the docblock for this alias
*
* @param string $prefix
* @return mixed
*/
public function getDocComment($prefix = "\t\t")
{
$serializer = new DocBlockSerializer(1, $prefix);
if (!$this->phpdoc) {
return '';
}
if ($this->config->get('ide-helper.include_class_docblocks')) {
// if a class doesn't expose any DocBlock tags
// we can perform reflection on the class and
// add in the original class DocBlock
if (count($this->phpdoc->getTags()) === 0) {
$class = new ReflectionClass($this->root);
$this->phpdoc = new DocBlock($class->getDocComment());
}
}
$this->removeDuplicateMethodsFromPhpDoc();
return $serializer->getDocComment($this->phpdoc);
}
/**
* Removes method tags from the doc comment that already appear as functions inside the class.
* This prevents duplicate function errors in the IDE.
*
* @return void
*/
protected function removeDuplicateMethodsFromPhpDoc()
{
$methodNames = array_map(function (Method $method) {
return $method->getName();
}, $this->getMethods());
foreach ($this->phpdoc->getTags() as $tag) {
if ($tag instanceof MethodTag && in_array($tag->getMethodName(), $methodNames)) {
$this->phpdoc->deleteTag($tag);
}
}
}
/**
* Output an error.
*
* @param string $string
* @return void
*/
protected function error($string)
{
echo $string . "\r\n";
}
}

View File

@@ -0,0 +1,415 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* This file is copied from the Symfony package to composer/composer and then copied again here.
*
* (c) Fabien Potencier <fabien@symfony.com>
*/
namespace Barryvdh\LaravelIdeHelper;
use Composer\Pcre\Preg;
use Symfony\Component\Finder\Finder;
/**
* ClassMapGenerator
*
* @author Gyula Sallai <salla016@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ClassMapGenerator
{
/** @var array<array{name: string, length: int, pattern: non-empty-string}> */
private static $typeConfig;
/** @var non-empty-string */
private static $restPattern;
/**
* Generate a class map file
*
* @param \Traversable<string>|array<string> $dirs Directories or a single path to search in
* @param string $file The name of the class map file
* @return void
*/
public static function dump($dirs, $file)
{
$maps = [];
foreach ($dirs as $dir) {
$maps = array_merge($maps, static::createMap($dir));
}
file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
}
/**
* Checks if the given path is absolute
*
* @param string $path
* @return bool
*
* @see \Composer\Util\Filesystem
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
public static function isAbsolutePath($path)
{
return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':' || substr($path, 0, 2) === '\\\\';
}
/**
* Normalize a path. This replaces backslashes with slashes, removes ending
* slash and collapses redundant separators and up-level references.
*
* @param string $path Path to the file or directory
* @return string
*
* @see \Composer\Util\Filesystem
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
public static function normalizePath($path)
{
$parts = [];
$path = strtr($path, '\\', '/');
$prefix = '';
$absolute = false;
// extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive:
if (preg_match('{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix', $path, $match)) {
$prefix = $match[1];
$path = substr($path, strlen($prefix));
}
if (substr($path, 0, 1) === '/') {
$absolute = true;
$path = substr($path, 1);
}
$up = false;
foreach (explode('/', $path) as $chunk) {
if ('..' === $chunk && ($absolute || $up)) {
array_pop($parts);
$up = !(empty($parts) || '..' === end($parts));
} elseif ('.' !== $chunk && '' !== $chunk) {
$parts[] = $chunk;
$up = '..' !== $chunk;
}
}
return $prefix . ($absolute ? '/' : '') . implode('/', $parts);
}
/**
* Iterate over all files in the given directory searching for classes
*
* @param \Traversable<\SplFileInfo>|string|array<string> $path The path to search in or an iterator
* @param string $excluded Regex that matches file paths to be excluded from the classmap
* @param ?\Composer\IO\IOInterface $io IO object
* @param ?string $namespace Optional namespace prefix to filter by
* @param ?string $autoloadType psr-0|psr-4 Optional autoload standard to use mapping rules
* @param array<string, true> $scannedFiles
* @return array<class-string, string> A class map array
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public static function createMap($path, $excluded = null, $io = null, $namespace = null, $autoloadType = null, &$scannedFiles = [])
{
$basePath = $path;
if (is_string($path)) {
if (is_file($path)) {
$path = [new \SplFileInfo($path)];
} elseif (is_dir($path) || strpos($path, '*') !== false) {
$path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "' . $path .
'" which does not appear to be a file nor a folder'
);
}
} elseif (null !== $autoloadType) {
throw new \RuntimeException('Path must be a string when specifying an autoload type');
}
$map = [];
$cwd = realpath(getcwd());
foreach ($path as $file) {
$filePath = $file->getPathname();
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), ['php', 'inc', 'hh'])) {
continue;
}
if (!self::isAbsolutePath($filePath)) {
$filePath = $cwd . '/' . $filePath;
$filePath = self::normalizePath($filePath);
} else {
$filePath = Preg::replace('{[\\\\/]{2,}}', '/', $filePath);
}
$realPath = realpath($filePath);
// if a list of scanned files is given, avoid scanning twice the same file to save cycles and avoid generating warnings
// in case a PSR-0/4 declaration follows another more specific one, or a classmap declaration, which covered this file already
if (isset($scannedFiles[$realPath])) {
continue;
}
// check the realpath of the file against the excluded paths as the path might be a symlink and the excluded path is realpath'd so symlink are resolved
if ($excluded && Preg::isMatch($excluded, strtr($realPath, '\\', '/'))) {
continue;
}
// check non-realpath of file for directories symlink in project dir
if ($excluded && Preg::isMatch($excluded, strtr($filePath, '\\', '/'))) {
continue;
}
$classes = self::findClasses($filePath);
if (null !== $autoloadType) {
$classes = self::filterByNamespace($classes, $filePath, $namespace, $autoloadType, $basePath, $io);
// if no valid class was found in the file then we do not mark it as scanned as it might still be matched by another rule later
if ($classes) {
$scannedFiles[$realPath] = true;
}
} else {
// classmap autoload rules always collect all classes so for these we definitely do not want to scan again
$scannedFiles[$realPath] = true;
}
foreach ($classes as $class) {
// skip classes not within the given namespace prefix
if (null === $autoloadType && null !== $namespace && '' !== $namespace && 0 !== strpos($class, $namespace)) {
continue;
}
if (!isset($map[$class])) {
$map[$class] = $filePath;
} elseif ($io && $map[$class] !== $filePath && !Preg::isMatch('{/(test|fixture|example|stub)s?/}i', strtr($map[$class] . ' ' . $filePath, '\\', '/'))) {
$io->writeError(
'<warning>Warning: Ambiguous class resolution, "' . $class . '"' .
' was found in both "' . $map[$class] . '" and "' . $filePath . '", the first will be used.</warning>'
);
}
}
}
return $map;
}
/**
* Remove classes which could not have been loaded by namespace autoloaders
*
* @param array<int, class-string> $classes found classes in given file
* @param string $filePath current file
* @param string $baseNamespace prefix of given autoload mapping
* @param string $namespaceType psr-0|psr-4
* @param string $basePath root directory of given autoload mapping
* @param ?\Composer\IO\IOInterface $io IO object
* @return array<int, class-string> valid classes
*/
private static function filterByNamespace($classes, $filePath, $baseNamespace, $namespaceType, $basePath, $io)
{
$validClasses = [];
$rejectedClasses = [];
$realSubPath = substr($filePath, strlen($basePath) + 1);
$dotPosition = strrpos($realSubPath, '.');
$realSubPath = substr($realSubPath, 0, $dotPosition === false ? PHP_INT_MAX : $dotPosition);
foreach ($classes as $class) {
// silently skip if ns doesn't have common root
if ('' !== $baseNamespace && 0 !== strpos($class, $baseNamespace)) {
continue;
}
// transform class name to file path and validate
if ('psr-0' === $namespaceType) {
$namespaceLength = strrpos($class, '\\');
if (false !== $namespaceLength) {
$namespace = substr($class, 0, $namespaceLength + 1);
$className = substr($class, $namespaceLength + 1);
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $namespace)
. str_replace('_', DIRECTORY_SEPARATOR, $className);
} else {
$subPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
}
} elseif ('psr-4' === $namespaceType) {
$subNamespace = ('' !== $baseNamespace) ? substr($class, strlen($baseNamespace)) : $class;
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $subNamespace);
} else {
throw new \RuntimeException("namespaceType must be psr-0 or psr-4, $namespaceType given");
}
if ($subPath === $realSubPath) {
$validClasses[] = $class;
} else {
$rejectedClasses[] = $class;
}
}
// warn only if no valid classes, else silently skip invalid
if (empty($validClasses)) {
foreach ($rejectedClasses as $class) {
if ($io) {
$io->writeError("<warning>Class $class located in " . Preg::replace('{^' . preg_quote(getcwd()) . '}', '.', $filePath, 1) . " does not comply with $namespaceType autoloading standard. Skipping.</warning>");
}
}
return [];
}
return $validClasses;
}
/**
* Extract the classes in the given file
*
* @param string $path The file to check
* @throws \RuntimeException
* @return array<int, class-string> The found classes
*/
private static function findClasses($path)
{
$extraTypes = self::getExtraTypes();
// Use @ here instead of Silencer to actively suppress 'unhelpful' output
// @link https://github.com/composer/composer/pull/4886
$contents = @php_strip_whitespace($path);
if (!$contents) {
if (!file_exists($path)) {
$message = 'File at "%s" does not exist, check your classmap definitions';
} elseif (!is_readable($path)) {
$message = 'File at "%s" is not readable, check its permissions';
} elseif ('' === trim((string) file_get_contents($path))) {
// The input file was really empty and thus contains no classes
return [];
} else {
$message = 'File at "%s" could not be parsed as PHP, it may be binary or corrupted';
}
$error = error_get_last();
if (isset($error['message'])) {
$message .= PHP_EOL . 'The following message may be helpful:' . PHP_EOL . $error['message'];
}
throw new \RuntimeException(sprintf($message, $path));
}
// return early if there is no chance of matching anything in this file
Preg::matchAll('{\b(?:class|interface|trait' . $extraTypes . ')\s}i', $contents, $matches);
if (!$matches) {
return [];
}
// strip heredocs/nowdocs
$contents = preg_replace('{<<<[ \t]*([\'"]?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)(?:\s*)\\2(?=\s+|[;,.)])}s', 'null', $contents);
// strip strings
$contents = preg_replace('{"[^"\\\\]*+(\\\\.[^"\\\\]*+)*+"|\'[^\'\\\\]*+(\\\\.[^\'\\\\]*+)*+\'}s', 'null', $contents);
// strip leading non-php code if needed
if (substr($contents, 0, 2) !== '<?') {
$contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
if ($replacements === 0) {
return [];
}
}
// strip non-php blocks in the file
$contents = preg_replace('{\?>(?:[^<]++|<(?!\?))*+<\?}s', '?><?', $contents);
// strip trailing non-php code if needed
$pos = strrpos($contents, '?>');
if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
$contents = substr($contents, 0, $pos);
}
// strip comments if short open tags are in the file
if (preg_match('{(<\?)(?!(php|hh))}i', $contents)) {
$contents = preg_replace('{//.* | /\*(?:[^*]++|\*(?!/))*\*/}x', '', $contents);
}
Preg::matchAll('{
(?:
\b(?<![\$:>])(?P<type>class|interface|trait' . $extraTypes . ') \s++ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+)
| \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s++[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+(?:\s*+\\\\\s*+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*+)*+)? \s*+ [\{;]
)
}ix', $contents, $matches);
$classes = [];
$namespace = '';
for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
if (!empty($matches['ns'][$i])) {
$namespace = str_replace([' ', "\t", "\r", "\n"], '', $matches['nsname'][$i]) . '\\';
} else {
$name = $matches['name'][$i];
// skip anon classes extending/implementing
if ($name === 'extends' || $name === 'implements') {
continue;
}
if ($name[0] === ':') {
// This is an XHP class, https://github.com/facebook/xhp
$name = 'xhp' . substr(str_replace(['-', ':'], ['_', '__'], $name), 1);
} elseif ($matches['type'][$i] === 'enum') {
// something like:
// enum Foo: int { HERP = '123'; }
// The regex above captures the colon, which isn't part of
// the class name.
// or:
// enum Foo:int { HERP = '123'; }
// The regex above captures the colon and type, which isn't part of
// the class name.
$colonPos = strrpos($name, ':');
if (false !== $colonPos) {
$name = substr($name, 0, $colonPos);
}
}
$classes[] = ltrim($namespace . $name, '\\');
}
}
return $classes;
}
/**
* @return string
*/
private static function getExtraTypes()
{
static $extraTypes = null;
if (null === $extraTypes) {
$extraTypes = '';
if (PHP_VERSION_ID >= 80100 || (defined('HHVM_VERSION') && version_compare(HHVM_VERSION, '3.3', '>='))) {
$extraTypes .= '|enum';
}
self::setTypeConfig(array_merge(['class', 'interface', 'trait'], array_filter(explode('|', $extraTypes))));
}
return $extraTypes;
}
/**
* @param string[] $types
* @return void
*
* @see \Composer\Autoload\PhpFileCleaner
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
private static function setTypeConfig($types)
{
foreach ($types as $type) {
self::$typeConfig[$type[0]] = [
'name' => $type,
'length' => strlen($type),
'pattern' => '{.\b(?<![\$:>])' . $type . '\s++[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*+}Ais',
];
}
self::$restPattern = '{[^?"\'</' . implode('', array_keys(self::$typeConfig)) . ']+}A';
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Laravel IDE Helper Generator - Eloquent Model Mixin
*
* @author Charles A. Peterson <artistan@gmail.com>
* @copyright 2017 Charles A. Peterson / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Eloquent;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
/**
* A command to add \Eloquent mixin to Eloquent\Model
*
* @author Charles A. Peterson <artistan@gmail.com>
*/
class EloquentCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:eloquent';
/**
* @var Filesystem $files
*/
protected $files;
/**
* The console command description.
*
* @var string
*/
protected $description = 'Add \Eloquent helper to \Eloquent\Model';
/**
* @param Filesystem $files
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
Eloquent::writeEloquentModelHelper($this, $this->files);
}
}

View File

@@ -0,0 +1,174 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Eloquent;
use Barryvdh\LaravelIdeHelper\Generator;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
/**
* A command to generate autocomplete information for your IDE
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
class GeneratorCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a new IDE Helper file.';
/** @var \Illuminate\Config\Repository */
protected $config;
/** @var \Illuminate\Filesystem\Filesystem */
protected $files;
/** @var \Illuminate\View\Factory */
protected $view;
protected $onlyExtend;
/**
*
* @param \Illuminate\Config\Repository $config
* @param \Illuminate\Filesystem\Filesystem $files
* @param \Illuminate\View\Factory $view
*/
public function __construct(
/*ConfigRepository */
$config,
Filesystem $files,
/* Illuminate\View\Factory */
$view
) {
$this->config = $config;
$this->files = $files;
$this->view = $view;
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
if (
file_exists(base_path() . '/vendor/compiled.php') ||
file_exists(base_path() . '/bootstrap/cache/compiled.php') ||
file_exists(base_path() . '/storage/framework/compiled.php')
) {
$this->error(
'Error generating IDE Helper: first delete your compiled file (php artisan clear-compiled)'
);
return;
}
$filename = $this->argument('filename');
// Add the php extension if missing
// This is a backwards-compatible shim and can be removed in the future
if (substr($filename, -4, 4) !== '.php') {
$filename .= '.php';
}
if ($this->option('memory')) {
$this->useMemoryDriver();
}
$helpers = '';
if ($this->option('helpers') || ($this->config->get('ide-helper.include_helpers'))) {
foreach ($this->config->get('ide-helper.helper_files', []) as $helper) {
if (file_exists($helper)) {
$helpers .= str_replace(['<?php', '?>'], '', $this->files->get($helper));
}
}
} else {
$helpers = '';
}
$generator = new Generator($this->config, $this->view, $this->getOutput(), $helpers);
$content = $generator->generate();
$written = $this->files->put($filename, $content);
if ($written !== false) {
$this->info("A new helper file was written to $filename");
if ($this->option('write_mixins')) {
Eloquent::writeEloquentModelHelper($this, $this->files);
}
} else {
$this->error("The helper file could not be created at $filename");
}
}
protected function useMemoryDriver()
{
//Use a sqlite database in memory, to avoid connection errors on Database facades
$this->config->set(
'database.connections.sqlite',
[
'driver' => 'sqlite',
'database' => ':memory:',
]
);
$this->config->set('database.default', 'sqlite');
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
$filename = $this->config->get('ide-helper.filename');
return [
[
'filename', InputArgument::OPTIONAL, 'The path to the helper file', $filename,
],
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
$writeMixins = $this->config->get('ide-helper.write_eloquent_model_mixins');
return [
['write_mixins', 'W', InputOption::VALUE_OPTIONAL, 'Write mixins to Laravel Model?', $writeMixins],
['helpers', 'H', InputOption::VALUE_NONE, 'Include the helper files'],
['memory', 'M', InputOption::VALUE_NONE, 'Use sqlite memory driver'],
];
}
}

View File

@@ -0,0 +1,181 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2015 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Factories;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* A command to generate phpstorm meta data
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
*/
class MetaCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'ide-helper:meta';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate metadata for PhpStorm';
/** @var \Illuminate\Contracts\Filesystem\Filesystem */
protected $files;
/** @var \Illuminate\Contracts\View\Factory */
protected $view;
/** @var \Illuminate\Contracts\Config\Repository */
protected $config;
protected $methods = [
'new \Illuminate\Contracts\Container\Container',
'\Illuminate\Container\Container::makeWith(0)',
'\Illuminate\Contracts\Container\Container::get(0)',
'\Illuminate\Contracts\Container\Container::make(0)',
'\Illuminate\Contracts\Container\Container::makeWith(0)',
'\App::get(0)',
'\App::make(0)',
'\App::makeWith(0)',
'\app(0)',
'\resolve(0)',
'\Psr\Container\ContainerInterface::get(0)',
];
/**
*
* @param \Illuminate\Contracts\Filesystem\Filesystem $files
* @param \Illuminate\Contracts\View\Factory $view
* @param \Illuminate\Contracts\Config\Repository $config
*/
public function __construct($files, $view, $config)
{
$this->files = $files;
$this->view = $view;
$this->config = $config;
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
// Needs to run before exception handler is registered
$factories = $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [];
$ourAutoloader = $this->registerClassAutoloadExceptions();
$bindings = [];
foreach ($this->getAbstracts() as $abstract) {
// Validator and seeder cause problems
if (in_array($abstract, ['validator', 'seeder'])) {
continue;
}
try {
$concrete = $this->laravel->make($abstract);
$reflectionClass = new \ReflectionClass($concrete);
if (is_object($concrete) && !$reflectionClass->isAnonymous()) {
$bindings[$abstract] = get_class($concrete);
}
} catch (\Throwable $e) {
if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$this->comment("Cannot make '$abstract': " . $e->getMessage());
}
}
}
$this->unregisterClassAutoloadExceptions($ourAutoloader);
$content = $this->view->make('meta', [
'bindings' => $bindings,
'methods' => $this->methods,
'factories' => $factories,
])->render();
$filename = $this->option('filename');
$written = $this->files->put($filename, $content);
if ($written !== false) {
$this->info("A new meta file was written to $filename");
} else {
$this->error("The meta file could not be created at $filename");
}
}
/**
* Get a list of abstracts from the Laravel Application.
*
* @return array
*/
protected function getAbstracts()
{
$abstracts = $this->laravel->getBindings();
// Return the abstract names only
$keys = array_keys($abstracts);
sort($keys);
return $keys;
}
/**
* Register an autoloader the throws exceptions when a class is not found.
*
* @return callable
*/
protected function registerClassAutoloadExceptions(): callable
{
$autoloader = function ($class) {
throw new \ReflectionException("Class '$class' not found.");
};
spl_autoload_register($autoloader);
return $autoloader;
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
$filename = $this->config->get('ide-helper.meta_filename');
return [
['filename', 'F', InputOption::VALUE_OPTIONAL, 'The path to the meta file', $filename],
];
}
/**
* Remove our custom autoloader that we pushed onto the autoload stack
*
* @param callable $ourAutoloader
*/
private function unregisterClassAutoloadExceptions(callable $ourAutoloader): void
{
spl_autoload_unregister($ourAutoloader);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
<?php
namespace Barryvdh\LaravelIdeHelper\Contracts;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Illuminate\Database\Eloquent\Model;
interface ModelHookInterface
{
public function run(ModelsCommand $command, Model $model): void;
}

View File

@@ -0,0 +1,113 @@
<?php
/**
* Laravel IDE Helper to add \Eloquent mixin to Eloquent\Model
*
* @author Charles A. Peterson <artistan@gmail.com>
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
class Eloquent
{
/**
* Write mixin helper to the Eloquent\Model
* This is needed since laravel/framework v5.4.29
*
* @param Command $command
* @param Filesystem $files
*
* @return void
*/
public static function writeEloquentModelHelper(Command $command, Filesystem $files)
{
$class = 'Illuminate\Database\Eloquent\Model';
$reflection = new \ReflectionClass($class);
$namespace = $reflection->getNamespaceName();
$originalDoc = $reflection->getDocComment();
if (!$originalDoc) {
$command->info('Unexpected no document on ' . $class);
}
$phpdoc = new DocBlock($reflection, new Context($namespace));
$mixins = $phpdoc->getTagsByName('mixin');
$expectedMixins = [
'\Eloquent' => false,
'\Illuminate\Database\Eloquent\Builder' => false,
'\Illuminate\Database\Query\Builder' => false,
];
foreach ($mixins as $m) {
$mixin = $m->getContent();
if (isset($expectedMixins[$mixin])) {
$command->info('Tag Exists: @mixin ' . $mixin . ' in ' . $class);
$expectedMixins[$mixin] = true;
}
}
$changed = false;
foreach ($expectedMixins as $expectedMixin => $present) {
if ($present === false) {
$phpdoc->appendTag(Tag::createInstance('@mixin ' . $expectedMixin, $phpdoc));
$changed = true;
}
}
// If nothing's changed, stop here.
if (!$changed) {
return;
}
$serializer = new DocBlockSerializer();
$serializer->getDocComment($phpdoc);
$docComment = $serializer->getDocComment($phpdoc);
/*
The new DocBlock is appended to the beginning of the class declaration.
Since there is no DocBlock, the declaration is used as a guide.
*/
if (!$originalDoc) {
$originalDoc = 'abstract class Model implements';
$docComment .= "\nabstract class Model implements";
}
$filename = $reflection->getFileName();
if (!$filename) {
$command->error('Filename not found ' . $class);
return;
}
$contents = $files->get($filename);
if (!$contents) {
$command->error('No file contents found ' . $filename);
return;
}
$count = 0;
$contents = str_replace($originalDoc, $docComment, $contents, $count);
if ($count <= 0) {
$command->error('Content did not change ' . $contents);
return;
}
if (!$files->put($filename, $contents)) {
$command->error('File write failed to ' . $filename);
return;
}
$command->info('Wrote expected docblock to ' . $filename);
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Barryvdh\LaravelIdeHelper;
use Exception;
use Illuminate\Database\Eloquent\Factory;
use ReflectionClass;
class Factories
{
public static function all()
{
$factories = [];
if (static::isLaravelSevenOrLower()) {
$factory = app(Factory::class);
$definitions = (new ReflectionClass(Factory::class))->getProperty('definitions');
$definitions->setAccessible(true);
foreach ($definitions->getValue($factory) as $factory_target => $config) {
try {
$factories[] = new ReflectionClass($factory_target);
} catch (Exception $exception) {
}
}
}
return $factories;
}
protected static function isLaravelSevenOrLower()
{
return class_exists('Illuminate\Database\Eloquent\Factory');
}
}

View File

@@ -0,0 +1,313 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use ReflectionClass;
use Symfony\Component\Console\Output\OutputInterface;
class Generator
{
/** @var \Illuminate\Config\Repository */
protected $config;
/** @var \Illuminate\View\Factory */
protected $view;
/** @var \Symfony\Component\Console\Output\OutputInterface */
protected $output;
protected $extra = [];
protected $magic = [];
protected $interfaces = [];
protected $helpers;
/**
* @param \Illuminate\Config\Repository $config
* @param \Illuminate\View\Factory $view
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param string $helpers
*/
public function __construct(
/*ConfigRepository */
$config,
/* Illuminate\View\Factory */
$view,
OutputInterface $output = null,
$helpers = ''
) {
$this->config = $config;
$this->view = $view;
// Find the drivers to add to the extra/interfaces
$this->detectDrivers();
$this->extra = array_merge($this->extra, $this->config->get('ide-helper.extra'), []);
$this->magic = array_merge($this->magic, $this->config->get('ide-helper.magic'), []);
$this->interfaces = array_merge($this->interfaces, $this->config->get('ide-helper.interfaces'), []);
// Make all interface classes absolute
foreach ($this->interfaces as &$interface) {
$interface = '\\' . ltrim($interface, '\\');
}
$this->helpers = $helpers;
}
/**
* Generate the helper file contents;
*
* @return string;
*/
public function generate()
{
$app = app();
return $this->view->make('helper')
->with('namespaces_by_extends_ns', $this->getAliasesByExtendsNamespace())
->with('namespaces_by_alias_ns', $this->getAliasesByAliasNamespace())
->with('helpers', $this->helpers)
->with('version', $app->version())
->with('include_fluent', $this->config->get('ide-helper.include_fluent', true))
->with('factories', $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [])
->render();
}
protected function detectDrivers()
{
$defaultUserModel = config('auth.providers.users.model', config('auth.model', 'App\User'));
$this->interfaces['\Illuminate\Contracts\Auth\Authenticatable'] = $defaultUserModel;
try {
if (
class_exists('Auth') && is_a('Auth', '\Illuminate\Support\Facades\Auth', true)
&& app()->bound('auth')
) {
$class = get_class(\Auth::guard());
$this->extra['Auth'] = [$class];
$this->interfaces['\Illuminate\Auth\UserProviderInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('DB') && is_a('DB', '\Illuminate\Support\Facades\DB', true)) {
$class = get_class(\DB::connection());
$this->extra['DB'] = [$class];
$this->interfaces['\Illuminate\Database\ConnectionInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('Cache') && is_a('Cache', '\Illuminate\Support\Facades\Cache', true)) {
$driver = get_class(\Cache::driver());
$store = get_class(\Cache::getStore());
$this->extra['Cache'] = [$driver, $store];
$this->interfaces['\Illuminate\Cache\StoreInterface'] = $store;
}
} catch (\Exception $e) {
}
try {
if (class_exists('Queue') && is_a('Queue', '\Illuminate\Support\Facades\Queue', true)) {
$class = get_class(\Queue::connection());
$this->extra['Queue'] = [$class];
$this->interfaces['\Illuminate\Queue\QueueInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('SSH') && is_a('SSH', '\Illuminate\Support\Facades\SSH', true)) {
$class = get_class(\SSH::connection());
$this->extra['SSH'] = [$class];
$this->interfaces['\Illuminate\Remote\ConnectionInterface'] = $class;
}
} catch (\Exception $e) {
}
try {
if (class_exists('Storage') && is_a('Storage', '\Illuminate\Support\Facades\Storage', true)) {
$class = get_class(\Storage::disk());
$this->extra['Storage'] = [$class];
$this->interfaces['\Illuminate\Contracts\Filesystem\Filesystem'] = $class;
}
} catch (\Exception $e) {
}
}
/**
* Find all aliases that are valid for us to render
*
* @return Collection
*/
protected function getValidAliases()
{
$aliases = new Collection();
// Get all aliases
foreach ($this->getAliases() as $name => $facade) {
// Skip the Redis facade, if not available (otherwise Fatal PHP Error)
if ($facade == 'Illuminate\Support\Facades\Redis' && $name == 'Redis' && !class_exists('Predis\Client')) {
continue;
}
$magicMethods = array_key_exists($name, $this->magic) ? $this->magic[$name] : [];
$alias = new Alias($this->config, $name, $facade, $magicMethods, $this->interfaces);
if ($alias->isValid()) {
//Add extra methods, from other classes (magic static calls)
if (array_key_exists($name, $this->extra)) {
$alias->addClass($this->extra[$name]);
}
$aliases[] = $alias;
}
}
return $aliases;
}
/**
* Regroup aliases by namespace of extended classes
*
* @return Collection
*/
protected function getAliasesByExtendsNamespace()
{
$aliases = $this->getValidAliases();
$this->addMacroableClasses($aliases);
return $aliases->groupBy(function (Alias $alias) {
return $alias->getExtendsNamespace();
});
}
/**
* Regroup aliases by namespace of alias
*
* @return Collection
*/
protected function getAliasesByAliasNamespace()
{
return $this->getValidAliases()->groupBy(function (Alias $alias) {
return $alias->getNamespace();
});
}
protected function getAliases()
{
// For Laravel, use the AliasLoader
if (class_exists('Illuminate\Foundation\AliasLoader')) {
return AliasLoader::getInstance()->getAliases();
}
$facades = [
'App' => 'Illuminate\Support\Facades\App',
'Auth' => 'Illuminate\Support\Facades\Auth',
'Bus' => 'Illuminate\Support\Facades\Bus',
'DB' => 'Illuminate\Support\Facades\DB',
'Cache' => 'Illuminate\Support\Facades\Cache',
'Cookie' => 'Illuminate\Support\Facades\Cookie',
'Crypt' => 'Illuminate\Support\Facades\Crypt',
'Event' => 'Illuminate\Support\Facades\Event',
'Hash' => 'Illuminate\Support\Facades\Hash',
'Log' => 'Illuminate\Support\Facades\Log',
'Mail' => 'Illuminate\Support\Facades\Mail',
'Queue' => 'Illuminate\Support\Facades\Queue',
'Request' => 'Illuminate\Support\Facades\Request',
'Schema' => 'Illuminate\Support\Facades\Schema',
'Session' => 'Illuminate\Support\Facades\Session',
'Storage' => 'Illuminate\Support\Facades\Storage',
'Validator' => 'Illuminate\Support\Facades\Validator',
'Gate' => 'Illuminate\Support\Facades\Gate',
];
$facades = array_merge($facades, $this->config->get('app.aliases', []));
// Only return the ones that actually exist
return array_filter(
$facades,
function ($alias) {
return class_exists($alias);
},
ARRAY_FILTER_USE_KEY
);
}
/**
* Write a string as error output.
*
* @param string $string
* @return void
*/
protected function error($string)
{
if ($this->output) {
$this->output->writeln("<error>$string</error>");
} else {
echo $string . "\r\n";
}
}
/**
* Add all macroable classes which are not already loaded as an alias and have defined macros.
*
* @param Collection $aliases
*/
protected function addMacroableClasses(Collection $aliases)
{
$macroable = $this->getMacroableClasses($aliases);
foreach ($macroable as $class) {
$reflection = new ReflectionClass($class);
if (!$reflection->getStaticProperties()['macros']) {
continue;
}
$aliases[] = new Alias($this->config, $class, $class, [], $this->interfaces);
}
}
/**
* Get all loaded macroable classes which are not loaded as an alias.
*
* @param Collection $aliases
* @return Collection
*/
protected function getMacroableClasses(Collection $aliases)
{
return (new Collection(get_declared_classes()))
->filter(function ($class) {
$reflection = new ReflectionClass($class);
// Filter out internal classes and class aliases
return !$reflection->isInternal() && $reflection->getName() === $class;
})
->filter(function ($class) {
$traits = class_uses_recursive($class);
// Filter only classes with the macroable trait
return isset($traits[Macroable::class]);
})
->filter(function ($class) use ($aliases) {
$class = Str::start($class, '\\');
// Filter out aliases
return !$aliases->first(function (Alias $alias) use ($class) {
return $alias->getExtends() === $class;
});
});
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\LaravelIdeHelper\Console\EloquentCommand;
use Barryvdh\LaravelIdeHelper\Console\GeneratorCommand;
use Barryvdh\LaravelIdeHelper\Console\MetaCommand;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Listeners\GenerateModelHelper;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Database\Events\MigrationsEnded;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Engines\EngineResolver;
use Illuminate\View\Engines\PhpEngine;
use Illuminate\View\Factory;
use Illuminate\View\FileViewFinder;
class IdeHelperServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
* Bootstrap the application events.
*
* @return void
*/
public function boot()
{
if (!$this->app->runningUnitTests() && $this->app['config']->get('ide-helper.post_migrate', [])) {
$this->app['events']->listen(CommandFinished::class, GenerateModelHelper::class);
$this->app['events']->listen(MigrationsEnded::class, function () {
GenerateModelHelper::$shouldRun = true;
});
}
if ($this->app->has('view')) {
$viewPath = __DIR__ . '/../resources/views';
$this->loadViewsFrom($viewPath, 'ide-helper');
}
$configPath = __DIR__ . '/../config/ide-helper.php';
if (function_exists('config_path')) {
$publishPath = config_path('ide-helper.php');
} else {
$publishPath = base_path('config/ide-helper.php');
}
$this->publishes([$configPath => $publishPath], 'config');
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$configPath = __DIR__ . '/../config/ide-helper.php';
$this->mergeConfigFrom($configPath, 'ide-helper');
$localViewFactory = $this->createLocalViewFactory();
$this->app->singleton(
'command.ide-helper.generate',
function ($app) use ($localViewFactory) {
return new GeneratorCommand($app['config'], $app['files'], $localViewFactory);
}
);
$this->app->singleton(
'command.ide-helper.models',
function ($app) {
return new ModelsCommand($app['files']);
}
);
$this->app->singleton(
'command.ide-helper.meta',
function ($app) use ($localViewFactory) {
return new MetaCommand($app['files'], $localViewFactory, $app['config']);
}
);
$this->app->singleton(
'command.ide-helper.eloquent',
function ($app) {
return new EloquentCommand($app['files']);
}
);
$this->commands(
'command.ide-helper.generate',
'command.ide-helper.models',
'command.ide-helper.meta',
'command.ide-helper.eloquent'
);
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['command.ide-helper.generate', 'command.ide-helper.models'];
}
/**
* @return Factory
*/
private function createLocalViewFactory()
{
$resolver = new EngineResolver();
$resolver->register('php', function () {
return new PhpEngine($this->app['files']);
});
$finder = new FileViewFinder($this->app['files'], [__DIR__ . '/../resources/views']);
$factory = new Factory($resolver, $finder, $this->app['events']);
$factory->addExtension('php', 'php');
return $factory;
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Barryvdh\LaravelIdeHelper\Listeners;
use Illuminate\Console\Events\CommandFinished;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Contracts\Console\Kernel as Artisan;
class GenerateModelHelper
{
/**
* Tracks whether we should run the models command on the CommandFinished event or not.
* Set to true by the MigrationsEnded event, needs to be cleared before artisan call to prevent infinite loop.
*
* @var bool
*/
public static $shouldRun = false;
/** @var \Illuminate\Contracts\Console\Kernel */
protected $artisan;
/** @var \Illuminate\Contracts\Config\Repository */
protected $config;
/**
* @param \Illuminate\Contracts\Console\Kernel $artisan
* @param \Illuminate\Contracts\Config\Repository $config
*/
public function __construct(Artisan $artisan, Config $config)
{
$this->artisan = $artisan;
$this->config = $config;
}
/**
* Handle the event.
*
* @param CommandFinished $event
*/
public function handle(CommandFinished $event)
{
if (!self::$shouldRun) {
return;
}
self::$shouldRun = false;
foreach ($this->config->get('ide-helper.post_migrate', []) as $command) {
$this->artisan->call($command, [], $event->output);
}
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Tag;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\Collection;
class Macro extends Method
{
/**
* Macro constructor.
*
* @param \ReflectionFunctionAbstract $method
* @param string $alias
* @param \ReflectionClass $class
* @param null $methodName
* @param array $interfaces
* @param array $classAliases
*/
public function __construct(
$method,
$alias,
$class,
$methodName = null,
$interfaces = [],
$classAliases = []
) {
parent::__construct($method, $alias, $class, $methodName, $interfaces, $classAliases);
}
/**
* @param \ReflectionFunctionAbstract $method
*/
protected function initPhpDoc($method)
{
$this->phpdoc = new DocBlock($method);
$this->addLocationToPhpDoc();
// Add macro parameters if they are missed in original docblock
if (!$this->phpdoc->hasTag('param')) {
foreach ($method->getParameters() as $parameter) {
$reflectionType = $parameter->getType();
$type = $this->concatReflectionTypes($reflectionType);
/** @psalm-suppress UndefinedClass */
if ($reflectionType && !$reflectionType instanceof \ReflectionUnionType && $reflectionType->allowsNull()) {
$type .= '|null';
}
$type = $type ?: 'mixed';
$name = $parameter->isVariadic() ? '...' : '';
$name .= '$' . $parameter->getName();
$this->phpdoc->appendTag(Tag::createInstance("@param {$type} {$name}"));
}
}
// Add macro return type if it missed in original docblock
if ($method->hasReturnType() && !$this->phpdoc->hasTag('return')) {
$builder = EloquentBuilder::class;
$return = $method->getReturnType();
$type = $this->concatReflectionTypes($return);
/** @psalm-suppress UndefinedClass */
if (!$return instanceof \ReflectionUnionType) {
$type .= $this->root === "\\{$builder}" && $return->getName() === $builder ? '|static' : '';
$type .= $return->allowsNull() ? '|null' : '';
}
$this->phpdoc->appendTag(Tag::createInstance("@return {$type}"));
}
}
protected function concatReflectionTypes(?\ReflectionType $type): string
{
/** @psalm-suppress UndefinedClass */
$returnTypes = $type instanceof \ReflectionUnionType
? $type->getTypes()
: [$type];
return Collection::make($returnTypes)
->filter()
->map->getName()
->implode('|');
}
protected function addLocationToPhpDoc()
{
if ($this->method->name === '__invoke') {
$enclosingClass = $this->method->getDeclaringClass();
} else {
$enclosingClass = $this->method->getClosureScopeClass();
}
if (!$enclosingClass) {
return;
}
/** @var \ReflectionMethod $enclosingMethod */
$enclosingMethod = Collection::make($enclosingClass->getMethods())
->first(function (\ReflectionMethod $method) {
return $method->getStartLine() <= $this->method->getStartLine()
&& $method->getEndLine() >= $this->method->getEndLine();
});
if ($enclosingMethod) {
$this->phpdoc->appendTag(Tag::createInstance(
'@see \\' . $enclosingClass->getName() . '::' . $enclosingMethod->getName() . '()'
));
}
}
/**
* @param \ReflectionFunctionAbstract $method
* @param \ReflectionClass $class
*/
protected function initClassDefinedProperties($method, \ReflectionClass $class)
{
$this->namespace = $class->getNamespaceName();
$this->declaringClassName = '\\' . ltrim($class->name, '\\');
}
}

View File

@@ -0,0 +1,379 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use Barryvdh\Reflection\DocBlock;
use Barryvdh\Reflection\DocBlock\Context;
use Barryvdh\Reflection\DocBlock\Serializer as DocBlockSerializer;
use Barryvdh\Reflection\DocBlock\Tag;
use Barryvdh\Reflection\DocBlock\Tag\ParamTag;
use Barryvdh\Reflection\DocBlock\Tag\ReturnTag;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Str;
class Method
{
/** @var \Barryvdh\Reflection\DocBlock */
protected $phpdoc;
/** @var \ReflectionMethod */
protected $method;
protected $output = '';
protected $declaringClassName;
protected $name;
protected $namespace;
protected $params = [];
protected $params_with_default = [];
protected $interfaces = [];
protected $real_name;
protected $return = null;
protected $root;
protected $classAliases;
/**
* @param \ReflectionMethod|\ReflectionFunctionAbstract $method
* @param string $alias
* @param \ReflectionClass $class
* @param string|null $methodName
* @param array $interfaces
* @param array $classAliases
*/
public function __construct($method, $alias, $class, $methodName = null, $interfaces = [], array $classAliases = [])
{
$this->method = $method;
$this->interfaces = $interfaces;
$this->classAliases = $classAliases;
$this->name = $methodName ?: $method->name;
$this->real_name = $method->isClosure() ? $this->name : $method->name;
$this->initClassDefinedProperties($method, $class);
//Reference the 'real' function in the declaring class
$this->root = '\\' . ltrim($method->name === '__invoke' ? $method->getDeclaringClass()->getName() : $class->getName(), '\\');
//Create a DocBlock and serializer instance
$this->initPhpDoc($method);
//Normalize the description and inherit the docs from parents/interfaces
try {
$this->normalizeParams($this->phpdoc);
$this->normalizeReturn($this->phpdoc);
$this->normalizeDescription($this->phpdoc);
} catch (\Exception $e) {
}
//Get the parameters, including formatted default values
$this->getParameters($method);
//Make the method static
$this->phpdoc->appendTag(Tag::createInstance('@static', $this->phpdoc));
}
/**
* @param \ReflectionMethod $method
*/
protected function initPhpDoc($method)
{
$this->phpdoc = new DocBlock($method, new Context($this->namespace, $this->classAliases));
}
/**
* @param \ReflectionMethod $method
* @param \ReflectionClass $class
*/
protected function initClassDefinedProperties($method, \ReflectionClass $class)
{
$declaringClass = $method->getDeclaringClass();
$this->namespace = $declaringClass->getNamespaceName();
$this->declaringClassName = '\\' . ltrim($declaringClass->name, '\\');
}
/**
* Get the class wherein the function resides
*
* @return string
*/
public function getDeclaringClass()
{
return $this->declaringClassName;
}
/**
* Return the class from which this function would be called
*
* @return string
*/
public function getRoot()
{
return $this->root;
}
/**
* @return bool
*/
public function isInstanceCall()
{
return !($this->method->isClosure() || $this->method->isStatic());
}
/**
* @return string
*/
public function getRootMethodCall()
{
if ($this->isInstanceCall()) {
return "\$instance->{$this->getRealName()}({$this->getParams()})";
} else {
return "{$this->getRoot()}::{$this->getRealName()}({$this->getParams()})";
}
}
/**
* Get the docblock for this method
*
* @param string $prefix
* @return mixed
*/
public function getDocComment($prefix = "\t\t")
{
$serializer = new DocBlockSerializer(1, $prefix);
return $serializer->getDocComment($this->phpdoc);
}
/**
* Get the method name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get the real method name
*
* @return string
*/
public function getRealName()
{
return $this->real_name;
}
/**
* Get the parameters for this method
*
* @param bool $implode Wether to implode the array or not
* @return string
*/
public function getParams($implode = true)
{
return $implode ? implode(', ', $this->params) : $this->params;
}
/**
* Get the parameters for this method including default values
*
* @param bool $implode Wether to implode the array or not
* @return string
*/
public function getParamsWithDefault($implode = true)
{
return $implode ? implode(', ', $this->params_with_default) : $this->params_with_default;
}
/**
* Get the description and get the inherited docs.
*
* @param DocBlock $phpdoc
*/
protected function normalizeDescription(DocBlock $phpdoc)
{
//Get the short + long description from the DocBlock
$description = $phpdoc->getText();
//Loop through parents/interfaces, to fill in {@inheritdoc}
if (strpos($description, '{@inheritdoc}') !== false) {
$inheritdoc = $this->getInheritDoc($this->method);
$inheritDescription = $inheritdoc->getText();
$description = str_replace('{@inheritdoc}', $inheritDescription, $description);
$phpdoc->setText($description);
$this->normalizeParams($inheritdoc);
$this->normalizeReturn($inheritdoc);
//Add the tags that are inherited
$inheritTags = $inheritdoc->getTags();
if ($inheritTags) {
/** @var Tag $tag */
foreach ($inheritTags as $tag) {
$tag->setDocBlock();
$phpdoc->appendTag($tag);
}
}
}
}
/**
* Normalize the parameters
*
* @param DocBlock $phpdoc
*/
protected function normalizeParams(DocBlock $phpdoc)
{
//Get the return type and adjust them for beter autocomplete
$paramTags = $phpdoc->getTagsByName('param');
if ($paramTags) {
/** @var ParamTag $tag */
foreach ($paramTags as $tag) {
// Convert the keywords
$content = $this->convertKeywords($tag->getContent());
$tag->setContent($content);
// Get the expanded type and re-set the content
$content = $tag->getType() . ' ' . $tag->getVariableName() . ' ' . $tag->getDescription();
$tag->setContent(trim($content));
}
}
}
/**
* Normalize the return tag (make full namespace, replace interfaces)
*
* @param DocBlock $phpdoc
*/
protected function normalizeReturn(DocBlock $phpdoc)
{
//Get the return type and adjust them for better autocomplete
$returnTags = $phpdoc->getTagsByName('return');
if (count($returnTags) === 0) {
$this->return = null;
return;
}
/** @var ReturnTag $tag */
$tag = reset($returnTags);
// Get the expanded type
$returnValue = $tag->getType();
// Replace the interfaces
foreach ($this->interfaces as $interface => $real) {
$returnValue = str_replace($interface, $real, $returnValue);
}
// Set the changed content
$tag->setContent($returnValue . ' ' . $tag->getDescription());
$this->return = $returnValue;
if ($tag->getType() === '$this') {
Str::contains($this->root, Builder::class)
? $tag->setType($this->root . '|static')
: $tag->setType($this->root);
}
}
/**
* Convert keywords that are incorrect.
*
* @param string $string
* @return string
*/
protected function convertKeywords($string)
{
$string = str_replace('\Closure', 'Closure', $string);
$string = str_replace('Closure', '\Closure', $string);
$string = str_replace('dynamic', 'mixed', $string);
return $string;
}
/**
* Should the function return a value?
*
* @return bool
*/
public function shouldReturn()
{
if ($this->return !== 'void' && $this->method->name !== '__construct') {
return true;
}
return false;
}
/**
* Get the parameters and format them correctly
*
* @param \ReflectionMethod $method
* @return void
*/
public function getParameters($method)
{
//Loop through the default values for parameters, and make the correct output string
$params = [];
$paramsWithDefault = [];
foreach ($method->getParameters() as $param) {
$paramStr = $param->isVariadic() ? '...$' . $param->getName() : '$' . $param->getName();
$params[] = $paramStr;
if ($param->isOptional() && !$param->isVariadic()) {
$default = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
if (is_bool($default)) {
$default = $default ? 'true' : 'false';
} elseif (is_array($default)) {
$default = '[]';
} elseif (is_null($default)) {
$default = 'null';
} elseif (is_int($default)) {
//$default = $default;
} elseif (is_resource($default)) {
//skip to not fail
} else {
$default = var_export($default, true);
}
$paramStr .= " = $default";
}
$paramsWithDefault[] = $paramStr;
}
$this->params = $params;
$this->params_with_default = $paramsWithDefault;
}
/**
* @param \ReflectionMethod $reflectionMethod
* @return DocBlock
*/
protected function getInheritDoc($reflectionMethod)
{
$parentClass = $reflectionMethod->getDeclaringClass()->getParentClass();
//Get either a parent or the interface
if ($parentClass) {
$method = $parentClass->getMethod($reflectionMethod->getName());
} else {
$method = $reflectionMethod->getPrototype();
}
if ($method) {
$namespace = $method->getDeclaringClass()->getNamespaceName();
$phpdoc = new DocBlock($method, new Context($namespace, $this->classAliases));
if (strpos($phpdoc->getText(), '{@inheritdoc}') !== false) {
//Not at the end yet, try another parent/interface..
return $this->getInheritDoc($method);
}
return $phpdoc;
}
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* Laravel IDE Helper Generator
*
* @author Barry vd. Heuvel <barryvdh@gmail.com>
* @copyright 2014 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/barryvdh/laravel-ide-helper
*/
namespace Barryvdh\LaravelIdeHelper;
use PhpParser\Node\Stmt\GroupUse;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Use_;
use PhpParser\Node\Stmt\UseUse;
use PhpParser\ParserFactory;
class UsesResolver
{
/**
* @param string $classFQN
* @return array
*/
public function loadFromClass(string $classFQN): array
{
return $this->loadFromFile(
$classFQN,
(new \ReflectionClass($classFQN))->getFileName()
);
}
/**
* @param string $classFQN
* @param string $filename
* @return array
*/
public function loadFromFile(string $classFQN, string $filename): array
{
return $this->loadFromCode(
$classFQN,
file_get_contents(
$filename
)
);
}
/**
* @param string $classFQN
* @param string $code
* @return array
*/
public function loadFromCode(string $classFQN, string $code): array
{
$classFQN = ltrim($classFQN, '\\');
$namespace = rtrim(
preg_replace(
'/([^\\\\]+)$/',
'',
$classFQN
),
'\\'
);
$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
$namespaceData = null;
foreach ($parser->parse($code) as $node) {
if ($node instanceof Namespace_ && $node->name->toCodeString() === $namespace) {
$namespaceData = $node;
break;
}
}
if ($namespaceData === null) {
return [];
}
/** @var Namespace_ $namespaceData */
$aliases = [];
foreach ($namespaceData->stmts as $stmt) {
if ($stmt instanceof Use_) {
if ($stmt->type !== Use_::TYPE_NORMAL) {
continue;
}
foreach ($stmt->uses as $use) {
/** @var UseUse $use */
$alias = $use->alias ?
$use->alias->name :
self::classBasename($use->name->toCodeString());
$aliases[$alias] = '\\' . $use->name->toCodeString();
}
} elseif ($stmt instanceof GroupUse) {
foreach ($stmt->uses as $use) {
/** @var UseUse $use */
$alias = $use->alias ?
$use->alias->name :
self::classBasename($use->name->toCodeString());
$aliases[$alias] = '\\' . $stmt->prefix->toCodeString() . '\\' . $use->name->toCodeString();
}
}
}
return $aliases;
}
/**
* @param string $classFQN
* @return string
*/
protected static function classBasename(string $classFQN): string
{
return preg_replace('/^.*\\\\([^\\\\]+)$/', '$1', $classFQN);
}
}

Some files were not shown because too many files have changed in this diff Show More