diff --git a/composer.json b/composer.json
index 1b439753a..021026603 100755
--- a/composer.json
+++ b/composer.json
@@ -13,14 +13,27 @@
"php": ">=8.4.23",
"d11wtq/boris": "~1.0",
"filp/whoops": "~2.11",
+ "illuminate/bus": "^13",
+ "illuminate/cache": "^13",
"illuminate/collections": "^13",
"illuminate/conditionable": "^13",
"illuminate/container": "^13",
"illuminate/contracts": "^13",
+ "illuminate/cookie": "^13",
+ "illuminate/database": "^13",
+ "illuminate/encryption": "^13",
+ "illuminate/events": "^13",
+ "illuminate/filesystem": "^13",
+ "illuminate/http": "^13",
"illuminate/macroable": "^13",
+ "illuminate/pagination": "^13",
+ "illuminate/pipeline": "^13",
+ "illuminate/redis": "^13",
"illuminate/reflection": "^13",
+ "illuminate/session": "^13",
+ "illuminate/support": "^13",
"ircmaxell/password-compat": "~1.0",
- "laravel/serializable-closure": "^1.2",
+ "laravel/serializable-closure": "^2.0.10",
"monolog/monolog": "^3.10",
"nesbot/carbon": "^3.8.4",
"opis/closure": "~3.6",
@@ -44,27 +57,16 @@
},
"replace": {
"illuminate/auth": "self.version",
- "illuminate/cache": "self.version",
"illuminate/config": "self.version",
"illuminate/console": "self.version",
- "illuminate/cookie": "self.version",
- "illuminate/database": "self.version",
- "illuminate/encryption": "self.version",
- "illuminate/events": "self.version",
"illuminate/exception": "self.version",
- "illuminate/filesystem": "self.version",
"illuminate/foundation": "self.version",
"illuminate/hashing": "self.version",
- "illuminate/http": "self.version",
"illuminate/html": "self.version",
"illuminate/log": "self.version",
"illuminate/mail": "self.version",
- "illuminate/pagination": "self.version",
"illuminate/queue": "self.version",
- "illuminate/redis": "self.version",
"illuminate/routing": "self.version",
- "illuminate/session": "self.version",
- "illuminate/support": "self.version",
"illuminate/translation": "self.version",
"illuminate/validation": "self.version",
"illuminate/view": "self.version",
diff --git a/src/Illuminate/Auth/AuthManager.php b/src/Illuminate/Auth/AuthManager.php
index 63798eb33..8e331392f 100755
--- a/src/Illuminate/Auth/AuthManager.php
+++ b/src/Illuminate/Auth/AuthManager.php
@@ -18,11 +18,11 @@ protected function createDriver($driver)
// When using the remember me functionality of the authentication services we
// will need to be set the encryption instance of the guard, which allows
// secure, encrypted cookie values to get generated for those cookies.
- $guard->setCookieJar($this->app['cookie']);
+ $guard->setCookieJar($this->container['cookie']);
- $guard->setDispatcher($this->app['events']);
+ $guard->setDispatcher($this->container['events']);
- return $guard->setRequest($this->app->refresh('request', $guard, 'setRequest'));
+ return $guard->setRequest($this->container->refresh('request', $guard, 'setRequest'));
}
/**
@@ -38,7 +38,7 @@ protected function callCustomCreator($driver)
if ($custom instanceof Guard) return $custom;
- return new Guard($custom, $this->app['session.store']);
+ return new Guard($custom, $this->container['session.store']);
}
/**
@@ -50,7 +50,7 @@ public function createDatabaseDriver()
{
$provider = $this->createDatabaseProvider();
- return new Guard($provider, $this->app['session.store']);
+ return new Guard($provider, $this->container['session.store']);
}
/**
@@ -60,14 +60,14 @@ public function createDatabaseDriver()
*/
protected function createDatabaseProvider()
{
- $connection = $this->app['db']->connection();
+ $connection = $this->container['db']->connection();
// When using the basic database user provider, we need to inject the table we
// want to use, since this is not an Eloquent model we will have no way to
// know without telling the provider, so we'll inject the config value.
- $table = $this->app['config']['auth.table'];
+ $table = $this->container['config']['auth.table'];
- return new DatabaseUserProvider($connection, $this->app['hash'], $table);
+ return new DatabaseUserProvider($connection, $this->container['hash'], $table);
}
/**
@@ -79,7 +79,7 @@ public function createEloquentDriver()
{
$provider = $this->createEloquentProvider();
- return new Guard($provider, $this->app['session.store']);
+ return new Guard($provider, $this->container['session.store']);
}
/**
@@ -89,9 +89,9 @@ public function createEloquentDriver()
*/
protected function createEloquentProvider()
{
- $model = $this->app['config']['auth.model'];
+ $model = $this->container['config']['auth.model'];
- return new EloquentUserProvider($this->app['hash'], $model);
+ return new EloquentUserProvider($this->container['hash'], $model);
}
/**
@@ -101,7 +101,7 @@ protected function createEloquentProvider()
*/
public function getDefaultDriver()
{
- return $this->app['config']['auth.driver'];
+ return $this->container['config']['auth.driver'];
}
/**
@@ -112,7 +112,7 @@ public function getDefaultDriver()
*/
public function setDefaultDriver($name)
{
- $this->app['config']['auth.driver'] = $name;
+ $this->container['config']['auth.driver'] = $name;
}
}
diff --git a/src/Illuminate/Console/Application.php b/src/Illuminate/Console/Application.php
index 23cc4cd0c..a0cd590f7 100755
--- a/src/Illuminate/Console/Application.php
+++ b/src/Illuminate/Console/Application.php
@@ -22,6 +22,27 @@ class Application extends \Symfony\Component\Console\Application {
*/
protected $laravel;
+ /**
+ * Callbacks to run when a console application is starting.
+ *
+ * ponytail: BC shim for v13 Support\ServiceProvider::commands(), which calls
+ * Illuminate\Console\Application::starting(). Remove when console swaps to v13 (task 4.2/4.3).
+ *
+ * @var callable[]
+ */
+ protected static $startingCallbacks = array();
+
+ /**
+ * Register a callback to run when the console application is starting.
+ *
+ * @param callable $callback
+ * @return void
+ */
+ public static function starting($callback)
+ {
+ static::$startingCallbacks[] = $callback;
+ }
+
/**
* Create and boot a new Console application.
*
@@ -51,6 +72,11 @@ public static function make($app)
$app->instance('artisan', $console);
+ foreach (static::$startingCallbacks as $callback)
+ {
+ $callback($console);
+ }
+
return $console;
}
@@ -153,7 +179,19 @@ public function resolveCommands($commands)
foreach ($commands as $command)
{
- $this->resolve($command);
+ try
+ {
+ $this->resolve($command);
+ }
+ catch (\Throwable $e)
+ {
+ // ponytail: some v13 components (session/cache/…) register console commands
+ // that extend v13 console base classes absent from the not-yet-swapped fork
+ // console. Skip the ones that can't load so artisan still boots; they return
+ // with the console swap (task 4.2). Commands that load fine still register.
+ error_log('[l13] skipped unresolvable console command '
+ . (is_string($command) ? $command : gettype($command)) . ': ' . $e->getMessage());
+ }
}
}
diff --git a/src/Illuminate/Console/Command.php b/src/Illuminate/Console/Command.php
index c81337b43..3809075c0 100755
--- a/src/Illuminate/Console/Command.php
+++ b/src/Illuminate/Console/Command.php
@@ -63,6 +63,19 @@ public function __construct()
$this->specifyParameters();
}
+ /**
+ * ponytail: BC shim — exists so v13 component commands that declare
+ * `#[\Override] configureDefaults()` (against the v13 console Command) can load under
+ * the not-yet-swapped fork console. The fork configures via the constructor /
+ * specifyParameters() instead, so this is a no-op. Remove at the console swap (task 4.2).
+ *
+ * @return void
+ */
+ protected function configureDefaults()
+ {
+ //
+ }
+
/**
* Specify the arguments and options on the command.
*
diff --git a/src/Illuminate/Console/MigrationGeneratorCommand.php b/src/Illuminate/Console/MigrationGeneratorCommand.php
new file mode 100644
index 000000000..187c11863
--- /dev/null
+++ b/src/Illuminate/Console/MigrationGeneratorCommand.php
@@ -0,0 +1,39 @@
+error('make:*-table generators require the v13 console (L13 migration task 4.2).');
+ }
+
+ return 1;
+ }
+}
diff --git a/src/Illuminate/Console/Prohibitable.php b/src/Illuminate/Console/Prohibitable.php
new file mode 100644
index 000000000..e706dbe6e
--- /dev/null
+++ b/src/Illuminate/Console/Prohibitable.php
@@ -0,0 +1,45 @@
+components->error('This command is prohibited from running in this environment.');
+ }
+
+ return true;
+ }
+}
diff --git a/src/Illuminate/Foundation/Application.php b/src/Illuminate/Foundation/Application.php
index 784676e19..b5f251335 100755
--- a/src/Illuminate/Foundation/Application.php
+++ b/src/Illuminate/Foundation/Application.php
@@ -203,6 +203,20 @@ public function bindInstallPaths(array $paths)
}
}
+ /**
+ * Get the path to the resources directory.
+ *
+ * ponytail: v13 ServiceProviders (e.g. PaginationServiceProvider) call resourcePath();
+ * the L4.2 fork Application lacks it. Remove once Foundation swaps to v13.
+ *
+ * @param string $path
+ * @return string
+ */
+ public function resourcePath($path = '')
+ {
+ return $this['path.base'].DIRECTORY_SEPARATOR.'resources'.($path != '' ? DIRECTORY_SEPARATOR.$path : '');
+ }
+
/**
* Get the application bootstrap file.
*
@@ -441,7 +455,12 @@ public function registerDeferredProvider($provider, $service = null)
{
$this->booting(function() use ($instance)
{
- $instance->boot();
+ // v13 ServiceProvider has no default boot(); call only when defined
+ // (mirrors the eager boot() loop). Via the container so boot() DI works.
+ if (method_exists($instance, 'boot'))
+ {
+ $this->call([$instance, 'boot']);
+ }
});
}
}
@@ -635,7 +654,11 @@ public function boot()
{
if ($this->booted) return;
- array_walk($this->serviceProviders, function($p) { $p->boot(); });
+ array_walk($this->serviceProviders, function($p) {
+ // v13 ServiceProvider has no default boot(); call only when defined (via
+ // the container so boot() method-injection keeps working).
+ if (method_exists($p, 'boot')) $this->call([$p, 'boot']);
+ });
$this->bootApplication();
}
@@ -1176,11 +1199,10 @@ public function registerCoreContainerAliases()
'translator' => 'Illuminate\Translation\Translator',
'log' => 'Illuminate\Log\Logger',
'mailer' => 'Illuminate\Mail\Mailer',
- 'paginator' => 'Illuminate\Pagination\Factory',
'auth.reminder' => 'Illuminate\Auth\Reminders\PasswordBroker',
'queue' => 'Illuminate\Queue\QueueManager',
'redirect' => 'Illuminate\Routing\Redirector',
- 'redis' => 'Illuminate\Redis\Database',
+ 'redis' => 'Illuminate\Redis\RedisManager',
'request' => 'Illuminate\Http\Request',
'router' => 'Illuminate\Routing\Router',
'session' => 'Illuminate\Session\SessionManager',
@@ -1205,6 +1227,22 @@ public function registerCoreContainerAliases()
// BC: Hashing\HasherInterface → Contracts\Hashing\Hasher (task 2.11); keep old name resolvable.
// class_alias covers use/typehint/instanceof; make()/autowiring by the old name needs this.
$this->alias('hash', 'Illuminate\Hashing\HasherInterface');
+
+ // L13 SCC-1 swap (task 4.1): the swapped components ship v13 contracts. Alias them to
+ // the core bindings so v13 code that type-hints the contracts resolves (the v13
+ // providers don't always register these against the fork's core aliases).
+ $this->alias('events', 'Illuminate\Contracts\Events\Dispatcher');
+ $this->alias('redis', 'Illuminate\Contracts\Redis\Factory');
+ $this->alias('cache', 'Illuminate\Contracts\Cache\Factory');
+ $this->alias('cache.store', 'Illuminate\Contracts\Cache\Repository');
+ $this->alias('config', 'Illuminate\Contracts\Config\Repository');
+ $this->alias('db', 'Illuminate\Database\ConnectionResolverInterface');
+
+ // ponytail: v13's Support\Facades\Artisan resolves Illuminate\Contracts\Console\Kernel.
+ // The fork has no console Kernel (task 4.2); 'artisan' is a lazy singleton
+ // (ArtisanServiceProvider), so alias the contract to it globally — works for the
+ // Artisan facade in web/console/tests (make()-only aliasing missed Artisan::call()).
+ $this->alias('artisan', 'Illuminate\Contracts\Console\Kernel');
}
}
diff --git a/src/Illuminate/Html/HtmlServiceProvider.php b/src/Illuminate/Html/HtmlServiceProvider.php
index 0c1f24138..7944b486a 100755
--- a/src/Illuminate/Html/HtmlServiceProvider.php
+++ b/src/Illuminate/Html/HtmlServiceProvider.php
@@ -45,7 +45,7 @@ protected function registerFormBuilder()
{
$this->app->singleton('form', function($app)
{
- $form = new FormBuilder($app['html'], $app['url'], $app['session.store']->getToken());
+ $form = new FormBuilder($app['html'], $app['url'], $app['session.store']->token());
return $form->setSessionStore($app['session.store']);
});
diff --git a/src/Illuminate/Mail/MailServiceProvider.php b/src/Illuminate/Mail/MailServiceProvider.php
index 396fab307..7ffda452c 100755
--- a/src/Illuminate/Mail/MailServiceProvider.php
+++ b/src/Illuminate/Mail/MailServiceProvider.php
@@ -59,6 +59,10 @@ public function register(): void
return $mailer;
});
+
+ // ponytail: v13 Support\Facades\Mail resolves 'mail.manager'; fork Mail is unswapped and
+ // binds 'mailer'. Alias so Mail::send() works. Remove when Mail swaps to illuminate/mail:^13.
+ $this->app->alias('mailer', 'mail.manager');
}
/**
@@ -244,7 +248,7 @@ protected function registerLogTransport(array $config): void
#[\Override]
public function provides(): array
{
- return ['mailer', 'symfony.transport'];
+ return ['mailer', 'mail.manager', 'symfony.transport'];
}
}
diff --git a/src/Illuminate/Pagination/BootstrapPresenter.php b/src/Illuminate/Pagination/BootstrapPresenter.php
deleted file mode 100644
index dc9c7c24f..000000000
--- a/src/Illuminate/Pagination/BootstrapPresenter.php
+++ /dev/null
@@ -1,42 +0,0 @@
-'.$page.'';
- }
-
- /**
- * Get HTML wrapper for disabled text.
- *
- * @param string $text
- * @return string
- */
- public function getDisabledTextWrapper($text)
- {
- return '
'.$text.'';
- }
-
- /**
- * Get HTML wrapper for active text.
- *
- * @param string $text
- * @return string
- */
- public function getActivePageWrapper($text)
- {
- return ''.$text.'';
- }
-
-}
diff --git a/src/Illuminate/Pagination/Factory.php b/src/Illuminate/Pagination/Factory.php
deleted file mode 100755
index 43a707998..000000000
--- a/src/Illuminate/Pagination/Factory.php
+++ /dev/null
@@ -1,289 +0,0 @@
-view = $view;
- $this->trans = $trans;
- $this->request = $request;
- $this->pageName = $pageName;
- $this->setupPaginationEnvironment();
- }
-
- /**
- * Setup the pagination environment.
- *
- * @return void
- */
- protected function setupPaginationEnvironment()
- {
- $this->view->addNamespace('pagination', __DIR__.'/views');
- }
-
- /**
- * Get a new paginator instance.
- *
- * @param array $items
- * @param int $total
- * @param int|null $perPage
- * @return \Illuminate\Pagination\Paginator
- */
- public function make(array $items, $total, $perPage = null)
- {
- $paginator = new Paginator($this, $items, $total, $perPage);
-
- return $paginator->setupPaginationContext();
- }
-
- /**
- * Get the pagination view.
- *
- * @param \Illuminate\Pagination\Paginator $paginator
- * @param string $view
- * @return \Illuminate\View\View
- */
- public function getPaginationView(Paginator $paginator, $view = null)
- {
- $data = array('environment' => $this, 'paginator' => $paginator);
-
- return $this->view->make($this->getViewName($view), $data);
- }
-
- /**
- * Get the number of the current page.
- *
- * @return int
- */
- public function getCurrentPage()
- {
- $page = (int) $this->currentPage ?: $this->request->input($this->pageName, 1);
-
- if ($page < 1 || filter_var($page, FILTER_VALIDATE_INT) === false)
- {
- return 1;
- }
-
- return $page;
- }
-
- /**
- * Set the number of the current page.
- *
- * @param int $number
- * @return void
- */
- public function setCurrentPage($number)
- {
- $this->currentPage = $number;
- }
-
- /**
- * Get the root URL for the request.
- *
- * @return string
- */
- public function getCurrentUrl()
- {
- return $this->baseUrl ?: $this->request->url();
- }
-
- /**
- * Set the base URL in use by the paginator.
- *
- * @param string $baseUrl
- * @return void
- */
- public function setBaseUrl($baseUrl)
- {
- $this->baseUrl = $baseUrl;
- }
-
- /**
- * Set the input page parameter name used by the paginator.
- *
- * @param string $pageName
- * @return void
- */
- public function setPageName($pageName)
- {
- $this->pageName = $pageName;
- }
-
- /**
- * Get the input page parameter name used by the paginator.
- *
- * @return string
- */
- public function getPageName()
- {
- return $this->pageName;
- }
-
- /**
- * Get the name of the pagination view.
- *
- * @param string $view
- * @return string
- */
- public function getViewName($view = null)
- {
- if ( ! is_null($view)) return $view;
-
- return $this->viewName ?: 'pagination::slider';
- }
-
- /**
- * Set the name of the pagination view.
- *
- * @param string $viewName
- * @return void
- */
- public function setViewName($viewName)
- {
- $this->viewName = $viewName;
- }
-
- /**
- * Get the locale of the paginator.
- *
- * @return string
- */
- public function getLocale()
- {
- return $this->locale;
- }
-
- /**
- * Set the locale of the paginator.
- *
- * @param string $locale
- * @return void
- */
- public function setLocale($locale)
- {
- $this->locale = $locale;
- }
-
- /**
- * Get the active request instance.
- *
- * @return \Symfony\Component\HttpFoundation\Request
- */
- public function getRequest()
- {
- return $this->request;
- }
-
- /**
- * Set the active request instance.
- *
- * @param \Symfony\Component\HttpFoundation\Request $request
- * @return void
- */
- public function setRequest(Request $request)
- {
- $this->request = $request;
- }
-
- /**
- * Get the current view factory.
- *
- * @return \Illuminate\View\Factory
- */
- public function getViewFactory()
- {
- return $this->view;
- }
-
- /**
- * Set the current view factory.
- *
- * @param \Illuminate\View\Factory $view
- * @return void
- */
- public function setViewFactory(ViewFactory $view)
- {
- $this->view = $view;
- }
-
- /**
- * Get the translator instance.
- *
- * @return \Symfony\Contracts\Translation\TranslatorInterface
- */
- public function getTranslator()
- {
- return $this->trans;
- }
-
-}
diff --git a/src/Illuminate/Pagination/PaginationServiceProvider.php b/src/Illuminate/Pagination/PaginationServiceProvider.php
deleted file mode 100755
index 933e82ca4..000000000
--- a/src/Illuminate/Pagination/PaginationServiceProvider.php
+++ /dev/null
@@ -1,44 +0,0 @@
-app->singleton('paginator', function($app)
- {
- $paginator = new Factory($app['request'], $app['view'], $app['translator']);
-
- $paginator->setViewName($app['config']['view.pagination']);
-
- $app->refresh('request', $paginator, 'setRequest');
-
- return $paginator;
- });
- }
-
- /**
- * Get the services provided by the provider.
- *
- * @return array
- */
- #[\Override]
- public function provides()
- {
- return array('paginator');
- }
-
-}
diff --git a/src/Illuminate/Pagination/Paginator.php b/src/Illuminate/Pagination/Paginator.php
deleted file mode 100755
index 121ef27ef..000000000
--- a/src/Illuminate/Pagination/Paginator.php
+++ /dev/null
@@ -1,545 +0,0 @@
-factory = $factory;
-
- if (is_null($perPage))
- {
- $this->perPage = (int) $total;
- $this->hasMore = count($items) > $this->perPage;
- $this->items = array_slice($items, 0, $this->perPage);
- }
- else
- {
- $this->items = $items;
- $this->total = (int) $total;
- $this->perPage = (int) $perPage;
- }
- }
-
- /**
- * Setup the pagination context (current and last page).
- *
- * @return $this
- */
- public function setupPaginationContext()
- {
- $this->calculateCurrentAndLastPages();
-
- $this->calculateItemRanges();
-
- return $this;
- }
-
- /**
- * Calculate the current and last pages for this instance.
- *
- * @return void
- */
- protected function calculateCurrentAndLastPages()
- {
- if ($this->isQuickPaginating())
- {
- $this->currentPage = $this->factory->getCurrentPage();
-
- $this->lastPage = $this->hasMore ? $this->currentPage + 1 : $this->currentPage;
- }
- else
- {
- $this->lastPage = max((int) ceil($this->total / $this->perPage), 1);
-
- $this->currentPage = $this->calculateCurrentPage($this->lastPage);
- }
- }
-
- /**
- * Calculate the first and last item number for this instance.
- *
- * @return void
- */
- protected function calculateItemRanges()
- {
- $this->from = $this->total ? ($this->currentPage - 1) * $this->perPage + 1 : 0;
-
- $this->to = min($this->total, $this->currentPage * $this->perPage);
- }
-
- /**
- * Get the current page for the request.
- *
- * @param int $lastPage
- * @return int
- */
- protected function calculateCurrentPage($lastPage)
- {
- $page = $this->factory->getCurrentPage();
-
- // The page number will get validated and adjusted if it either less than one
- // or greater than the last page available based on the count of the given
- // items array. If it's greater than the last, we'll give back the last.
- if (is_numeric($page) && $page > $lastPage)
- {
- return $lastPage > 0 ? $lastPage : 1;
- }
-
- return $this->isValidPageNumber($page) ? (int) $page : 1;
- }
-
- /**
- * Determine if the given value is a valid page number.
- *
- * @param int $page
- * @return bool
- */
- protected function isValidPageNumber($page)
- {
- return $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false;
- }
-
- /**
- * Get the pagination links view.
- *
- * @param string $view
- * @return \Illuminate\View\View
- */
- public function links($view = null)
- {
- return $this->factory->getPaginationView($this, $view);
- }
-
- /**
- * Get a URL for a given page number.
- *
- * @param int $page
- * @return string
- */
- public function getUrl($page)
- {
- $parameters = array(
- $this->factory->getPageName() => $page,
- );
-
- // If we have any extra query string key / value pairs that need to be added
- // onto the URL, we will put them in query string form and then attach it
- // to the URL. This allows for extra information like sortings storage.
- if (count($this->query) > 0)
- {
- $parameters = array_merge($this->query, $parameters);
- }
-
- $fragment = $this->buildFragment();
-
- return $this->factory->getCurrentUrl().'?'.http_build_query($parameters, '', '&').$fragment;
- }
-
- /**
- * Get / set the URL fragment to be appended to URLs.
- *
- * @param string|null $fragment
- * @return $this|string
- */
- public function fragment($fragment = null)
- {
- if (is_null($fragment)) return $this->fragment;
-
- $this->fragment = $fragment;
-
- return $this;
- }
-
- /**
- * Build the full fragment portion of a URL.
- *
- * @return string
- */
- protected function buildFragment()
- {
- return $this->fragment ? '#'.$this->fragment : '';
- }
-
- /**
- * Add a query string value to the paginator.
- *
- * @param string $key
- * @param string $value
- * @return $this
- */
- public function appends($key, $value = null)
- {
- if (is_array($key)) return $this->appendArray($key);
-
- return $this->addQuery($key, $value);
- }
-
- /**
- * Add an array of query string values.
- *
- * @param array $keys
- * @return $this
- */
- protected function appendArray(array $keys)
- {
- foreach ($keys as $key => $value)
- {
- $this->addQuery($key, $value);
- }
-
- return $this;
- }
-
- /**
- * Add a query string value to the paginator.
- *
- * @param string $key
- * @param string $value
- * @return $this
- */
- public function addQuery($key, $value)
- {
- if ($key !== $this->factory->getPageName())
- {
- $this->query[$key] = $value;
- }
-
- return $this;
- }
-
- /**
- * Determine if the paginator is doing "quick" pagination.
- *
- * @return bool
- */
- public function isQuickPaginating()
- {
- return is_null($this->total);
- }
-
- /**
- * Get the current page for the request.
- *
- * @param int|null $total
- * @return int
- */
- public function currentPage($total = null)
- {
- if (is_null($total))
- {
- return $this->currentPage;
- }
-
- return min($this->currentPage, (int) ceil($total / $this->perPage));
- }
-
- /**
- * Get the last page that should be available.
- *
- * @return int
- */
- public function lastPage()
- {
- return $this->lastPage;
- }
-
- /**
- * Get the number of the first item on the paginator.
- *
- * @return int
- */
- public function firstItem()
- {
- return $this->from;
- }
-
- /**
- * Get the number of the last item on the paginator.
- *
- * @return int
- */
- public function lastItem()
- {
- return $this->to;
- }
-
- /**
- * Get the number of items to be displayed per page.
- *
- * @return int
- */
- public function perPage()
- {
- return $this->perPage;
- }
-
- /**
- * Get a collection instance containing the items.
- *
- * @return \Illuminate\Support\Collection
- */
- public function getCollection()
- {
- return new Collection($this->items);
- }
-
- /**
- * Get the items being paginated.
- *
- * @return array
- */
- public function items()
- {
- return $this->items;
- }
-
- /**
- * Set the items being paginated.
- *
- * @param mixed $items
- * @return void
- */
- public function setItems($items)
- {
- $this->items = $items;
- }
-
- /**
- * Get the total number of items in the collection.
- *
- * @return int
- */
- public function total()
- {
- return $this->total;
- }
-
- /**
- * Set the base URL in use by the paginator.
- *
- * @param string $baseUrl
- * @return void
- */
- public function setBaseUrl($baseUrl)
- {
- $this->factory->setBaseUrl($baseUrl);
- }
-
- /**
- * Get the pagination factory.
- *
- * @return \Illuminate\Pagination\Factory
- */
- public function getFactory()
- {
- return $this->factory;
- }
-
- /**
- * Get an iterator for the items.
- *
- * @return \ArrayIterator
- */
- public function getIterator(): Traversable
- {
- return new ArrayIterator($this->items);
- }
-
- /**
- * Determine if the list of items is empty or not.
- *
- * @return bool
- */
- public function isEmpty()
- {
- return empty($this->items);
- }
-
- /**
- * Get the number of items for the current page.
- *
- * @return int
- */
- public function count(): int
- {
- return count($this->items);
- }
-
- /**
- * Determine if the given item exists.
- *
- * @param mixed $key
- * @return bool
- */
- public function offsetExists($key): bool
- {
- return array_key_exists($key, $this->items);
- }
-
- /**
- * Get the item at the given offset.
- *
- * @param mixed $key
- * @return mixed
- */
- public function offsetGet($key): mixed
- {
- return $this->items[$key];
- }
-
- /**
- * Set the item at the given offset.
- *
- * @param mixed $key
- * @param mixed $value
- * @return void
- */
- public function offsetSet($key, $value): void
- {
- $this->items[$key] = $value;
- }
-
- /**
- * Unset the item at the given key.
- *
- * @param mixed $key
- * @return void
- */
- public function offsetUnset($key): void
- {
- unset($this->items[$key]);
- }
-
- /**
- * Get the instance as an array.
- *
- * @return array
- */
- public function toArray()
- {
- return array(
- 'total' => $this->total, 'per_page' => $this->perPage,
- 'current_page' => $this->currentPage, 'last_page' => $this->lastPage,
- 'from' => $this->from, 'to' => $this->to, 'data' => $this->getCollection()->toArray(),
- );
- }
-
- /**
- * Convert the object to its JSON representation.
- *
- * @param int $options
- * @return string
- */
- public function toJson($options = 0)
- {
- return json_encode($this->toArray(), $options);
- }
-
- /**
- * Call a method on the underlying Collection
- *
- * @param string $method
- * @param array $arguments
- * @return mixed
- */
- public function __call($method, $arguments)
- {
- return call_user_func_array(array($this->getCollection(), $method), $arguments);
- }
-
-}
diff --git a/src/Illuminate/Pagination/Presenter.php b/src/Illuminate/Pagination/Presenter.php
deleted file mode 100755
index 42a9eb789..000000000
--- a/src/Illuminate/Pagination/Presenter.php
+++ /dev/null
@@ -1,277 +0,0 @@
-paginator = $paginator;
- $this->lastPage = $this->paginator->lastPage();
- $this->currentPage = $this->paginator->currentPage();
- }
-
- /**
- * Get HTML wrapper for a page link.
- *
- * @param string $url
- * @param int $page
- * @param string $rel
- * @return string
- */
- abstract public function getPageLinkWrapper($url, $page, $rel = null);
-
- /**
- * Get HTML wrapper for disabled text.
- *
- * @param string $text
- * @return string
- */
- abstract public function getDisabledTextWrapper($text);
-
- /**
- * Get HTML wrapper for active text.
- *
- * @param string $text
- * @return string
- */
- abstract public function getActivePageWrapper($text);
-
- /**
- * Render the Pagination contents.
- *
- * @return string
- */
- public function render()
- {
- // The hard-coded thirteen represents the minimum number of pages we need to
- // be able to create a sliding page window. If we have less than that, we
- // will just render a simple range of page links insteadof the sliding.
- if ($this->lastPage < 13)
- {
- $content = $this->getPageRange(1, $this->lastPage);
- }
- else
- {
- $content = $this->getPageSlider();
- }
-
- return $this->getPrevious().$content.$this->getNext();
- }
-
- /**
- * Create a range of pagination links.
- *
- * @param int $start
- * @param int $end
- * @return string
- */
- public function getPageRange($start, $end)
- {
- $pages = array();
-
- for ($page = $start; $page <= $end; $page++)
- {
- // If the current page is equal to the page we're iterating on, we will create a
- // disabled link for that page. Otherwise, we can create a typical active one
- // for the link. We will use this implementing class's methods to get HTML.
- if ($this->currentPage == $page)
- {
- $pages[] = $this->getActivePageWrapper($page);
- }
- else
- {
- $pages[] = $this->getLink($page);
- }
- }
-
- return implode('', $pages);
- }
-
- /**
- * Create a pagination slider link window.
- *
- * @return string
- */
- protected function getPageSlider()
- {
- $window = 6;
-
- // If the current page is very close to the beginning of the page range, we will
- // just render the beginning of the page range, followed by the last 2 of the
- // links in this list, since we will not have room to create a full slider.
- if ($this->currentPage <= $window)
- {
- $ending = $this->getFinish();
-
- return $this->getPageRange(1, $window + 2).$ending;
- }
-
- // If the current page is close to the ending of the page range we will just get
- // this first couple pages, followed by a larger window of these ending pages
- // since we're too close to the end of the list to create a full on slider.
- elseif ($this->currentPage >= $this->lastPage - $window)
- {
- $start = $this->lastPage - 8;
-
- $content = $this->getPageRange($start, $this->lastPage);
-
- return $this->getStart().$content;
- }
-
- // If we have enough room on both sides of the current page to build a slider we
- // will surround it with both the beginning and ending caps, with this window
- // of pages in the middle providing a Google style sliding paginator setup.
- else
- {
- $content = $this->getAdjacentRange();
-
- return $this->getStart().$content.$this->getFinish();
- }
- }
-
- /**
- * Get the page range for the current page window.
- *
- * @return string
- */
- public function getAdjacentRange()
- {
- return $this->getPageRange($this->currentPage - 3, $this->currentPage + 3);
- }
-
- /**
- * Create the beginning leader of a pagination slider.
- *
- * @return string
- */
- public function getStart()
- {
- return $this->getPageRange(1, 2).$this->getDots();
- }
-
- /**
- * Create the ending cap of a pagination slider.
- *
- * @return string
- */
- public function getFinish()
- {
- $content = $this->getPageRange($this->lastPage - 1, $this->lastPage);
-
- return $this->getDots().$content;
- }
-
- /**
- * Get the previous page pagination element.
- *
- * @param string $text
- * @return string
- */
- public function getPrevious($text = '«')
- {
- // If the current page is less than or equal to one, it means we can't go any
- // further back in the pages, so we will render a disabled previous button
- // when that is the case. Otherwise, we will give it an active "status".
- if ($this->currentPage <= 1)
- {
- return $this->getDisabledTextWrapper($text);
- }
-
- $url = $this->paginator->getUrl($this->currentPage - 1);
-
- return $this->getPageLinkWrapper($url, $text, 'prev');
- }
-
- /**
- * Get the next page pagination element.
- *
- * @param string $text
- * @return string
- */
- public function getNext($text = '»')
- {
- // If the current page is greater than or equal to the last page, it means we
- // can't go any further into the pages, as we're already on this last page
- // that is available, so we will make it the "next" link style disabled.
- if ($this->currentPage >= $this->lastPage)
- {
- return $this->getDisabledTextWrapper($text);
- }
-
- $url = $this->paginator->getUrl($this->currentPage + 1);
-
- return $this->getPageLinkWrapper($url, $text, 'next');
- }
-
- /**
- * Get a pagination "dot" element.
- *
- * @return string
- */
- public function getDots()
- {
- return $this->getDisabledTextWrapper("...");
- }
-
- /**
- * Create a pagination slider link.
- *
- * @param mixed $page
- * @return string
- */
- public function getLink($page)
- {
- $url = $this->paginator->getUrl($page);
-
- return $this->getPageLinkWrapper($url, $page);
- }
-
- /**
- * Set the value of the current page.
- *
- * @param int $page
- * @return void
- */
- public function setCurrentPage($page)
- {
- $this->currentPage = $page;
- }
-
- /**
- * Set the value of the last page.
- *
- * @param int $page
- * @return void
- */
- public function setLastPage($page)
- {
- $this->lastPage = $page;
- }
-
-}
diff --git a/src/Illuminate/Pagination/composer.json b/src/Illuminate/Pagination/composer.json
deleted file mode 100755
index 96c959f82..000000000
--- a/src/Illuminate/Pagination/composer.json
+++ /dev/null
@@ -1,30 +0,0 @@
-{
- "name": "illuminate/pagination",
- "license": "MIT",
- "authors": [
- {
- "name": "Taylor Otwell",
- "email": "taylorotwell@gmail.com"
- }
- ],
- "require": {
- "php": ">=5.4.0",
- "illuminate/http": "4.2.*",
- "illuminate/support": "4.2.*",
- "illuminate/view": "4.2.*",
- "symfony/http-foundation": "~6.4",
- "symfony/translation": "~6.4"
- },
- "autoload": {
- "psr-0": {
- "Illuminate\\Pagination": ""
- }
- },
- "target-dir": "Illuminate/Pagination",
- "extra": {
- "branch-alias": {
- "dev-master": "4.2-dev"
- }
- },
- "minimum-stability": "dev"
-}
diff --git a/src/Illuminate/Pagination/views/simple.php b/src/Illuminate/Pagination/views/simple.php
deleted file mode 100755
index 36353c327..000000000
--- a/src/Illuminate/Pagination/views/simple.php
+++ /dev/null
@@ -1,15 +0,0 @@
-getTranslator();
-?>
-
-lastPage() > 1): ?>
-
-
diff --git a/src/Illuminate/Pagination/views/slider-3.php b/src/Illuminate/Pagination/views/slider-3.php
deleted file mode 100755
index 0131087bc..000000000
--- a/src/Illuminate/Pagination/views/slider-3.php
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
-lastPage() > 1): ?>
-
-
diff --git a/src/Illuminate/Pagination/views/slider.php b/src/Illuminate/Pagination/views/slider.php
deleted file mode 100755
index af10c3c90..000000000
--- a/src/Illuminate/Pagination/views/slider.php
+++ /dev/null
@@ -1,11 +0,0 @@
-
-
-lastPage() > 1): ?>
-
-
diff --git a/src/Illuminate/Support/helpers.php b/src/Illuminate/Support/helpers.php
index adc6e3a2e..560bc9fe0 100755
--- a/src/Illuminate/Support/helpers.php
+++ b/src/Illuminate/Support/helpers.php
@@ -441,7 +441,7 @@ function csrf_token()
if (isset($session))
{
- return $session->getToken();
+ return $session->token();
}
throw new RuntimeException("Application session store not set.");
diff --git a/src/Illuminate/View/View.php b/src/Illuminate/View/View.php
index 5a33e7e28..e76a4aefc 100755
--- a/src/Illuminate/View/View.php
+++ b/src/Illuminate/View/View.php
@@ -5,7 +5,7 @@
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\MessageBag;
use Illuminate\View\Engines\EngineInterface;
-use Illuminate\Support\Contracts\MessageProviderInterface;
+use Illuminate\Contracts\Support\MessageProvider as MessageProviderInterface;
use Illuminate\Support\Contracts\ArrayableInterface as Arrayable;
class View implements ArrayAccess, Renderable
diff --git a/tests/Cache/CacheApcStoreTest.php b/tests/Cache/CacheApcStoreTest.php
deleted file mode 100755
index ac3d28a26..000000000
--- a/tests/Cache/CacheApcStoreTest.php
+++ /dev/null
@@ -1,70 +0,0 @@
-getMock(ApcWrapper::class, ['get']);
- $apc->expects($this->once())->method('get')->with($this->equalTo('foobar'))->willReturn(null);
- $store = new Illuminate\Cache\ApcStore($apc, 'foo');
- $this->assertNull($store->get('bar'));
- }
-
-
- public function testAPCValueIsReturned()
- {
- $apc = $this->getMock(ApcWrapper::class, ['get']);
- $apc->expects($this->once())->method('get')->willReturn('bar');
- $store = new Illuminate\Cache\ApcStore($apc);
- $this->assertEquals('bar', $store->get('foo'));
- }
-
-
- public function testSetMethodProperlyCallsAPC()
- {
- $apc = $this->getMock(ApcWrapper::class, ['put']);
- $apc->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(60));
- $store = new Illuminate\Cache\ApcStore($apc);
- $store->put('foo', 'bar', 1);
- }
-
-
- public function testIncrementMethodProperlyCallsAPC()
- {
- $apc = $this->getMock(ApcWrapper::class, ['increment']);
- $apc->expects($this->once())->method('increment')->with($this->equalTo('foo'), $this->equalTo(5));
- $store = new Illuminate\Cache\ApcStore($apc);
- $store->increment('foo', 5);
- }
-
-
- public function testDecrementMethodProperlyCallsAPC()
- {
- $apc = $this->getMock(ApcWrapper::class, ['decrement']);
- $apc->expects($this->once())->method('decrement')->with($this->equalTo('foo'), $this->equalTo(5));
- $store = new Illuminate\Cache\ApcStore($apc);
- $store->decrement('foo', 5);
- }
-
-
- public function testStoreItemForeverProperlyCallsAPC()
- {
- $apc = $this->getMock(ApcWrapper::class, ['put']);
- $apc->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0));
- $store = new Illuminate\Cache\ApcStore($apc);
- $store->forever('foo', 'bar');
- }
-
-
- public function testForgetMethodProperlyCallsAPC()
- {
- $apc = $this->getMock(ApcWrapper::class, ['delete']);
- $apc->expects($this->once())->method('delete')->with($this->equalTo('foo'));
- $store = new Illuminate\Cache\ApcStore($apc);
- $store->forget('foo');
- }
-
-}
diff --git a/tests/Cache/CacheArrayStoreTest.php b/tests/Cache/CacheArrayStoreTest.php
deleted file mode 100755
index fd03da61f..000000000
--- a/tests/Cache/CacheArrayStoreTest.php
+++ /dev/null
@@ -1,68 +0,0 @@
-put('foo', 'bar', 10);
- $this->assertEquals('bar', $store->get('foo'));
- }
-
-
- public function testStoreItemForeverProperlyStoresInArray()
- {
- $mock = $this->getMock(ArrayStore::class, ['put']);
- $mock->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0));
- $mock->forever('foo', 'bar');
- }
-
-
- public function testValuesCanBeIncremented()
- {
- $store = new ArrayStore;
- $store->put('foo', 1, 10);
- $store->increment('foo');
- $this->assertEquals(2, $store->get('foo'));
- }
-
-
- public function testValuesCanBeDecremented()
- {
- $store = new ArrayStore;
- $store->put('foo', 1, 10);
- $store->decrement('foo');
- $this->assertEquals(0, $store->get('foo'));
- }
-
-
- public function testItemsCanBeRemoved()
- {
- $store = new ArrayStore;
- $store->put('foo', 'bar', 10);
- $store->forget('foo');
- $this->assertNull($store->get('foo'));
- }
-
-
- public function testItemsCanBeFlushed()
- {
- $store = new ArrayStore;
- $store->put('foo', 'bar', 10);
- $store->put('baz', 'boom', 10);
- $store->flush();
- $this->assertNull($store->get('foo'));
- $this->assertNull($store->get('baz'));
- }
-
-
- public function testCacheKey()
- {
- $store = new ArrayStore;
- $this->assertEquals('', $store->getPrefix());
- }
-
-}
diff --git a/tests/Cache/CacheDatabaseStoreTest.php b/tests/Cache/CacheDatabaseStoreTest.php
deleted file mode 100755
index c81b9e43d..000000000
--- a/tests/Cache/CacheDatabaseStoreTest.php
+++ /dev/null
@@ -1,131 +0,0 @@
-getStore();
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
- $table->shouldReceive('where')->once()->with('key', '=', 'prefixfoo')->andReturn($table);
- $table->shouldReceive('first')->once()->andReturn(null);
-
- $this->assertNull($store->get('foo'));
- }
-
-
- public function testNullIsReturnedAndItemDeletedWhenItemIsExpired(): void
- {
- $store = $this->getMock(DatabaseStore::class, ['forget'], $this->getMocks());
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
- $table->shouldReceive('where')->once()->with('key', '=', 'prefixfoo')->andReturn($table);
- $table->shouldReceive('first')->once()->andReturn((object) ['expiration' => 1]);
- $store->expects($this->once())->method('forget')->with($this->equalTo('foo'))->willReturn(null);
-
- $this->assertNull($store->get('foo'));
- }
-
-
- public function testDecryptedValueIsReturnedWhenItemIsValid(): void
- {
- $store = $this->getStore();
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
- $table->shouldReceive('where')->once()->with('key', '=', 'prefixfoo')->andReturn($table);
- $table->shouldReceive('first')->once()->andReturn((object) ['value' => 'bar', 'expiration' => 999999999999999]);
- $store->getEncrypter()->shouldReceive('decrypt')->once()->with('bar')->andReturn('bar');
-
- $this->assertEquals('bar', $store->get('foo'));
- }
-
-
- public function testEncryptedValueIsInsertedWhenNoExceptionsAreThrown(): void
- {
- $store = $this->getMock(DatabaseStore::class, ['getTime'], $this->getMocks());
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
- $store->getEncrypter()->shouldReceive('encrypt')->once()->with('bar')->andReturn('bar');
- $store->expects($this->once())->method('getTime')->willReturn(1);
- $table->shouldReceive('insert')->once()->with(['key' => 'prefixfoo', 'value' => 'bar', 'expiration' => 61]);
-
- $store->put('foo', 'bar', 1);
- }
-
-
- public function testEncryptedValueIsUpdatedWhenInsertThrowsException(): void
- {
- $store = $this->getMock(DatabaseStore::class, ['getTime'], $this->getMocks());
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->with('table')->andReturn($table);
- $store->getEncrypter()->shouldReceive('encrypt')->once()->with('bar')->andReturn('bar');
- $store->expects($this->once())->method('getTime')->willReturn(1);
- $table->shouldReceive('insert')->once()->with(['key' => 'prefixfoo', 'value' => 'bar', 'expiration' => 61])->andReturnUsing(function(): never
- {
- throw new Exception;
- });
- $table->shouldReceive('where')->once()->with('key', '=', 'prefixfoo')->andReturn($table);
- $table->shouldReceive('update')->once()->with(['value' => 'bar', 'expiration' => 61]);
-
- $store->put('foo', 'bar', 1);
- }
-
-
- public function testForeverCallsStoreItemWithReallyLongTime(): void
- {
- $store = $this->getMock(DatabaseStore::class, ['put'], $this->getMocks());
- $store->expects($this->once())->method('put')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(5256000));
- $store->forever('foo', 'bar');
- }
-
-
- public function testItemsMayBeRemovedFromCache(): void
- {
- $store = $this->getStore();
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
- $table->shouldReceive('where')->once()->with('key', '=', 'prefixfoo')->andReturn($table);
- $table->shouldReceive('delete')->once();
-
- $store->forget('foo');
- }
-
-
- public function testItemsMayBeFlushedFromCache(): void
- {
- $store = $this->getStore();
- $table = m::mock('StdClass');
- $store->getConnection()->shouldReceive('table')->once()->with('table')->andReturn($table);
- $table->shouldReceive('delete')->once();
-
- $store->flush();
- }
-
-
- protected function getStore(): DatabaseStore
- {
- return new DatabaseStore(m::mock(Connection::class), m::mock(
- Encrypter::class
- ), 'table', 'prefix');
- }
-
-
- protected function getMocks(): array
- {
- return [m::mock(Connection::class), m::mock(Encrypter::class), 'table', 'prefix'];
- }
-
-}
diff --git a/tests/Cache/CacheFileStoreTest.php b/tests/Cache/CacheFileStoreTest.php
deleted file mode 100755
index 9b8f96bd5..000000000
--- a/tests/Cache/CacheFileStoreTest.php
+++ /dev/null
@@ -1,146 +0,0 @@
-mockFilesystem();
- $files->expects($this->once())->method('exists')->willReturn(false);
- $store = new FileStore($files, __DIR__);
- $value = $store->get('foo');
- $this->assertNull($value);
- }
-
-
- public function testPutCreatesMissingDirectories()
- {
- $files = $this->mockFilesystem();
- $md5 = md5('foo');
- $full_dir = __DIR__.'/'.substr($md5, 0, 2).'/'.substr($md5, 2, 2);
- $files->expects($this->once())->method('makeDirectory')->with($this->equalTo($full_dir), $this->equalTo(0777), $this->equalTo(true));
- $files->expects($this->once())->method('put')->with($this->equalTo($full_dir.'/'.$md5));
- $store = new FileStore($files, __DIR__);
- $store->put('foo', '0000000000', 0);
- }
-
-
- public function testExpiredItemsReturnNull()
- {
- $files = $this->mockFilesystem();
- $files->expects($this->once())->method('exists')->willReturn(true);
- $contents = '0000000000';
- $files->expects($this->once())->method('get')->willReturn($contents);
- $store = $this->getMock(FileStore::class, ['forget'], [$files, __DIR__]);
- $store->expects($this->once())->method('forget');
- $value = $store->get('foo');
- $this->assertNull($value);
- }
-
-
- public function testValidItemReturnsContents()
- {
- $files = $this->mockFilesystem();
- $files->expects($this->once())->method('exists')->willReturn(true);
- $contents = '9999999999'.serialize('Hello World');
- $files->expects($this->once())->method('get')->willReturn($contents);
- $store = new FileStore($files, __DIR__);
- $this->assertEquals('Hello World', $store->get('foo'));
- }
-
-
- public function testStoreItemProperlyStoresValues()
- {
- $files = $this->mockFilesystem();
- $store = $this->getMock(FileStore::class, ['expiration'], [$files, __DIR__]);
- $store->expects($this->once())->method('expiration')->with($this->equalTo(10))->willReturn(1111111111);
- $contents = '1111111111'.serialize('Hello World');
- $md5 = md5('foo');
- $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2);
- $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5), $this->equalTo($contents));
- $store->put('foo', 'Hello World', 10);
- }
-
-
- public function testForeversAreStoredWithHighTimestamp()
- {
- $files = $this->mockFilesystem();
- $contents = '9999999999'.serialize('Hello World');
- $md5 = md5('foo');
- $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2);
- $files->expects($this->once())->method('put')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5), $this->equalTo($contents));
- $store = new FileStore($files, __DIR__);
- $store->forever('foo', 'Hello World', 10);
- }
-
-
- public function testRemoveDeletesFileDoesntExist()
- {
- $files = $this->mockFilesystem();
- $md5 = md5('foobull');
- $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2);
- $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5))->willReturn(
- false
- );
- $store = new FileStore($files, __DIR__);
- $store->forget('foobull');
- }
-
-
- public function testRemoveDeletesFile()
- {
- $files = $this->mockFilesystem();
- $md5 = md5('foobar');
- $cache_dir = substr($md5, 0, 2).'/'.substr($md5, 2, 2);
- $store = new FileStore($files, __DIR__);
- $store->put('foobar', 'Hello Baby', 10);
- $files->expects($this->once())->method('exists')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5))->willReturn(
- true
- );
- $files->expects($this->once())->method('delete')->with($this->equalTo(__DIR__.'/'.$cache_dir.'/'.$md5));
- $store->forget('foobar');
- }
-
-
- public function testFlushCleansDirectory()
- {
- $files = $this->mockFilesystem();
- $files->expects($this->once())->method('isDirectory')->with($this->equalTo(__DIR__))->willReturn(true);
- $files->expects($this->once())->method('directories')->with($this->equalTo(__DIR__))->willReturn(['foo']);
- $files->expects($this->once())->method('deleteDirectory')->with($this->equalTo('foo'));
-
- $store = new FileStore($files, __DIR__);
- $store->flush();
- }
-
-
- public function testFlushIgnoreNonExistingDirectory()
- {
- $files = $this->mockFilesystem();
- $files->expects($this->once())->method('isDirectory')->with($this->equalTo(__DIR__ . '--wrong'))->willReturn(
- false
- );
-
- $store = new FileStore($files, __DIR__ . '--wrong');
- $store->flush();
- }
-
-
- protected function mockFilesystem()
- {
- return $this->getMock(Filesystem::class, [
- 'get',
- 'put',
- 'exists',
- 'delete',
- 'directories',
- 'isDirectory',
- 'makeDirectory',
- 'deleteDirectory'
- ]);
- }
-
-}
diff --git a/tests/Cache/CacheMemcachedConnectorTest.php b/tests/Cache/CacheMemcachedConnectorTest.php
deleted file mode 100755
index 0feac57f0..000000000
--- a/tests/Cache/CacheMemcachedConnectorTest.php
+++ /dev/null
@@ -1,40 +0,0 @@
-getMock(MemcachedConnector::class, ['getMemcached']);
- $memcached = m::mock('stdClass');
- $memcached->shouldReceive('addServer')->once()->with('localhost', 11211, 100);
- $memcached->shouldReceive('getVersion')->once()->andReturn(true);
- $connector->expects($this->once())->method('getMemcached')->willReturn($memcached);
- $result = $connector->connect([['host' => 'localhost', 'port' => 11211, 'weight' => 100]]);
-
- $this->assertSame($result, $memcached);
- }
-
-
- public function testExceptionThrownOnBadConnection()
- {
- $this->expectException(RuntimeException::class);
- $connector = $this->getMock(MemcachedConnector::class, ['getMemcached']);
- $memcached = m::mock('stdClass');
- $memcached->shouldReceive('addServer')->once()->with('localhost', 11211, 100);
- $memcached->shouldReceive('getVersion')->once()->andReturn(false);
- $connector->expects($this->once())->method('getMemcached')->willReturn($memcached);
- $result = $connector->connect([['host' => 'localhost', 'port' => 11211, 'weight' => 100]]);
- }
-
-}
diff --git a/tests/Cache/CacheMemcachedStoreTest.php b/tests/Cache/CacheMemcachedStoreTest.php
deleted file mode 100755
index edb793a2c..000000000
--- a/tests/Cache/CacheMemcachedStoreTest.php
+++ /dev/null
@@ -1,76 +0,0 @@
-markTestSkipped("We dont use Memcached");
- }
-
- public function testGetReturnsNullWhenNotFound()
- {
- $memcache = $this->getMock(stdClass::class, ['get', 'getResultCode']);
- $memcache->expects($this->once())->method('get')->with($this->equalTo('foo:bar'))->willReturn(null);
- $memcache->expects($this->once())->method('getResultCode')->willReturn(1);
- $store = new Illuminate\Cache\MemcachedStore($memcache, 'foo');
- $this->assertNull($store->get('bar'));
- }
-
-
- public function testMemcacheValueIsReturned()
- {
- $memcache = $this->getMock(stdClass::class, ['get', 'getResultCode']);
- $memcache->expects($this->once())->method('get')->willReturn('bar');
- $memcache->expects($this->once())->method('getResultCode')->willReturn(0);
- $store = new Illuminate\Cache\MemcachedStore($memcache);
- $this->assertEquals('bar', $store->get('foo'));
- }
-
-
- public function testSetMethodProperlyCallsMemcache()
- {
- $memcache = $this->getMock(Memcached::class, ['set']);
- $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(60));
- $store = new Illuminate\Cache\MemcachedStore($memcache);
- $store->put('foo', 'bar', 1);
- }
-
-
- public function testIncrementMethodProperlyCallsMemcache()
- {
- $memcache = $this->getMock(Memcached::class, ['increment']);
- $memcache->expects($this->once())->method('increment')->with($this->equalTo('foo'), $this->equalTo(5));
- $store = new Illuminate\Cache\MemcachedStore($memcache);
- $store->increment('foo', 5);
- }
-
-
- public function testDecrementMethodProperlyCallsMemcache()
- {
- $memcache = $this->getMock(Memcached::class, ['decrement']);
- $memcache->expects($this->once())->method('decrement')->with($this->equalTo('foo'), $this->equalTo(5));
- $store = new Illuminate\Cache\MemcachedStore($memcache);
- $store->decrement('foo', 5);
- }
-
-
- public function testStoreItemForeverProperlyCallsMemcached()
- {
- $memcache = $this->getMock(Memcached::class, ['set']);
- $memcache->expects($this->once())->method('set')->with($this->equalTo('foo'), $this->equalTo('bar'), $this->equalTo(0));
- $store = new Illuminate\Cache\MemcachedStore($memcache);
- $store->forever('foo', 'bar');
- }
-
-
- public function testForgetMethodProperlyCallsMemcache()
- {
- $memcache = $this->getMock(Memcached::class, ['delete']);
- $memcache->expects($this->once())->method('delete')->with($this->equalTo('foo'));
- $store = new Illuminate\Cache\MemcachedStore($memcache);
- $store->forget('foo');
- }
-
-}
diff --git a/tests/Cache/CacheNullStoreTest.php b/tests/Cache/CacheNullStoreTest.php
deleted file mode 100644
index f0f09cb4a..000000000
--- a/tests/Cache/CacheNullStoreTest.php
+++ /dev/null
@@ -1,15 +0,0 @@
-put('foo', 'bar', 10);
- $this->assertNull($store->get('foo'));
- }
-
-}
diff --git a/tests/Cache/CacheRedisStoreTest.php b/tests/Cache/CacheRedisStoreTest.php
deleted file mode 100755
index 851f5702f..000000000
--- a/tests/Cache/CacheRedisStoreTest.php
+++ /dev/null
@@ -1,102 +0,0 @@
-getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(null);
- $this->assertNull($redis->get('foo'));
- }
-
-
- public function testRedisValueIsReturned()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(serialize('foo'));
- $this->assertEquals('foo', $redis->get('foo'));
- }
-
-
- public function testRedisValueIsReturnedForNumerics()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('get')->once()->with('prefix:foo')->andReturn(1);
- $this->assertEquals(1, $redis->get('foo'));
- }
-
-
- public function testSetMethodProperlyCallsRedis()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, serialize('foo'));
- $redis->put('foo', 'foo', 60);
- }
-
-
- public function testSetMethodProperlyCallsRedisForNumerics()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('setex')->once()->with('prefix:foo', 60 * 60, 1);
- $redis->put('foo', 1, 60);
- }
-
-
- public function testIncrementMethodProperlyCallsRedis()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('incrby')->once()->with('prefix:foo', 5);
- $redis->increment('foo', 5);
- }
-
-
- public function testDecrementMethodProperlyCallsRedis()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('decrby')->once()->with('prefix:foo', 5);
- $redis->decrement('foo', 5);
- }
-
-
- public function testStoreItemForeverProperlyCallsRedis()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('set')->once()->with('prefix:foo', serialize('foo'));
- $redis->forever('foo', 'foo', 60);
- }
-
-
- public function testForgetMethodProperlyCallsRedis()
- {
- $redis = $this->getRedis();
- $redis->getRedis()->shouldReceive('connection')->once()->with('default')->andReturn($redis->getRedis());
- $redis->getRedis()->shouldReceive('del')->once()->with('prefix:foo');
- $redis->forget('foo');
- }
-
-
- protected function getRedis()
- {
- return new Illuminate\Cache\RedisStore(m::mock(Database::class), 'prefix');
- }
-
-}
diff --git a/tests/Cache/CacheRepositoryTest.php b/tests/Cache/CacheRepositoryTest.php
deleted file mode 100755
index 67453db75..000000000
--- a/tests/Cache/CacheRepositoryTest.php
+++ /dev/null
@@ -1,94 +0,0 @@
-getRepository();
- $repo->getStore()->shouldReceive('get')->once()->with('foo')->andReturn('bar');
- $this->assertEquals('bar', $repo->get('foo'));
- }
-
-
- public function testDefaultValueIsReturned()
- {
- $repo = $this->getRepository();
- $repo->getStore()->shouldReceive('get')->andReturn(null);
- $this->assertEquals('bar', $repo->get('foo', 'bar'));
- $this->assertEquals('baz', $repo->get('boom', function() { return 'baz'; }));
- }
-
-
- public function testSettingDefaultCacheTime()
- {
- $repo = $this->getRepository();
- $repo->setDefaultCacheTime(10);
- $this->assertEquals(10, $repo->getDefaultCacheTime());
- }
-
-
- public function testHasMethod()
- {
- $repo = $this->getRepository();
- $repo->getStore()->shouldReceive('get')->once()->with('foo')->andReturn(null);
- $repo->getStore()->shouldReceive('get')->once()->with('bar')->andReturn('bar');
-
- $this->assertTrue($repo->has('bar'));
- $this->assertFalse($repo->has('foo'));
- }
-
-
- public function testRememberMethodCallsPutAndReturnsDefault()
- {
- $repo = $this->getRepository();
- $repo->getStore()->shouldReceive('get')->andReturn(null);
- $repo->getStore()->shouldReceive('put')->once()->with('foo', 'bar', m::type('int'));
- $result = $repo->remember('foo', Carbon::now()->addMinutes(10), function() { return 'bar'; });
- $this->assertEquals('bar', $result);
- }
-
-
- public function testPutAcceptsDateIntervalTtl()
- {
- $repo = $this->getRepository();
- $repo->getStore()->shouldReceive('put')->once()->with('foo', 'bar', m::type('int'));
- $repo->put('foo', 'bar', new DateInterval('PT10M'));
- }
-
-
- public function testRememberForeverMethodCallsForeverAndReturnsDefault()
- {
- $repo = $this->getRepository();
- $repo->getStore()->shouldReceive('get')->andReturn(null);
- $repo->getStore()->shouldReceive('forever')->once()->with('foo', 'bar');
- $result = $repo->rememberForever('foo', function() { return 'bar'; });
- $this->assertEquals('bar', $result);
- }
-
-
- public function testRegisterMacroWithNonStaticCall()
- {
- $repo = $this->getRepository();
- $repo::macro(__CLASS__, function() { return 'Taylor'; });
- $this->assertEquals($repo->{__CLASS__}(), 'Taylor');
- }
-
-
- protected function getRepository()
- {
- return new Illuminate\Cache\Repository(m::mock(StoreInterface::class));
- }
-
-}
diff --git a/tests/Cache/CacheTaggedCacheTest.php b/tests/Cache/CacheTaggedCacheTest.php
deleted file mode 100644
index f1fb4199a..000000000
--- a/tests/Cache/CacheTaggedCacheTest.php
+++ /dev/null
@@ -1,115 +0,0 @@
-section('bop')->put('foo', 'bar', Carbon::now()->addMinutes(10));
- $store->section('zap')->put('baz', 'boom', Carbon::now()->addMinutes(10));
- $store->section('bop')->flush();
- $this->assertNull($store->section('bop')->get('foo'));
- $this->assertEquals('boom', $store->section('zap')->get('baz'));
- }
-
-
- public function testCacheCanBeSavedWithMultipleTags()
- {
- $store = new ArrayStore;
- $tags = ['bop', 'zap'];
- $store->tags($tags)->put('foo', 'bar', Carbon::now()->addMinutes(10));
- $this->assertEquals('bar', $store->tags($tags)->get('foo'));
- }
-
-
- public function testCacheCanBeSetWithDatetimeArgument()
- {
- $store = new ArrayStore;
- $tags = ['bop', 'zap'];
- $duration = new DateTime();
- $duration->add(new DateInterval("PT10M"));
- $store->tags($tags)->put('foo', 'bar', $duration);
- $this->assertEquals('bar', $store->tags($tags)->get('foo'));
- }
-
-
- public function testCacheSavedWithMultipleTagsCanBeFlushed()
- {
- $store = new ArrayStore;
- $tags1 = ['bop', 'zap'];
- $store->tags($tags1)->put('foo', 'bar', Carbon::now()->addMinutes(10));
- $tags2 = ['bam', 'pow'];
- $store->tags($tags2)->put('foo', 'bar', Carbon::now()->addMinutes(10));
- $store->tags('zap')->flush();
- $this->assertNull($store->tags($tags1)->get('foo'));
- $this->assertEquals('bar', $store->tags($tags2)->get('foo'));
- }
-
-
- public function testTagsWithStringArgument()
- {
- $store = new ArrayStore;
- $store->tags('bop')->put('foo', 'bar', Carbon::now()->addMinutes(10));
- $this->assertEquals('bar', $store->tags('bop')->get('foo'));
- }
-
-
- public function testTagsCacheForever()
- {
- $store = new ArrayStore;
- $tags = ['bop', 'zap'];
- $store->tags($tags)->forever('foo', 'bar');
- $this->assertEquals('bar', $store->tags($tags)->get('foo'));
- }
-
-
- public function testRedisCacheTagsPushForeverKeysCorrectly()
- {
- $store = m::mock(StoreInterface::class);
- $tagSet = m::mock(TagSet::class, [$store, ['foo', 'bar']]);
- $tagSet->shouldReceive('getNamespace')->andReturn('foo|bar');
- $redis = new Illuminate\Cache\RedisTaggedCache($store, $tagSet);
- $store->shouldReceive('getPrefix')->andReturn('prefix:');
- $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass'));
- $conn->shouldReceive('lpush')->once()->with('prefix:foo:forever', 'prefix:'.sha1('foo|bar').':key1');
- $conn->shouldReceive('lpush')->once()->with('prefix:bar:forever', 'prefix:'.sha1('foo|bar').':key1');
- $store->shouldReceive('forever')->with(sha1('foo|bar').':key1', 'key1:value');
-
- $redis->forever('key1', 'key1:value');
- }
-
-
- public function testRedisCacheForeverTagsCanBeFlushed()
- {
- $store = m::mock(StoreInterface::class);
- $tagSet = m::mock(TagSet::class, [$store, ['foo', 'bar']]);
- $tagSet->shouldReceive('getNamespace')->andReturn('foo|bar');
- $redis = new Illuminate\Cache\RedisTaggedCache($store, $tagSet);
- $store->shouldReceive('getPrefix')->andReturn('prefix:');
- $store->shouldReceive('connection')->andReturn($conn = m::mock('StdClass'));
- $conn->shouldReceive('lrange')->once()->with('prefix:foo:forever', 0, -1)->andReturn(['key1', 'key2']);
- $conn->shouldReceive('lrange')->once()->with('prefix:bar:forever', 0, -1)->andReturn(['key3']);
- $conn->shouldReceive('del')->once()->with('key1', 'key2');
- $conn->shouldReceive('del')->once()->with('key3');
- $conn->shouldReceive('del')->once()->with('prefix:foo:forever');
- $conn->shouldReceive('del')->once()->with('prefix:bar:forever');
- $tagSet->shouldReceive('reset')->once();
-
- $redis->flush();
- }
-
-}
diff --git a/tests/CachedRouting/RoutingIntegrationTest.php b/tests/CachedRouting/RoutingIntegrationTest.php
index c27b700d6..7776713f7 100755
--- a/tests/CachedRouting/RoutingIntegrationTest.php
+++ b/tests/CachedRouting/RoutingIntegrationTest.php
@@ -95,8 +95,9 @@ protected function refreshApplication(): void
$this->app['files'] = new Filesystem;
$this->app['cache'] = new CacheManager($this->app);
- $this->app['config']['cache.driver'] = 'file';
- $this->app['config']['cache.path'] = self::$cachePath = sys_get_temp_dir() . '/l42x-route-cache-' . uniqid();
+ self::$cachePath = sys_get_temp_dir() . '/l42x-route-cache-' . uniqid();
+ $this->app['config']['cache.default'] = 'file';
+ $this->app['config']['cache.stores.file'] = ['driver' => 'file', 'path' => self::$cachePath];
$this->app['session'] = new SessionManager($this->app);
$this->app['config']['session.driver'] = 'array';
diff --git a/tests/Cookie/CookieTest.php b/tests/Cookie/CookieTest.php
deleted file mode 100755
index c4128e37d..000000000
--- a/tests/Cookie/CookieTest.php
+++ /dev/null
@@ -1,139 +0,0 @@
-getCreator();
- $cookie->setDefaultPathAndDomain('foo', 'bar');
- $c = $cookie->make('color', 'blue', 10, '/path', '/domain', true, false);
- $this->assertEquals('blue', $c->getValue());
- $this->assertFalse($c->isHttpOnly());
- $this->assertTrue($c->isSecure());
- $this->assertEquals('/domain', $c->getDomain());
- $this->assertEquals('/path', $c->getPath());
-
- $c2 = $cookie->forever('color', 'blue', '/path', '/domain', true, false);
- $this->assertEquals('blue', $c2->getValue());
- $this->assertFalse($c2->isHttpOnly());
- $this->assertTrue($c2->isSecure());
- $this->assertEquals('/domain', $c2->getDomain());
- $this->assertEquals('/path', $c2->getPath());
-
- $c3 = $cookie->forget('color');
- $this->assertNull($c3->getValue());
- $this->assertTrue($c3->getExpiresTime() < time());
- }
-
-
- public function testCookiesAreCreatedWithProperOptionsUsingDefaultPathAndDomain()
- {
- $cookie = $this->getCreator();
- $cookie->setDefaultPathAndDomain('/path', '/domain');
- $c = $cookie->make('color', 'blue', 10, null, null, true, false);
- $this->assertEquals('blue', $c->getValue());
- $this->assertFalse($c->isHttpOnly());
- $this->assertTrue($c->isSecure());
- $this->assertEquals('/domain', $c->getDomain());
- $this->assertEquals('/path', $c->getPath());
- }
-
-
- public function testSameSiteAndRawWidening()
- {
- $cookie = $this->getCreator();
-
- // behavior-preserving default: L4.2/Symfony effective SameSite = lax
- $this->assertSame('lax', $cookie->make('a', 'b')->getSameSite());
- $this->assertFalse($cookie->make('a', 'b')->isRaw());
-
- // per-cookie overrides via the widened signature
- $c = $cookie->make('a', 'b', 0, null, null, null, true, true, 'strict');
- $this->assertSame('strict', $c->getSameSite());
- $this->assertTrue($c->isRaw());
- }
-
-
- public function testQueuedCookies()
- {
- $cookie = $this->getCreator();
- $this->assertEmpty($cookie->getQueuedCookies());
- $this->assertFalse($cookie->hasQueued('foo'));
- $cookie->queue($cookie->make('foo','bar'));
- $this->assertTrue($cookie->hasQueued('foo'));
- $this->assertInstanceOf(Cookie::class, $cookie->queued('foo'));
- $cookie->queue('qu','ux');
- $this->assertTrue($cookie->hasQueued('qu'));
- $this->assertInstanceOf(Cookie::class, $cookie->queued('qu'));
- $this->assertCount(2, $cookie->getQueuedCookies());
- }
-
-
- public function testUnqueue()
- {
- $cookie = $this->getCreator();
- $cookie->queue($cookie->make('foo','bar'));
- $this->assertTrue($cookie->hasQueued('foo'));
- $cookie->unqueue('foo');
- $this->assertEmpty($cookie->getQueuedCookies());
- $this->assertFalse($cookie->hasQueued('foo'));
- }
-
-
- public function testPathAwareQueuedCookies()
- {
- $cookie = $this->getCreator();
- $cookie->queue($cookie->make('foo', 'a', 0, '/a'));
- $cookie->queue($cookie->make('foo', 'b', 0, '/b'));
-
- $this->assertCount(2, $cookie->getQueuedCookies());
- $this->assertSame('a', $cookie->queued('foo', null, '/a')->getValue());
- $this->assertSame('b', $cookie->queued('foo', null, '/b')->getValue());
- $this->assertSame('b', $cookie->queued('foo')->getValue());
-
- $cookie->unqueue('foo', '/a');
- $this->assertNull($cookie->queued('foo', null, '/a'));
- $this->assertSame('b', $cookie->queued('foo', null, '/b')->getValue());
- $this->assertCount(1, $cookie->getQueuedCookies());
-
- $cookie->flushQueuedCookies();
- $this->assertEmpty($cookie->getQueuedCookies());
- }
-
-
- public function testExpireQueuesForgetCookie()
- {
- $cookie = $this->getCreator();
- $cookie->expire('foo');
-
- $this->assertTrue($cookie->hasQueued('foo'));
- $queued = $cookie->queued('foo');
- $this->assertInstanceOf(Cookie::class, $queued);
- $this->assertTrue($queued->getExpiresTime() < time());
- }
-
-
- public function getCreator()
- {
- return new CookieJar(Request::create('/foo', 'GET'), [
- 'path' => '/path',
- 'domain' => '/domain',
- 'secure' => true,
- 'httpOnly' => false,
- ]);
- }
-
-}
diff --git a/tests/Database/DatabaseConnectionFactoryTest.php b/tests/Database/DatabaseConnectionFactoryTest.php
deleted file mode 100755
index bf26ee104..000000000
--- a/tests/Database/DatabaseConnectionFactoryTest.php
+++ /dev/null
@@ -1,149 +0,0 @@
-getMock(
- ConnectionFactory::class,
- ['createConnector', 'createConnection'],
- [$container = m::mock(Container::class)]
- );
- $container->shouldReceive('bound')->andReturn(false);
- $connector = m::mock('stdClass');
- $config = ['driver' => 'mysql', 'prefix' => 'prefix', 'database' => 'database', 'name' => 'foo'];
- $pdo = new DatabaseConnectionFactoryPDOStub;
- $connector->shouldReceive('connect')->once()->with($config)->andReturn($pdo);
- $factory->expects($this->once())->method('createConnector')->with($config)->willReturn($connector);
- $mockConnection = m::mock('stdClass');
- $passedConfig = array_merge($config, ['name' => 'foo']);
- $factory->expects($this->once())->method('createConnection')->with($this->equalTo('mysql'), $this->equalTo($pdo), $this->equalTo('database'), $this->equalTo('prefix'), $this->equalTo($passedConfig))->willReturn(
- $mockConnection
- );
- $connection = $factory->make($config, 'foo');
-
- $this->assertEquals($mockConnection, $connection);
- }
-
-
- public function testMakeCallsCreateConnectionForReadWrite()
- {
- $factory = $this->getMock(ConnectionFactory::class, ['createConnector', 'createConnection'], [
- $container = m::mock(
- Container::class
- )
- ]);
- $container->shouldReceive('bound')->andReturn(false);
- $connector = m::mock('stdClass');
- $config = [
- 'read' => ['database' => 'database'],
- 'write' => ['database' => 'database'],
- 'driver' => 'mysql', 'prefix' => 'prefix', 'name' => 'foo',
- ];
- $expect = $config;
- unset($expect['read']);
- unset($expect['write']);
- $expect['database'] = 'database';
- $pdo = new DatabaseConnectionFactoryPDOStub;
- $connector->shouldReceive('connect')->twice()->with($expect)->andReturn($pdo);
- $factory->expects($this->exactly(2))->method('createConnector')->with($expect)->willReturn($connector);
- $mockConnection = m::mock('stdClass');
- $mockConnection->shouldReceive('setReadPdo')->once()->andReturn($mockConnection);
- $passedConfig = array_merge($expect, ['name' => 'foo']);
- $factory->expects($this->once())->method('createConnection')->with($this->equalTo('mysql'), $this->equalTo($pdo), $this->equalTo('database'), $this->equalTo('prefix'), $this->equalTo($passedConfig))->willReturn(
- $mockConnection
- );
- $connection = $factory->make($config, 'foo');
-
- $this->assertEquals($mockConnection, $connection);
- }
-
-
- public function testMakeCanCallTheContainer()
- {
- $factory = $this->getMock(ConnectionFactory::class, ['createConnector'], [
- $container = m::mock(
- Container::class
- )
- ]);
- $container->shouldReceive('bound')->andReturn(true);
- $connector = m::mock('stdClass');
- $config = ['driver' => 'mysql', 'prefix' => 'prefix', 'database' => 'database', 'name' => 'foo'];
- $pdo = new DatabaseConnectionFactoryPDOStub;
- $connector->shouldReceive('connect')->once()->with($config)->andReturn($pdo);
- $passedConfig = array_merge($config, ['name' => 'foo']);
- $factory->expects($this->once())->method('createConnector')->with($config)->willReturn($connector);
- $container->shouldReceive('make')->once()->with('db.connection.mysql', [$pdo, 'database', 'prefix', $passedConfig]
- )->andReturn('foo');
- $connection = $factory->make($config, 'foo');
-
- $this->assertEquals('foo', $connection);
- }
-
-
- public function testProperInstancesAreReturnedForProperDrivers()
- {
- $factory = new Illuminate\Database\Connectors\ConnectionFactory($container = m::mock(
- Container::class
- ));
- $container->shouldReceive('bound')->andReturn(false);
- $this->assertInstanceOf(MySqlConnector::class, $factory->createConnector(['driver' => 'mysql']));
- $this->assertInstanceOf(PostgresConnector::class, $factory->createConnector(['driver' => 'pgsql']));
- $this->assertInstanceOf(SQLiteConnector::class, $factory->createConnector(['driver' => 'sqlite']));
- $this->assertInstanceOf(SqlServerConnector::class, $factory->createConnector(['driver' => 'sqlsrv']));
- }
-
-
- public function testIfDriverIsntSetExceptionIsThrown()
- {
- $this->expectException(InvalidArgumentException::class);
- $factory = new Illuminate\Database\Connectors\ConnectionFactory(
- $container = m::mock(Container::class)
- );
- $factory->createConnector(['foo']);
- }
-
-
- public function testExceptionIsThrownOnUnsupportedDriver()
- {
- $this->expectException(InvalidArgumentException::class);
- $factory = new Illuminate\Database\Connectors\ConnectionFactory(
- $container = m::mock(Container::class)
- );
- $container->shouldReceive('bound')->once()->andReturn(false);
- $factory->createConnector(['driver' => 'foo']);
- }
-
-
- public function testCustomConnectorsCanBeResolvedViaContainer()
- {
- $factory = new Illuminate\Database\Connectors\ConnectionFactory($container = m::mock(
- Container::class
- ));
- $container->shouldReceive('bound')->once()->with('db.connector.foo')->andReturn(true);
- $container->shouldReceive('make')->once()->with('db.connector.foo')->andReturn('connector');
-
- $this->assertEquals('connector', $factory->createConnector(['driver' => 'foo']));
- }
-
-}
diff --git a/tests/Database/DatabaseConnectionTest.php b/tests/Database/DatabaseConnectionTest.php
deleted file mode 100755
index 42cca2204..000000000
--- a/tests/Database/DatabaseConnectionTest.php
+++ /dev/null
@@ -1,333 +0,0 @@
-getMockConnection();
- $mock = m::mock(stdClass::class);
- $connection->expects($this->once())->method('getDefaultQueryGrammar')->willReturn($mock);
- $connection->useDefaultQueryGrammar();
- $this->assertEquals($mock, $connection->getQueryGrammar());
- }
-
-
- public function testSettingDefaultCallsGetDefaultPostProcessor()
- {
- $connection = $this->getMockConnection();
- $mock = m::mock(stdClass::class);
- $connection->expects($this->once())->method('getDefaultPostProcessor')->willReturn($mock);
- $connection->useDefaultPostProcessor();
- $this->assertEquals($mock, $connection->getPostProcessor());
- }
-
-
- public function testSelectOneCallsSelectAndReturnsSingleResult()
- {
- $connection = $this->getMockConnection(['select']);
- $connection->expects($this->once())->method('select')->with('foo', ['bar' => 'baz'])->willReturn(
- ['foo']
- );
- $this->assertEquals('foo', $connection->selectOne('foo', ['bar' => 'baz']));
- }
-
-
- public function testSelectProperlyCallsPDO()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['prepare']);
- $writePdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['prepare']);
- $writePdo->expects($this->never())->method('prepare');
- $statement = $this->getMock('PDOStatement', ['execute', 'fetchAll']);
- $statement->expects($this->once())->method('execute')->with($this->equalTo(['foo' => 'bar']));
- $statement->expects($this->once())->method('fetchAll')->willReturn(['boom']);
- $pdo->expects($this->once())->method('prepare')->with('foo')->willReturn($statement);
- $mock = $this->getMockConnection(['prepareBindings'], $writePdo);
- $mock->setReadPdo($pdo);
- $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(['foo' => 'bar']))->willReturn(
- ['foo' => 'bar']
- );
- $results = $mock->select('foo', ['foo' => 'bar']);
- $this->assertEquals(['boom'], $results);
- $log = $mock->getQueryLog();
- $this->assertEquals('foo', $log[0]['query']);
- $this->assertEquals(['foo' => 'bar'], $log[0]['bindings']);
- $this->assertIsNumeric($log[0]['time']);
- }
-
-
- public function testInsertCallsTheStatementMethod()
- {
- $connection = $this->getMockConnection(['statement']);
- $connection->expects($this->once())->method('statement')->with($this->equalTo('foo'), $this->equalTo(['bar']))->willReturn(
- 'baz'
- );
- $results = $connection->insert('foo', ['bar']);
- $this->assertEquals('baz', $results);
- }
-
-
- public function testUpdateCallsTheAffectingStatementMethod()
- {
- $connection = $this->getMockConnection(['affectingStatement']);
- $connection->expects($this->once())->method('affectingStatement')->with($this->equalTo('foo'), $this->equalTo(
- ['bar']
- ))->willReturn(
- 'baz'
- );
- $results = $connection->update('foo', ['bar']);
- $this->assertEquals('baz', $results);
- }
-
-
- public function testDeleteCallsTheAffectingStatementMethod()
- {
- $connection = $this->getMockConnection(['affectingStatement']);
- $connection->expects($this->once())->method('affectingStatement')->with($this->equalTo('foo'), $this->equalTo(
- ['bar']
- ))->willReturn(
- 'baz'
- );
- $results = $connection->delete('foo', ['bar']);
- $this->assertEquals('baz', $results);
- }
-
-
- public function testStatementProperlyCallsPDO()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['prepare']);
- $statement = $this->getMock('PDOStatement', ['execute']);
- $statement->expects($this->once())->method('execute')->with($this->equalTo(['bar']))->willReturn(true);
- $pdo->expects($this->once())->method('prepare')->with($this->equalTo('foo'))->willReturn($statement);
- $mock = $this->getMockConnection(['prepareBindings'], $pdo);
- $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(['bar']))->willReturn(
- ['bar']
- );
- $results = $mock->statement('foo', ['bar']);
- $this->assertEquals(true, $results);
- $log = $mock->getQueryLog();
- $this->assertEquals('foo', $log[0]['query']);
- $this->assertEquals(['bar'], $log[0]['bindings']);
- $this->assertIsNumeric($log[0]['time']);
- }
-
-
- public function testAffectingStatementProperlyCallsPDO()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['prepare']);
- $statement = $this->getMock('PDOStatement', ['execute', 'rowCount']);
- $statement->expects($this->once())->method('execute')->with($this->equalTo(['foo' => 'bar']));
- $statement->expects($this->once())->method('rowCount')->willReturn(100);
- $pdo->expects($this->once())->method('prepare')->with('foo')->willReturn($statement);
- $mock = $this->getMockConnection(['prepareBindings'], $pdo);
- $mock->expects($this->once())->method('prepareBindings')->with($this->equalTo(['foo' => 'bar']))->willReturn(
- ['foo' => 'bar']
- );
- $results = $mock->update('foo', ['foo' => 'bar']);
- $this->assertEquals(100, $results);
- $log = $mock->getQueryLog();
- $this->assertEquals('foo', $log[0]['query']);
- $this->assertEquals(['foo' => 'bar'], $log[0]['bindings']);
- $this->assertIsNumeric($log[0]['time']);
- }
-
-
- public function testBeganTransactionFiresEventsIfSet()
- {
- $pdo = $this->createMock(DatabaseConnectionTestMockPDO::class);
- $connection = $this->getMockConnection(['getName'], $pdo);
- $connection->expects($this->any())->method('getName')->willReturn('name');
- $connection->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('dispatch')->once()->with('connection.name.beganTransaction', $connection);
- $connection->beginTransaction();
- }
-
-
- public function testCommitedFiresEventsIfSet()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class);
- $connection = $this->getMockConnection(['getName'], $pdo);
- $connection->expects($this->once())->method('getName')->willReturn('name');
- $connection->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('dispatch')->once()->with('connection.name.committed', $connection);
- $connection->commit();
- }
-
-
- public function testRollBackedFiresEventsIfSet()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class);
- $connection = $this->getMockConnection(['getName'], $pdo);
- $connection->expects($this->once())->method('getName')->willReturn('name');
- $connection->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('dispatch')->once()->with('connection.name.rollingBack', $connection);
- $connection->rollBack();
- }
-
-
- public function testTransactionMethodRunsSuccessfully()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['beginTransaction', 'commit']);
- $mock = $this->getMockConnection([], $pdo);
- $pdo->expects($this->once())->method('beginTransaction');
- $pdo->expects($this->once())->method('commit');
- $result = $mock->transaction(function($db) { return $db; });
- $this->assertEquals($mock, $result);
- }
-
-
- public function testTransactionMethodRollsbackAndThrows()
- {
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['beginTransaction', 'commit', 'rollBack']);
- $mock = $this->getMockConnection([], $pdo);
- $pdo->expects($this->once())->method('beginTransaction');
- $pdo->expects($this->once())->method('rollBack');
- $pdo->expects($this->never())->method('commit');
- try
- {
- $mock->transaction(function(): never { throw new Exception('foo'); });
- }
- catch (Exception $e)
- {
- $this->assertEquals('foo', $e->getMessage());
- }
- }
-
- public function testTransactionMethodDisallowPDOChanging()
- {
- $this->expectException(RuntimeException::class);
- $pdo = $this->getMock(DatabaseConnectionTestMockPDO::class, ['beginTransaction', 'commit', 'rollBack']);
- $pdo->expects($this->once())->method('beginTransaction');
- $pdo->expects($this->once())->method('rollBack');
- $pdo->expects($this->never())->method('commit');
-
- $mock = $this->getMockConnection([], $pdo);
-
- $mock->setReconnector(
- function ($connection) {
- $connection->setPDO(null);
- }
- );
-
- $mock->transaction(function ($connection) { $connection->reconnect(); });
- }
-
-
- public function testFromCreatesNewQueryBuilder()
- {
- $conn = $this->getMockConnection();
- $conn->setQueryGrammar(m::mock(Grammar::class));
- $conn->setPostProcessor(m::mock(Processor::class));
- $builder = $conn->table('users');
- $this->assertInstanceOf(\Illuminate\Database\Query\Builder::class, $builder);
- $this->assertEquals('users', $builder->from);
- }
-
-
- public function testPrepareBindings()
- {
- $date = m::mock('DateTime');
- $date->shouldReceive('format')->once()->with('foo')->andReturn('bar');
- $bindings = ['test' => $date];
- $conn = $this->getMockConnection();
- $grammar = m::mock(Grammar::class);
- $grammar->shouldReceive('getDateFormat')->once()->andReturn('foo');
- $conn->setQueryGrammar($grammar);
- $result = $conn->prepareBindings($bindings);
- $this->assertEquals(['test' => 'bar'], $result);
- }
-
-
- public function testLogQueryFiresEventsIfSet()
- {
- $connection = $this->getMockConnection();
- $connection->logQuery('foo', [], time());
- $connection->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('dispatch')->once()->with('illuminate.query', ['foo', [], null, null]);
- $connection->logQuery('foo', [], null);
- }
-
-
- public function testPretendOnlyLogsQueries()
- {
- $connection = $this->getMockConnection();
- $queries = $connection->pretend(function($connection)
- {
- $connection->select('foo bar', ['baz']);
- });
- $this->assertEquals('foo bar', $queries[0]['query']);
- $this->assertEquals(['baz'], $queries[0]['bindings']);
- }
-
-
- public function testSchemaBuilderCanBeCreated()
- {
- $connection = $this->getMockConnection();
- $schema = $connection->getSchemaBuilder();
- $this->assertInstanceOf(Builder::class, $schema);
- $this->assertSame($connection, $schema->getConnection());
- }
-
-
- public function testResolvingPaginatorThroughClosure()
- {
- $connection = $this->getMockConnection();
- $paginator = m::mock(Factory::class);
- $connection->setPaginator(function() use ($paginator)
- {
- return $paginator;
- });
- $this->assertEquals($paginator, $connection->getPaginator());
- }
-
-
- public function testResolvingCacheThroughClosure()
- {
- $connection = $this->getMockConnection();
- $cache = m::mock(CacheManager::class);
- $connection->setCacheManager(function() use ($cache)
- {
- return $cache;
- });
- $this->assertEquals($cache, $connection->getCacheManager());
- }
-
-
- protected function getMockConnection($methods = [], $pdo = null)
- {
- $pdo = $pdo ?: new DatabaseConnectionTestMockPDO;
- $defaults = ['getDefaultQueryGrammar', 'getDefaultPostProcessor', 'getDefaultSchemaGrammar'];
-
- $connection = $this->getMockBuilder(Connection::class)
- ->onlyMethods(array_merge($defaults, $methods))
- ->setConstructorArgs([$pdo])
- ->getMock();
-
- $connection->enableQueryLog();
-
- return $connection;
- }
-
-}
-
-class DatabaseConnectionTestMockPDO extends PDO {
- public function __construct() {
- //
- }
-}
diff --git a/tests/Database/DatabaseConnectorTest.php b/tests/Database/DatabaseConnectorTest.php
deleted file mode 100755
index 83f3fb351..000000000
--- a/tests/Database/DatabaseConnectorTest.php
+++ /dev/null
@@ -1,185 +0,0 @@
-setDefaultOptions([0 => 'foo', 1 => 'bar']);
- $this->assertEquals(
- [0 => 'baz', 1 => 'bar', 2 => 'boom'],
- $connector->getOptions(['options' => [0 => 'baz', 2 => 'boom']])
- );
- }
-
-
- /**
- * @dataProvider mySqlConnectProvider
- */
- public function testMySqlConnectCallsCreateConnectionWithProperArguments($dsn, $config)
- {
- $connector = $this->getMock(MySqlConnector::class, ['createConnection', 'getOptions']);
- $connection = m::mock('stdClass');
- $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(
- ['options']
- );
- $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(
- ['options']
- ))->willReturn(
- $connection
- );
- $connection->shouldReceive('prepare')->once()->with('set names \'utf8\' collate \'utf8_unicode_ci\'')->andReturn($connection);
- $connection->shouldReceive('prepare')->once()->with('set session sql_mode=\'\'')->andReturn($connection);
- $connection->shouldReceive('execute')->times(2);
- $connection->shouldReceive('exec')->zeroOrMoreTimes();
- $result = $connector->connect($config);
-
- $this->assertSame($result, $connection);
- }
-
-
- public function mySqlConnectProvider()
- {
- return [
- ['mysql:host=foo;dbname=bar', ['host' => 'foo', 'database' => 'bar', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8']],
- ['mysql:host=foo;port=111;dbname=bar', ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8']],
- ['mysql:unix_socket=baz;dbname=bar', ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'unix_socket' => 'baz', 'collation' => 'utf8_unicode_ci', 'charset' => 'utf8']],
- ];
- }
-
-
- public function testPostgresConnectCallsCreateConnectionWithProperArguments()
- {
- $dsn = 'pgsql:host=foo;dbname=bar;port=111';
- $config = ['host' => 'foo', 'database' => 'bar', 'port' => 111, 'charset' => 'utf8'];
- $connector = $this->getMock(PostgresConnector::class, ['createConnection', 'getOptions']);
- $connection = m::mock('stdClass');
- $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(
- ['options']
- );
- $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(
- ['options']
- ))->willReturn(
- $connection
- );
- $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection);
- $connection->shouldReceive('execute')->once();
- $result = $connector->connect($config);
-
- $this->assertSame($result, $connection);
- }
-
-
- public function testPostgresSearchPathIsSet()
- {
- $dsn = 'pgsql:host=foo;dbname=bar';
- $config = ['host' => 'foo', 'database' => 'bar', 'schema' => 'public', 'charset' => 'utf8'];
- $connector = $this->getMock(PostgresConnector::class, ['createConnection', 'getOptions']);
- $connection = m::mock('stdClass');
- $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(
- ['options']
- );
- $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(
- ['options']
- ))->willReturn(
- $connection
- );
- $connection->shouldReceive('prepare')->once()->with('set names \'utf8\'')->andReturn($connection);
- $connection->shouldReceive('prepare')->once()->with("set search_path to public")->andReturn($connection);
- $connection->shouldReceive('execute')->twice();
- $result = $connector->connect($config);
-
- $this->assertSame($result, $connection);
- }
-
-
- public function testSQLiteMemoryDatabasesMayBeConnectedTo()
- {
- $dsn = 'sqlite::memory:';
- $config = ['database' => ':memory:'];
- $connector = $this->getMock(SQLiteConnector::class, ['createConnection', 'getOptions']);
- $connection = m::mock('stdClass');
- $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(
- ['options']
- );
- $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(
- ['options']
- ))->willReturn(
- $connection
- );
- $result = $connector->connect($config);
-
- $this->assertSame($result, $connection);
- }
-
-
- public function testSQLiteFileDatabasesMayBeConnectedTo()
- {
- $dsn = 'sqlite:'.__DIR__;
- $config = ['database' => __DIR__];
- $connector = $this->getMock(SQLiteConnector::class, ['createConnection', 'getOptions']);
- $connection = m::mock('stdClass');
- $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(
- ['options']
- );
- $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(
- ['options']
- ))->willReturn(
- $connection
- );
- $result = $connector->connect($config);
-
- $this->assertSame($result, $connection);
- }
-
-
- public function testSqlServerConnectCallsCreateConnectionWithProperArguments()
- {
- $config = ['host' => 'foo', 'database' => 'bar', 'port' => 111];
- $dsn = $this->getDsn($config);
- $connector = $this->getMock(SqlServerConnector::class, ['createConnection', 'getOptions']);
- $connection = m::mock('stdClass');
- $connector->expects($this->once())->method('getOptions')->with($this->equalTo($config))->willReturn(
- ['options']
- );
- $connector->expects($this->once())->method('createConnection')->with($this->equalTo($dsn), $this->equalTo($config), $this->equalTo(
- ['options']
- ))->willReturn(
- $connection
- );
- $result = $connector->connect($config);
-
- $this->assertSame($result, $connection);
- }
-
- protected function getDsn(array $config)
- {
- extract($config);
-
- if (in_array('dblib', PDO::getAvailableDrivers()))
- {
- $port = isset($config['port']) ? ':'.$port : '';
- return "dblib:host={$host}{$port};dbname={$database}";
- }
- else
- {
- $port = isset($config['port']) ? ','.$port : '';
- return "sqlsrv:Server={$host}{$port};Database={$database}";
- }
- }
-
-}
diff --git a/tests/Database/DatabaseEloquentBelongsToManyTest.php b/tests/Database/DatabaseEloquentBelongsToManyTest.php
deleted file mode 100755
index cd0183a91..000000000
--- a/tests/Database/DatabaseEloquentBelongsToManyTest.php
+++ /dev/null
@@ -1,506 +0,0 @@
-fill(['name' => 'taylor', 'pivot_user_id' => 1, 'pivot_role_id' => 2]);
- $model2 = new EloquentBelongsToManyModelStub;
- $model2->fill(['name' => 'dayle', 'pivot_user_id' => 3, 'pivot_role_id' => 4]);
- $models = [$model1, $model2];
-
- $baseBuilder = m::mock(\Illuminate\Database\Query\Builder::class);
-
- $relation = $this->getRelation();
- $relation->getParent()->shouldReceive('getConnectionName')->andReturn('foo.connection');
- $relation->getQuery()->shouldReceive('addSelect')->once()->with(
- ['roles.*', 'user_role.user_id as pivot_user_id', 'user_role.role_id as pivot_role_id']
- )->andReturn($relation->getQuery());
- $relation->getQuery()->shouldReceive('getModels')->once()->andReturn($models);
- $relation->getQuery()->shouldReceive('eagerLoadRelations')->once()->with($models)->andReturn($models);
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); });
- $relation->getQuery()->shouldReceive('getQuery')->once()->andReturn($baseBuilder);
- $results = $relation->get();
-
- $this->assertInstanceOf(Collection::class, $results);
-
- // Make sure the foreign keys were set on the pivot models...
- $this->assertEquals('user_id', $results[0]->pivot->getForeignKey());
- $this->assertEquals('role_id', $results[0]->pivot->getOtherKey());
-
- $this->assertEquals('taylor', $results[0]->name);
- $this->assertEquals(1, $results[0]->pivot->user_id);
- $this->assertEquals(2, $results[0]->pivot->role_id);
- $this->assertEquals('foo.connection', $results[0]->pivot->getConnectionName());
- $this->assertEquals('dayle', $results[1]->name);
- $this->assertEquals(3, $results[1]->pivot->user_id);
- $this->assertEquals(4, $results[1]->pivot->role_id);
- $this->assertEquals('foo.connection', $results[1]->pivot->getConnectionName());
- $this->assertEquals('user_role', $results[0]->pivot->getTable());
- $this->assertTrue($results[0]->pivot->exists);
- }
-
-
- public function testTimestampsCanBeRetrievedProperly()
- {
- $model1 = new EloquentBelongsToManyModelStub;
- $model1->fill(['name' => 'taylor', 'pivot_user_id' => 1, 'pivot_role_id' => 2]);
- $model2 = new EloquentBelongsToManyModelStub;
- $model2->fill(['name' => 'dayle', 'pivot_user_id' => 3, 'pivot_role_id' => 4]);
- $models = [$model1, $model2];
-
- $baseBuilder = m::mock(\Illuminate\Database\Query\Builder::class);
-
- $relation = $this->getRelation()->withTimestamps();
- $relation->getParent()->shouldReceive('getConnectionName')->andReturn('foo.connection');
- $relation->getQuery()->shouldReceive('addSelect')->once()->with([
- 'roles.*',
- 'user_role.user_id as pivot_user_id',
- 'user_role.role_id as pivot_role_id',
- 'user_role.created_at as pivot_created_at',
- 'user_role.updated_at as pivot_updated_at',
- ])->andReturn($relation->getQuery());
- $relation->getQuery()->shouldReceive('getModels')->once()->andReturn($models);
- $relation->getQuery()->shouldReceive('eagerLoadRelations')->once()->with($models)->andReturn($models);
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); });
- $relation->getQuery()->shouldReceive('getQuery')->once()->andReturn($baseBuilder);
- $results = $relation->get();
- }
-
-
- public function testModelsAreProperlyMatchedToParents()
- {
- $relation = $this->getRelation();
-
- $result1 = new EloquentBelongsToManyModelPivotStub;
- $result1->pivot->user_id = 1;
- $result2 = new EloquentBelongsToManyModelPivotStub;
- $result2->pivot->user_id = 2;
- $result3 = new EloquentBelongsToManyModelPivotStub;
- $result3->pivot->user_id = 2;
-
- $model1 = new EloquentBelongsToManyModelStub;
- $model1->id = 1;
- $model2 = new EloquentBelongsToManyModelStub;
- $model2->id = 2;
- $model3 = new EloquentBelongsToManyModelStub;
- $model3->id = 3;
-
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); });
- $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2, $result3]), 'foo');
-
- $this->assertEquals(1, $models[0]->foo[0]->pivot->user_id);
- $this->assertCount(1, $models[0]->foo);
-
- $this->assertEquals(2, $models[1]->foo[0]->pivot->user_id);
- $this->assertEquals(2, $models[1]->foo[1]->pivot->user_id);
- $this->assertCount(2, $models[1]->foo);
- $this->assertEmpty($models[2]->foo);
- }
-
-
- public function testRelationIsProperlyInitialized()
- {
- $relation = $this->getRelation();
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array = []) { return new Collection($array); });
- $model = m::mock(Model::class);
- $model->shouldReceive('setRelation')->once()->with('foo', m::type(Collection::class));
- $models = $relation->initRelation([$model], 'foo');
-
- $this->assertEquals([$model], $models);
- }
-
-
- public function testEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('user_role.user_id', [1, 2]);
- $model1 = new EloquentBelongsToManyModelStub;
- $model1->id = 1;
- $model2 = new EloquentBelongsToManyModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- public function testAttachInsertsPivotTableRecord()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('insert')->once()->with([['user_id' => 1, 'role_id' => 2, 'foo' => 'bar']])->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $relation->attach(2, ['foo' => 'bar']);
- }
-
-
- public function testAttachMultipleInsertsPivotTableRecord()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('insert')->once()->with(
- [
- ['user_id' => 1, 'role_id' => 2, 'foo' => 'bar'],
- ['user_id' => 1, 'role_id' => 3, 'baz' => 'boom', 'foo' => 'bar'],
- ]
- )->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $relation->attach([2, 3 => ['baz' => 'boom']], ['foo' => 'bar']);
- }
-
-
- public function testAttachInsertsPivotTableRecordWithTimestampsWhenNecessary()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $relation->withTimestamps();
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $carbon = new Carbon;
- $query->shouldReceive('insert')->once()->with(
- [['user_id' => 1, 'role_id' => 2, 'foo' => 'bar', 'created_at' => $carbon, 'updated_at' => $carbon]]
- )->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->getParent()->shouldReceive('freshTimestamp')->once()->andReturn($carbon);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $relation->attach(2, ['foo' => 'bar']);
- }
-
-
- public function testAttachInsertsPivotTableRecordWithACreatedAtTimestamp()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $relation->withPivot('created_at');
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $carbon = new Carbon;
- $query->shouldReceive('insert')->once()->with(
- [['user_id' => 1, 'role_id' => 2, 'foo' => 'bar', 'created_at' => $carbon]]
- )->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->getParent()->shouldReceive('freshTimestamp')->once()->andReturn($carbon);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $relation->attach(2, ['foo' => 'bar']);
- }
-
-
- public function testAttachInsertsPivotTableRecordWithAnUpdatedAtTimestamp()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $relation->withPivot('updated_at');
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $carbon = new Carbon;
- $query->shouldReceive('insert')->once()->with(
- [['user_id' => 1, 'role_id' => 2, 'foo' => 'bar', 'updated_at' => $carbon]]
- )->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->getParent()->shouldReceive('freshTimestamp')->once()->andReturn($carbon);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $relation->attach(2, ['foo' => 'bar']);
- }
-
-
- public function testDetachRemovesPivotTableRecord()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $query->shouldReceive('whereIn')->once()->with('role_id', [1, 2, 3]);
- $query->shouldReceive('delete')->once()->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertTrue($relation->detach([1, 2, 3]));
- }
-
-
- public function testDetachWithSingleIDRemovesPivotTableRecord()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $query->shouldReceive('whereIn')->once()->with('role_id', [1]);
- $query->shouldReceive('delete')->once()->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertTrue($relation->detach([1]));
- }
-
-
- public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $query->shouldReceive('whereIn')->never();
- $query->shouldReceive('delete')->once()->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertTrue($relation->detach());
- }
-
-
- public function testCreateMethodCreatesNewModelAndInsertsAttachmentRecord()
- {
- $relation = $this->getMock(BelongsToMany::class, ['attach'], $this->getRelationArguments());
- $relation->getRelated()->shouldReceive('newInstance')->once()->andReturn($model = m::mock(Model::class))->with(
- ['attributes']
- );
- $model->shouldReceive('save')->once();
- $model->shouldReceive('getKey')->andReturn('foo');
- $relation->expects($this->once())->method('attach')->with('foo', ['joining']);
-
- $this->assertEquals($model, $relation->create(['attributes'], ['joining']));
- }
-
-
- /**
- * @dataProvider syncMethodListProvider
- */
- public function testSyncMethodSyncsIntermediateTableWithGivenArray($list)
- {
- $relation = $this->getMock(BelongsToMany::class, ['attach', 'detach'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $query->shouldReceive('pluck')->once()->with('role_id')->andReturn([1, 2, 3]);
- $relation->expects($this->once())->method('attach')->with($this->equalTo(4), $this->equalTo([]), $this->equalTo(false));
- $relation->expects($this->once())->method('detach')->with($this->equalTo([1]));
- $relation->getRelated()->shouldReceive('touches')->andReturn(false);
- $relation->getParent()->shouldReceive('touches')->andReturn(false);
-
- $this->assertEquals(['attached' => [4], 'detached' => [1], 'updated' => []], $relation->sync($list));
- }
-
-
- public function syncMethodListProvider()
- {
- return [
- [[2, 3, 4]],
- [['2', '3', '4']],
- ];
- }
-
-
- public function testSyncMethodSyncsIntermediateTableWithGivenArrayAndAttributes()
- {
- $relation = $this->getMock(BelongsToMany::class, ['attach', 'detach', 'touchIfTouching', 'updateExistingPivot'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $query->shouldReceive('pluck')->once()->with('role_id')->andReturn([1, 2, 3]);
- $relation->expects($this->once())->method('attach')->with($this->equalTo(4), $this->equalTo(['foo' => 'bar']), $this->equalTo(false));
- $relation->expects($this->once())->method('updateExistingPivot')->with($this->equalTo(3), $this->equalTo(
- ['baz' => 'qux']
- ), $this->equalTo(false))->willReturn(
- true
- );
- $relation->expects($this->once())->method('detach')->with($this->equalTo([1]));
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertEquals(
- ['attached' => [4], 'detached' => [1], 'updated' => [3]], $relation->sync(
- [2, 3 => ['baz' => 'qux'], 4 => ['foo' => 'bar']]
- ));
- }
-
-
- public function testSyncMethodDoesntReturnValuesThatWereNotUpdated()
- {
- $relation = $this->getMock(BelongsToMany::class, ['attach', 'detach', 'touchIfTouching', 'updateExistingPivot'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $query->shouldReceive('pluck')->once()->with('role_id')->andReturn([1, 2, 3]);
- $relation->expects($this->once())->method('attach')->with($this->equalTo(4), $this->equalTo(['foo' => 'bar']), $this->equalTo(false));
- $relation->expects($this->once())->method('updateExistingPivot')->with($this->equalTo(3), $this->equalTo(
- ['baz' => 'qux']
- ), $this->equalTo(false))->willReturn(
- false
- );
- $relation->expects($this->once())->method('detach')->with($this->equalTo([1]));
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertEquals(
- ['attached' => [4], 'detached' => [1], 'updated' => []], $relation->sync(
- [2, 3 => ['baz' => 'qux'], 4 => ['foo' => 'bar']]
- ));
- }
-
-
- public function testTouchMethodSyncsTimestamps()
- {
- $relation = $this->getRelation();
- $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- $carbon = new Carbon;
- $relation->getRelated()->shouldReceive('freshTimestamp')->andReturn($carbon);
- $relation->getRelated()->shouldReceive('getQualifiedKeyName')->andReturn('table.id');
- $relation->getQuery()->shouldReceive('select')->once()->with('table.id')->andReturn($relation->getQuery());
- $relation->getQuery()->shouldReceive('pluck')->once()->with('id')->andReturn([1, 2, 3]);
- $relation->getRelated()->shouldReceive('newQuery')->once()->andReturn($query = m::mock(Builder::class));
- $query->shouldReceive('whereIn')->once()->with('id', [1, 2, 3])->andReturn($query);
- $query->shouldReceive('update')->once()->with(['updated_at' => $carbon]);
-
- $relation->touch();
- }
-
-
- public function testTouchIfTouching()
- {
- $relation = $this->getMock(BelongsToMany::class, ['touch', 'touchingParent'], $this->getRelationArguments());
- $relation->expects($this->once())->method('touchingParent')->willReturn(true);
- $relation->getParent()->shouldReceive('touch')->once();
- $relation->getParent()->shouldReceive('touches')->once()->with('relation_name')->andReturn(true);
- $relation->expects($this->once())->method('touch');
-
- $relation->touchIfTouching();
- }
-
-
- public function testSyncMethodConvertsCollectionToArrayOfKeys()
- {
- $relation = $this->getMock(BelongsToMany::class, ['attach', 'detach', 'touchIfTouching', 'formatSyncList'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $query->shouldReceive('pluck')->once()->with('role_id')->andReturn([1, 2, 3]);
-
- $collection = m::mock(Collection::class);
- $collection->shouldReceive('modelKeys')->once()->andReturn([1, 2, 3]);
- $relation->expects($this->once())->method('formatSyncList')->with([1, 2, 3])->willReturn(
- [1 => [], 2 => [], 3 => []]
- );
- $relation->sync($collection);
- }
-
-
- public function testWherePivotParamsUsedForNewQueries()
- {
- $relation = $this->getMock(BelongsToMany::class, ['attach', 'detach', 'touchIfTouching', 'formatSyncList'], $this->getRelationArguments());
-
- // we expect to call $relation->wherePivot()
- $relation->getQuery()->shouldReceive('where')->once()->andReturn($relation);
-
- // Our sync() call will produce a new query
- $mockQueryBuilder = m::mock('stdClass');
- $query = m::mock('stdClass');
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder);
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
-
- // BelongsToMany::newPivotStatement() sets this
- $query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
-
- // BelongsToMany::newPivotQuery() sets this
- $query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
-
- // This is our test! The wherePivot() params also need to be called
- $query->shouldReceive('where')->once()->with('foo', '=', 'bar')->andReturn($query);
-
- // This is so $relation->sync() works
- $query->shouldReceive('pluck')->once()->with('role_id')->andReturn([1, 2, 3]);
- $relation->expects($this->once())->method('formatSyncList')->with([1, 2, 3])->willReturn(
- [1 => [], 2 => [], 3 => []]
- );
-
-
- $relation = $relation->wherePivot('foo', '=', 'bar'); // these params are to be stored
- $relation->sync([1,2,3]); // triggers the whole process above
- }
-
-
- public function getRelation()
- {
- [$builder, $parent] = $this->getRelationArguments();
-
- return new BelongsToMany($builder, $parent, 'user_role', 'user_id', 'role_id', 'relation_name');
- }
-
-
- public function getRelationArguments()
- {
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getKey')->andReturn(1);
- $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
- $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
-
- $builder = m::mock(Builder::class);
- $related = m::mock(Model::class);
- $builder->shouldReceive('getModel')->andReturn($related);
-
- $related->shouldReceive('getTable')->andReturn('roles');
- $related->shouldReceive('getKeyName')->andReturn('id');
- $related->shouldReceive('newPivot')->andReturnUsing(function()
- {
- $reflector = new ReflectionClass(Pivot::class);
- return $reflector->newInstanceArgs(func_get_args());
- });
-
- $builder->shouldReceive('join')->once()->with('user_role', 'roles.id', '=', 'user_role.role_id');
- $builder->shouldReceive('where')->once()->with('user_role.user_id', '=', 1);
-
- return [$builder, $parent, 'user_role', 'user_id', 'role_id', 'relation_name'];
- }
-
-}
-
-class EloquentBelongsToManyModelStub extends Illuminate\Database\Eloquent\Model {
- protected array $guarded = [];
-}
-
-class EloquentBelongsToManyModelPivotStub extends Illuminate\Database\Eloquent\Model {
- public $pivot;
- public function __construct()
- {
- $this->pivot = new EloquentBelongsToManyPivotStub;
- }
-}
-
-class EloquentBelongsToManyPivotStub {
- public $user_id;
-}
diff --git a/tests/Database/DatabaseEloquentBelongsToTest.php b/tests/Database/DatabaseEloquentBelongsToTest.php
deleted file mode 100755
index 43eef7b42..000000000
--- a/tests/Database/DatabaseEloquentBelongsToTest.php
+++ /dev/null
@@ -1,108 +0,0 @@
-getRelation();
- $mock = m::mock(Model::class);
- $mock->shouldReceive('fill')->once()->with(['attributes'])->andReturn($mock);
- $mock->shouldReceive('save')->once()->andReturn(true);
- $relation->getQuery()->shouldReceive('first')->once()->andReturn($mock);
-
- $this->assertTrue($relation->update(['attributes']));
- }
-
-
- public function testEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('relation.id', ['foreign.value', 'foreign.value.two']
- );
- $models = [new EloquentBelongsToModelStub, new EloquentBelongsToModelStub, new AnotherEloquentBelongsToModelStub];
- $relation->addEagerConstraints($models);
- }
-
-
- public function testRelationIsProperlyInitialized()
- {
- $relation = $this->getRelation();
- $model = m::mock(Model::class);
- $model->shouldReceive('setRelation')->once()->with('foo', null);
- $models = $relation->initRelation([$model], 'foo');
-
- $this->assertEquals([$model], $models);
- }
-
-
- public function testModelsAreProperlyMatchedToParents()
- {
- $relation = $this->getRelation();
- $result1 = m::mock('stdClass');
- $result1->shouldReceive('getAttribute')->with('id')->andReturn(1);
- $result2 = m::mock('stdClass');
- $result2->shouldReceive('getAttribute')->with('id')->andReturn(2);
- $model1 = new EloquentBelongsToModelStub;
- $model1->foreign_key = 1;
- $model2 = new EloquentBelongsToModelStub;
- $model2->foreign_key = 2;
- $models = $relation->match([$model1, $model2], new Collection([$result1, $result2]), 'foo');
-
- $this->assertEquals(1, $models[0]->foo->getAttribute('id'));
- $this->assertEquals(2, $models[1]->foo->getAttribute('id'));
- }
-
-
- public function testAssociateMethodSetsForeignKeyOnModel()
- {
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->once()->with('foreign_key')->andReturn('foreign.value');
- $relation = $this->getRelation($parent);
- $associate = m::mock(Model::class);
- $associate->shouldReceive('getAttribute')->once()->with('id')->andReturn(1);
- $parent->shouldReceive('setAttribute')->once()->with('foreign_key', 1);
- $parent->shouldReceive('setRelation')->once()->with('relation', $associate);
-
- $relation->associate($associate);
- }
-
-
- protected function getRelation($parent = null)
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value');
- $related = m::mock(Model::class);
- $related->shouldReceive('getKeyName')->andReturn('id');
- $related->shouldReceive('getTable')->andReturn('relation');
- $builder->shouldReceive('getModel')->andReturn($related);
- $parent = $parent ?: new EloquentBelongsToModelStub;
- return new BelongsTo($builder, $parent, 'foreign_key', 'id', 'relation');
- }
-
-}
-
-class EloquentBelongsToModelStub extends Illuminate\Database\Eloquent\Model {
-
- public $foreign_key = 'foreign.value';
-
-}
-
-class AnotherEloquentBelongsToModelStub extends Illuminate\Database\Eloquent\Model {
-
- public $foreign_key = 'foreign.value.two';
-
-}
diff --git a/tests/Database/DatabaseEloquentBuilderTest.php b/tests/Database/DatabaseEloquentBuilderTest.php
deleted file mode 100755
index 1dfec3f21..000000000
--- a/tests/Database/DatabaseEloquentBuilderTest.php
+++ /dev/null
@@ -1,629 +0,0 @@
-getMockQueryBuilder()]);
- $builder->setModel($this->getMockModel());
- $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
- $builder->shouldReceive('first')->with(['column'])->andReturn('baz');
-
- $result = $builder->find('bar', ['column']);
- $this->assertEquals('baz', $result);
- }
-
-
- public function testFindOrNewMethodModelFound()
- {
- $model = $this->getMockModel();
- $model->shouldReceive('findOrNew')->once()->andReturn('baz');
-
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', [$this->getMockQueryBuilder()]);
- $builder->setModel($model);
- $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
- $builder->shouldReceive('first')->with(['column'])->andReturn('baz');
-
- $expected = $model->findOrNew('bar', ['column']);
- $result = $builder->find('bar', ['column']);
- $this->assertEquals($expected, $result);
- }
-
-
- public function testFindOrNewMethodModelNotFound()
- {
- $model = $this->getMockModel();
- $model->shouldReceive('findOrNew')->once()->andReturn(m::mock(Model::class));
-
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', [$this->getMockQueryBuilder()]);
- $builder->setModel($model);
- $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
- $builder->shouldReceive('first')->with(['column'])->andReturn(null);
-
- $result = $model->findOrNew('bar', ['column']);
- $findResult = $builder->find('bar', ['column']);
- $this->assertNull($findResult);
- $this->assertInstanceOf(Model::class, $result);
- }
-
- public function testFindOrFailMethodThrowsModelNotFoundException()
- {
- $this->expectException(Illuminate\Database\Eloquent\ModelNotFoundException::class);
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', [$this->getMockQueryBuilder()]);
- $builder->setModel($this->getMockModel());
- $builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
- $builder->shouldReceive('first')->with(['column'])->andReturn(null);
- $result = $builder->findOrFail('bar', ['column']);
- }
-
- public function testFirstOrFailMethodThrowsModelNotFoundException()
- {
- $this->expectException(Illuminate\Database\Eloquent\ModelNotFoundException::class);
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', [$this->getMockQueryBuilder()]);
- $builder->setModel($this->getMockModel());
- $builder->shouldReceive('first')->with(['column'])->andReturn(null);
- $result = $builder->firstOrFail(['column']);
- }
-
-
- public function testFindWithMany()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[get]', [$this->getMockQueryBuilder()]);
- $builder->getQuery()->shouldReceive('whereIn')->once()->with('foo_table.foo', [1, 2]);
- $builder->setModel($this->getMockModel());
- $builder->shouldReceive('get')->with(['column'])->andReturn('baz');
-
- $result = $builder->find([1, 2], ['column']);
- $this->assertEquals('baz', $result);
- }
-
-
- public function testFirstMethod()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[get,take]', [$this->getMockQueryBuilder()]);
- $builder->shouldReceive('take')->with(1)->andReturn($builder);
- $builder->shouldReceive('get')->with(['*'])->andReturn(new Collection(['bar']));
-
- $result = $builder->first();
- $this->assertEquals('bar', $result);
- }
-
-
- public function testGetMethodLoadsModelsAndHydratesEagerRelations()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[getModels,eagerLoadRelations]', [$this->getMockQueryBuilder()]
- );
- $builder->shouldReceive('getModels')->with(['foo'])->andReturn(['bar']);
- $builder->shouldReceive('eagerLoadRelations')->with(['bar'])->andReturn(['bar', 'baz']);
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('newCollection')->with(['bar', 'baz'])->andReturn(new Collection(
- ['bar', 'baz']
- ));
-
- $results = $builder->get(['foo']);
- $this->assertEquals(['bar', 'baz'], $results->all());
- }
-
-
- public function testGetMethodDoesntHydrateEagerRelationsWhenNoResultsAreReturned()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[getModels,eagerLoadRelations]', [$this->getMockQueryBuilder()]
- );
- $builder->shouldReceive('getModels')->with(['foo'])->andReturn([]);
- $builder->shouldReceive('eagerLoadRelations')->never();
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('newCollection')->with([])->andReturn(new Collection([]));
-
- $results = $builder->get(['foo']);
- $this->assertEquals([], $results->all());
- }
-
-
-public function testValueMethodWithModelFound()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', [$this->getMockQueryBuilder()]);
- $mockModel = new StdClass;
- $mockModel->name = 'foo';
- $builder->shouldReceive('first')->with(['name'])->andReturn($mockModel);
-
- $this->assertEquals('foo', $builder->value('name'));
- }
-
-
- public function testValueMethodWithModelNotFound()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', [$this->getMockQueryBuilder()]);
- $builder->shouldReceive('first')->with(['name'])->andReturn(null);
-
- $this->assertNull($builder->value('name'));
- }
-
-
- public function testChunkExecuteCallbackOverPaginatedRequest()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[forPage,get]', [$this->getMockQueryBuilder()]);
- $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturn($builder);
- $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturn($builder);
- $builder->shouldReceive('forPage')->once()->with(3, 2)->andReturn($builder);
- $builder->shouldReceive('get')->times(3)->andReturn(['foo1', 'foo2'], ['foo3'], []);
-
- $callbackExecutionAssertor = m::mock('StdClass');
- $callbackExecutionAssertor->shouldReceive('doSomething')->with('foo1')->once();
- $callbackExecutionAssertor->shouldReceive('doSomething')->with('foo2')->once();
- $callbackExecutionAssertor->shouldReceive('doSomething')->with('foo3')->once();
-
- $builder->chunk(2, function($results) use($callbackExecutionAssertor) {
- foreach ($results as $result) {
- $callbackExecutionAssertor->doSomething($result);
- }
- });
- }
-
-
- public function testListsReturnsTheMutatedAttributesOfAModel()
- {
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(['bar', 'baz']);
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(true);
- $builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestListsStub(
- ['name' => 'bar']
- ));
- $builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestListsStub(
- ['name' => 'baz']
- ));
-
- $this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name'));
- }
-
-
- public function testListsWithoutModelGetterJustReturnTheAttributesFoundInDatabase()
- {
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(['bar', 'baz']);
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(false);
-
- $this->assertEquals(['bar', 'baz'], $builder->pluck('name'));
- }
-
-
- public function testMacrosAreCalledOnBuilder()
- {
- unset($_SERVER['__test.builder']);
- $builder = new Illuminate\Database\Eloquent\Builder(new Illuminate\Database\Query\Builder(
- m::mock(ConnectionInterface::class),
- m::mock(Grammar::class),
- m::mock(Processor::class)
- ));
- $builder->macro('fooBar', function($builder)
- {
- $_SERVER['__test.builder'] = $builder;
-
- return $builder;
- });
- $result = $builder->fooBar();
-
- $this->assertEquals($builder, $result);
- $this->assertEquals($builder, $_SERVER['__test.builder']);
- unset($_SERVER['__test.builder']);
- }
-
-
- public function testPaginateMethod()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[get]', [$this->getMockQueryBuilder()]);
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('getPerPage')->once()->andReturn(15);
- $builder->getQuery()->shouldReceive('getPaginationCount')->once()->andReturn(10);
- $conn = m::mock('stdClass');
- $paginator = m::mock('stdClass');
- $paginator->shouldReceive('getCurrentPage')->once()->andReturn(1);
- $conn->shouldReceive('getPaginator')->once()->andReturn($paginator);
- $builder->getQuery()->shouldReceive('getConnection')->once()->andReturn($conn);
- $builder->getQuery()->shouldReceive('forPage')->once()->with(1, 15);
- $builder->shouldReceive('get')->with(['*'])->andReturn(new Collection(['results']));
- $paginator->shouldReceive('make')->once()->with(['results'], 10, 15)->andReturn(['results']);
-
- $this->assertEquals(['results'], $builder->paginate());
- }
-
-
- public function testPaginateMethodWithGroupedQuery()
- {
- $query = $this->getMock(\Illuminate\Database\Query\Builder::class, ['from', 'getConnection'], [
- m::mock(ConnectionInterface::class),
- m::mock(Grammar::class),
- m::mock(Processor::class),
- ]);
- $query->expects($this->once())->method('from')->willReturn('foo_table');
- $builder = $this->getMock(Builder::class, ['get'], [$query]);
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('getPerPage')->once()->andReturn(2);
- $conn = m::mock('stdClass');
- $paginator = m::mock('stdClass');
- $paginator->shouldReceive('getCurrentPage')->once()->andReturn(2);
- $conn->shouldReceive('getPaginator')->once()->andReturn($paginator);
- $query->expects($this->once())->method('getConnection')->willReturn($conn);
- $builder->expects($this->once())->method('get')->with($this->equalTo(['*']))->willReturn(
- new Collection(['foo', 'bar', 'baz'])
- );
- $paginator->shouldReceive('make')->once()->with(['baz'], 3, 2)->andReturn(['results']);
-
- $this->assertEquals(['results'], $builder->groupBy('foo')->paginate());
- }
-
-
- public function testQuickPaginateMethod()
- {
- $query = $this->getMock(\Illuminate\Database\Query\Builder::class, ['from', 'getConnection', 'skip', 'take'], [
- m::mock(ConnectionInterface::class),
- m::mock(Grammar::class),
- m::mock(Processor::class),
- ]);
- $query->expects($this->once())->method('from')->willReturn('foo_table');
- $builder = $this->getMock(Builder::class, ['get'], [$query]);
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('getPerPage')->once()->andReturn(15);
- $conn = m::mock('stdClass');
- $paginator = m::mock('stdClass');
- $paginator->shouldReceive('getCurrentPage')->once()->andReturn(1);
- $conn->shouldReceive('getPaginator')->once()->andReturn($paginator);
- $query->expects($this->once())->method('getConnection')->willReturn($conn);
- $query->expects($this->once())->method('skip')->with(0)->willReturn($query);
- $query->expects($this->once())->method('take')->with(16)->willReturn($query);
- $builder->expects($this->once())->method('get')->with($this->equalTo(['*']))->willReturn(
- new Collection(['results'])
- );
- $paginator->shouldReceive('make')->once()->with(['results'], 15)->andReturn(['results']);
-
- $this->assertEquals(['results'], $builder->simplePaginate());
- }
-
-
- public function testGetModelsProperlyHydratesModels()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[get]', [$this->getMockQueryBuilder()]);
- $records[] = ['name' => 'taylor', 'age' => 26];
- $records[] = ['name' => 'dayle', 'age' => 28];
- $builder->getQuery()->shouldReceive('get')->once()->with(['foo'])->andReturn($records);
- $model = m::mock('Illuminate\Database\Eloquent\Model[getTable,getConnectionName,newInstance]');
- $model->shouldReceive('getTable')->once()->andReturn('foo_table');
- $builder->setModel($model);
- $model->shouldReceive('getConnectionName')->once()->andReturn('foo_connection');
- $model->shouldReceive('newInstance')->andReturnUsing(function() { return new EloquentBuilderTestModelStub; });
- $models = $builder->getModels(['foo']);
-
- $this->assertEquals('taylor', $models[0]->name);
- $this->assertEquals($models[0]->getAttributes(), $models[0]->getOriginal());
- $this->assertEquals('dayle', $models[1]->name);
- $this->assertEquals($models[1]->getAttributes(), $models[1]->getOriginal());
- $this->assertEquals('foo_connection', $models[0]->getConnectionName());
- $this->assertEquals('foo_connection', $models[1]->getConnectionName());
- }
-
-
- public function testEagerLoadRelationsLoadTopLevelRelationships()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[loadRelation]', [$this->getMockQueryBuilder()]);
- $nop1 = function() {};
- $nop2 = function() {};
- $builder->setEagerLoads(['foo' => $nop1, 'foo.bar' => $nop2]);
- $builder->shouldAllowMockingProtectedMethods()->shouldReceive('loadRelation')->with(['models'], 'foo', $nop1)->andReturn(
- ['foo']
- );
-
- $results = $builder->eagerLoadRelations(['models']);
- $this->assertEquals(['foo'], $results);
- }
-
-
- public function testRelationshipEagerLoadProcess()
- {
- $builder = m::mock('Illuminate\Database\Eloquent\Builder[getRelation]', [$this->getMockQueryBuilder()]);
- $builder->setEagerLoads(['orders' => function($query) { $_SERVER['__eloquent.constrain'] = $query; }]);
- $relation = m::mock('stdClass');
- $relation->shouldReceive('addEagerConstraints')->once()->with(['models']);
- $relation->shouldReceive('initRelation')->once()->with(['models'], 'orders')->andReturn(['models']);
- $relation->shouldReceive('getEager')->once()->andReturn(['results']);
- $relation->shouldReceive('match')->once()->with(['models'], ['results'], 'orders')->andReturn(['models.matched']
- );
- $builder->shouldReceive('getRelation')->once()->with('orders')->andReturn($relation);
- $results = $builder->eagerLoadRelations(['models']);
-
- $this->assertEquals(['models.matched'], $results);
- $this->assertEquals($relation, $_SERVER['__eloquent.constrain']);
- unset($_SERVER['__eloquent.constrain']);
- }
-
-
- public function testGetRelationProperlySetsNestedRelationships()
- {
- $builder = $this->getBuilder();
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('orders')->once()->andReturn($relation = m::mock('stdClass'));
- $relationQuery = m::mock('stdClass');
- $relation->shouldReceive('getQuery')->andReturn($relationQuery);
- $relationQuery->shouldReceive('with')->once()->with(['lines' => null, 'lines.details' => null]);
- $builder->setEagerLoads(['orders' => null, 'orders.lines' => null, 'orders.lines.details' => null]);
-
- $relation = $builder->getRelation('orders');
- }
-
-
- public function testGetRelationProperlySetsNestedRelationshipsWithSimilarNames()
- {
- $builder = $this->getBuilder();
- $builder->setModel($this->getMockModel());
- $builder->getModel()->shouldReceive('orders')->once()->andReturn($relation = m::mock('stdClass'));
- $builder->getModel()->shouldReceive('ordersGroups')->once()->andReturn($groupsRelation = m::mock('stdClass'));
-
- $relationQuery = m::mock('stdClass');
- $relation->shouldReceive('getQuery')->andReturn($relationQuery);
-
- $groupRelationQuery = m::mock('stdClass');
- $groupsRelation->shouldReceive('getQuery')->andReturn($groupRelationQuery);
- $groupRelationQuery->shouldReceive('with')->once()->with(['lines' => null, 'lines.details' => null]);
-
- $builder->setEagerLoads(
- ['orders' => null, 'ordersGroups' => null, 'ordersGroups.lines' => null, 'ordersGroups.lines.details' => null]
- );
-
- $builder->getRelation('orders');
- $builder->getRelation('ordersGroups');
- }
-
-
- public function testEagerLoadParsingSetsProperRelationships()
- {
- $builder = $this->getBuilder();
- $builder->with(['orders', 'orders.lines']);
- $eagers = $builder->getEagerLoads();
-
- $this->assertEquals(['orders', 'orders.lines'], array_keys($eagers));
- $this->assertInstanceOf('Closure', $eagers['orders']);
- $this->assertInstanceOf('Closure', $eagers['orders.lines']);
-
- $builder = $this->getBuilder();
- $builder->with('orders', 'orders.lines');
- $eagers = $builder->getEagerLoads();
-
- $this->assertEquals(['orders', 'orders.lines'], array_keys($eagers));
- $this->assertInstanceOf('Closure', $eagers['orders']);
- $this->assertInstanceOf('Closure', $eagers['orders.lines']);
-
- $builder = $this->getBuilder();
- $builder->with(['orders.lines']);
- $eagers = $builder->getEagerLoads();
-
- $this->assertEquals(['orders', 'orders.lines'], array_keys($eagers));
- $this->assertInstanceOf('Closure', $eagers['orders']);
- $this->assertInstanceOf('Closure', $eagers['orders.lines']);
-
- $builder = $this->getBuilder();
- $builder->with(['orders' => function() { return 'foo'; }]);
- $eagers = $builder->getEagerLoads();
-
- $this->assertEquals('foo', $eagers['orders']());
-
- $builder = $this->getBuilder();
- $builder->with(['orders.lines' => function() { return 'foo'; }]);
- $eagers = $builder->getEagerLoads();
-
- $this->assertInstanceOf('Closure', $eagers['orders']);
- $this->assertNull($eagers['orders']());
- $this->assertEquals('foo', $eagers['orders.lines']());
- }
-
-
- public function testQueryPassThru()
- {
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('foobar')->once()->andReturn('foo');
-
- $this->assertInstanceOf(Builder::class, $builder->foobar());
-
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('insert')->once()->with(['bar'])->andReturn('foo');
-
- $this->assertEquals('foo', $builder->insert(['bar']));
- }
-
-
- public function testQueryScopes()
- {
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('from');
- $builder->getQuery()->shouldReceive('where')->once()->with('foo', 'bar');
- $builder->setModel($model = new EloquentBuilderTestScopeStub);
- $result = $builder->approved();
-
- $this->assertEquals($builder, $result);
- }
-
-
- public function testNestedWhere()
- {
- $nestedQuery = m::mock(Builder::class);
- $nestedRawQuery = $this->getMockQueryBuilder();
- $nestedQuery->shouldReceive('getQuery')->once()->andReturn($nestedRawQuery);
- $model = $this->getMockModel()->makePartial();
- $model->shouldReceive('newQueryWithoutScopes')->once()->andReturn($nestedQuery);
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('from');
- $builder->setModel($model);
- $builder->getQuery()->shouldReceive('addNestedWhereQuery')->once()->with($nestedRawQuery, 'and');
- $nestedQuery->shouldReceive('foo')->once();
-
- $result = $builder->where(function($query) { $query->foo(); });
- $this->assertEquals($builder, $result);
- }
-
-
- public function testRealNestedWhereWithScopes()
- {
- $model = new EloquentBuilderTestNestedStub;
- $this->mockConnectionForModel($model, 'SQLite');
- $query = $model->newQuery()->where('foo', '=', 'bar')->where(function($query) { $query->where('baz', '>', 9000); });
- $this->assertEquals('select * from "table" where "table"."deleted_at" is null and "foo" = ? and ("baz" > ?)', $query->toSql());
- $this->assertEquals(['bar', 9000], $query->getBindings());
- }
-
-
- public function testSimpleWhere()
- {
- $builder = $this->getBuilder();
- $builder->getQuery()->shouldReceive('where')->once()->with('foo', '=', 'bar');
- $result = $builder->where('foo', '=', 'bar');
- $this->assertEquals($result, $builder);
- }
-
-
- public function testDeleteOverride()
- {
- $builder = $this->getBuilder();
- $builder->onDelete(function($builder)
- {
- return ['foo' => $builder];
- });
- $this->assertEquals(['foo' => $builder], $builder->delete());
- }
-
-
- public function testHasNestedWithConstraints()
- {
- $model = new EloquentBuilderTestModelParentStub;
-
- $builder = $model->whereHas('foo', function ($q) {
- $q->whereHas('bar', function ($q) {
- $q->where('baz', 'bam');
- });
- })->toSql();
-
- $result = $model->whereHas('foo.bar', function ($q) {
- $q->where('baz', 'bam');
- })->toSql();
-
- $this->assertEquals($builder, $result);
- }
-
-
- public function testHasNested()
- {
- $model = new EloquentBuilderTestModelParentStub;
-
- $builder = $model->whereHas('foo', function ($q) {
- $q->has('bar');
- });
-
- $result = $model->has('foo.bar')->toSql();
-
- $this->assertEquals($builder->toSql(), $result);
- }
-
-
- protected function mockConnectionForModel($model, $database)
- {
- $grammarClass = 'Illuminate\Database\Query\Grammars\\'.$database.'Grammar';
- $processorClass = 'Illuminate\Database\Query\Processors\\'.$database.'Processor';
- $grammar = new $grammarClass;
- $processor = new $processorClass;
- $connection = m::mock(Connection::class, ['getQueryGrammar' => $grammar, 'getPostProcessor' => $processor]
- );
- $resolver = m::mock(ConnectionResolverInterface::class, ['connection' => $connection]);
- $class = get_class($model);
- $class::setConnectionResolver($resolver);
- }
-
-
- protected function getBuilder()
- {
- return new Builder($this->getMockQueryBuilder());
- }
-
-
- protected function getMockModel()
- {
- $model = m::mock(Model::class);
- $model->shouldReceive('getKeyName')->andReturn('foo');
- $model->shouldReceive('getTable')->andReturn('foo_table');
- $model->shouldReceive('getQualifiedKeyName')->andReturn('foo_table.foo');
- return $model;
- }
-
-
- protected function getMockQueryBuilder()
- {
- $query = m::mock(\Illuminate\Database\Query\Builder::class);
- $query->shouldReceive('from')->with('foo_table');
- return $query;
- }
-
-}
-
-class EloquentBuilderTestModelStub extends Illuminate\Database\Eloquent\Model {}
-
-class EloquentBuilderTestScopeStub extends Illuminate\Database\Eloquent\Model {
- public function scopeApproved($query)
- {
- $query->where('foo', 'bar');
- }
-}
-
-class EloquentBuilderTestWithTrashedStub extends Illuminate\Database\Eloquent\Model {
- use Illuminate\Database\Eloquent\SoftDeletes;
- protected string $table = 'table';
- #[\Override]
- public function getKeyName(): string { return 'foo'; }
-}
-
-class EloquentBuilderTestNestedStub extends Illuminate\Database\Eloquent\Model {
- protected string $table = 'table';
- use Illuminate\Database\Eloquent\SoftDeletes;
-}
-
-class EloquentBuilderTestListsStub {
- protected $attributes;
- public function __construct($attributes)
- {
- $this->attributes = $attributes;
- }
- public function __get($key)
- {
- return 'foo_' . $this->attributes[$key];
- }
-}
-
-class EloquentBuilderTestModelParentStub extends Illuminate\Database\Eloquent\Model {
- public function foo()
- {
- return $this->belongsTo('EloquentBuilderTestModelCloseRelatedStub');
- }
-}
-
-class EloquentBuilderTestModelCloseRelatedStub extends Illuminate\Database\Eloquent\Model {
- public function bar()
- {
- return $this->hasMany('EloquentBuilderTestModelFarRelatedStub');
- }
-}
-
-class EloquentBuilderTestModelFarRelatedStub extends Illuminate\Database\Eloquent\Model {}
diff --git a/tests/Database/DatabaseEloquentCollectionTest.php b/tests/Database/DatabaseEloquentCollectionTest.php
deleted file mode 100755
index e8b2d8cdc..000000000
--- a/tests/Database/DatabaseEloquentCollectionTest.php
+++ /dev/null
@@ -1,225 +0,0 @@
-add('bar')->add('baz');
- $this->assertEquals(['foo', 'bar', 'baz'], $c->all());
- }
-
-
- public function testGettingMaxItemsFromCollection()
- {
- $c = new Collection([(object) ['foo' => 10], (object) ['foo' => 20]]);
- $this->assertEquals(20, $c->max('foo'));
- }
-
-
- public function testGettingMinItemsFromCollection()
- {
- $c = new Collection([(object) ['foo' => 10], (object) ['foo' => 20]]);
- $this->assertEquals(10, $c->min('foo'));
- }
-
-
- public function testContainsIndicatesIfModelInArray()
- {
- $mockModel = m::mock(Model::class);
- $mockModel->shouldReceive('getKey')->andReturn(1);
- $mockModel2 = m::mock(Model::class);
- $mockModel2->shouldReceive('getKey')->andReturn(2);
- $mockModel3 = m::mock(Model::class);
- $mockModel3->shouldReceive('getKey')->andReturn(3);
- $c = new Collection([$mockModel, $mockModel2]);
-
- $this->assertTrue($c->contains($mockModel));
- $this->assertTrue($c->contains($mockModel2));
- $this->assertFalse($c->contains($mockModel3));
- }
-
-
- public function testContainsIndicatesIfKeyedModelInArray()
- {
- $mockModel = m::mock(Model::class);
- $mockModel->shouldReceive('getKey')->andReturn(1);
- $c = new Collection([$mockModel]);
- $mockModel2 = m::mock(Model::class);
- $mockModel2->shouldReceive('getKey')->andReturn(2);
- $c->add($mockModel2);
-
- $this->assertTrue($c->contains(1));
- $this->assertTrue($c->contains(2));
- $this->assertFalse($c->contains(3));
- }
-
-
- public function testFindMethodFindsModelById()
- {
- $mockModel = m::mock(Model::class);
- $mockModel->shouldReceive('getKey')->andReturn(1);
- $c = new Collection([$mockModel]);
-
- $this->assertSame($mockModel, $c->find(1));
- $this->assertSame('taylor', $c->find(2, 'taylor'));
- }
-
-
- public function testLoadMethodEagerLoadsGivenRelationships()
- {
- $c = $this->getMock(Collection::class, ['first'], [['foo']]);
- $mockItem = m::mock('StdClass');
- $c->expects($this->once())->method('first')->willReturn($mockItem);
- $mockItem->shouldReceive('newQuery')->once()->andReturn($mockItem);
- $mockItem->shouldReceive('with')->with(['bar', 'baz'])->andReturn($mockItem);
- $mockItem->shouldReceive('eagerLoadRelations')->once()->with(['foo'])->andReturn(['results']);
- $c->load('bar', 'baz');
-
- $this->assertEquals(['results'], $c->all());
- }
-
-
- public function testCollectionDictionaryReturnsModelKeys()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn(2);
-
- $three = m::mock(Model::class);
- $three->shouldReceive('getKey')->andReturn(3);
-
- $c = new Collection([$one, $two, $three]);
-
- $this->assertEquals([1,2,3], $c->modelKeys());
- }
-
-
- public function testCollectionMergesWithGivenCollection()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn(2);
-
- $three = m::mock(Model::class);
- $three->shouldReceive('getKey')->andReturn(3);
-
- $c1 = new Collection([$one, $two]);
- $c2 = new Collection([$two, $three]);
-
- $this->assertEquals(new Collection([$one, $two, $three]), $c1->merge($c2));
- }
-
-
- public function testCollectionDiffsWithGivenCollection()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn(2);
-
- $three = m::mock(Model::class);
- $three->shouldReceive('getKey')->andReturn(3);
-
- $c1 = new Collection([$one, $two]);
- $c2 = new Collection([$two, $three]);
-
- $this->assertEquals(new Collection([$one]), $c1->diff($c2));
- }
-
-
- public function testCollectionIntersectsWithGivenCollection()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn(2);
-
- $three = m::mock(Model::class);
- $three->shouldReceive('getKey')->andReturn(3);
-
- $c1 = new Collection([$one, $two]);
- $c2 = new Collection([$two, $three]);
-
- $this->assertEquals(new Collection([$two]), $c1->intersect($c2));
- }
-
-
- public function testCollectionReturnsUniqueItems()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn(2);
-
- $c = new Collection([$one, $two, $two]);
-
- $this->assertEquals(new Collection([$one, $two]), $c->unique());
- }
-
-
- public function testPluck()
- {
- $data = new Collection(
- [(object) ['name' => 'taylor', 'email' => 'foo'], (object) ['name' => 'dayle', 'email' => 'bar']]
- );
- $this->assertEquals(['taylor' => 'foo', 'dayle' => 'bar'], $data->pluck('email', 'name')->all());
- $this->assertEquals(['foo', 'bar'], $data->pluck('email')->all());
- }
-
-
- public function testOnlyReturnsCollectionWithGivenModelKeys()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn(2);
-
- $three = m::mock(Model::class);
- $three->shouldReceive('getKey')->andReturn(3);
-
- $c = new Collection([$one, $two, $three]);
-
- $this->assertEquals(new Collection([$one]), $c->only(1));
- $this->assertEquals(new Collection([$two, $three]), $c->only([2, 3]));
- }
-
-
- public function testExceptReturnsCollectionWithoutGivenModelKeys()
- {
- $one = m::mock(Model::class);
- $one->shouldReceive('getKey')->andReturn(1);
-
- $two = m::mock(Model::class);
- $two->shouldReceive('getKey')->andReturn('2');
-
- $three = m::mock(Model::class);
- $three->shouldReceive('getKey')->andReturn(3);
-
- $c = new Collection([$one, $two, $three]);
-
- $this->assertEquals(new Collection([$one, $three]), $c->except(2));
- $this->assertEquals(new Collection([$one]), $c->except([2, 3]));
- }
-
-}
diff --git a/tests/Database/DatabaseEloquentHasManyTest.php b/tests/Database/DatabaseEloquentHasManyTest.php
deleted file mode 100755
index 9b1d6565f..000000000
--- a/tests/Database/DatabaseEloquentHasManyTest.php
+++ /dev/null
@@ -1,115 +0,0 @@
-getRelation();
- $created = $this->getMock(Model::class, ['save', 'getKey', 'setAttribute']);
- $created->expects($this->once())->method('save')->willReturn(true);
- $relation->getRelated()->shouldReceive('newInstance')->once()->with(['name' => 'taylor'])->andReturn($created);
- $created->expects($this->once())->method('setAttribute')->with('foreign_key', 1);
-
- $this->assertEquals($created, $relation->create(['name' => 'taylor']));
- }
-
-
- public function testUpdateMethodUpdatesModelsWithTimestamps()
- {
- $relation = $this->getRelation();
- $relation->getRelated()->shouldReceive('usesTimestamps')->once()->andReturn(true);
- $relation->getRelated()->shouldReceive('freshTimestamp')->once()->andReturn($carbon = new Carbon());
- $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- $relation->getQuery()->shouldReceive('update')->once()->with(['foo' => 'bar', 'updated_at' => $carbon])->andReturn('results');
-
- $this->assertEquals('results', $relation->update(['foo' => 'bar']));
- }
-
-
- public function testRelationIsProperlyInitialized()
- {
- $relation = $this->getRelation();
- $model = m::mock(Model::class);
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array = []) { return new Collection($array); });
- $model->shouldReceive('setRelation')->once()->with('foo', m::type(Collection::class));
- $models = $relation->initRelation([$model], 'foo');
-
- $this->assertEquals([$model], $models);
- }
-
-
- public function testEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('table.foreign_key', [1, 2]);
- $model1 = new EloquentHasManyModelStub;
- $model1->id = 1;
- $model2 = new EloquentHasManyModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- public function testModelsAreProperlyMatchedToParents()
- {
- $relation = $this->getRelation();
-
- $result1 = new EloquentHasManyModelStub;
- $result1->foreign_key = 1;
- $result2 = new EloquentHasManyModelStub;
- $result2->foreign_key = 2;
- $result3 = new EloquentHasManyModelStub;
- $result3->foreign_key = 2;
-
- $model1 = new EloquentHasManyModelStub;
- $model1->id = 1;
- $model2 = new EloquentHasManyModelStub;
- $model2->id = 2;
- $model3 = new EloquentHasManyModelStub;
- $model3->id = 3;
-
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); });
- $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2, $result3]), 'foo');
-
- $this->assertEquals(1, $models[0]->foo[0]->foreign_key);
- $this->assertCount(1, $models[0]->foo);
- $this->assertEquals(2, $models[1]->foo[0]->foreign_key);
- $this->assertEquals(2, $models[1]->foo[1]->foreign_key);
- $this->assertCount(2, $models[1]->foo);
- $this->assertEmpty($models[2]->foo);
- }
-
-
- protected function getRelation()
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('where')->with('table.foreign_key', '=', 1);
- $related = m::mock(Model::class);
- $builder->shouldReceive('getModel')->andReturn($related);
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
- $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
- $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- return new HasMany($builder, $parent, 'table.foreign_key', 'id');
- }
-
-}
-
-class EloquentHasManyModelStub extends Illuminate\Database\Eloquent\Model {
- public $foreign_key = 'foreign.value';
-}
diff --git a/tests/Database/DatabaseEloquentHasManyThroughTest.php b/tests/Database/DatabaseEloquentHasManyThroughTest.php
deleted file mode 100644
index 98906fd11..000000000
--- a/tests/Database/DatabaseEloquentHasManyThroughTest.php
+++ /dev/null
@@ -1,104 +0,0 @@
-getRelation();
- $model = m::mock(Model::class);
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(
- function ($array = []) {
- return new Collection($array);
- }
- );
- $model->shouldReceive('setRelation')->once()->with('foo', m::type(Collection::class));
- $models = $relation->initRelation([$model], 'foo');
-
- $this->assertEquals([$model], $models);
- }
-
-
- public function testEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('users.country_id', [1, 2]);
- $model1 = new EloquentHasManyThroughModelStub;
- $model1->id = 1;
- $model2 = new EloquentHasManyThroughModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- public function testModelsAreProperlyMatchedToParents()
- {
- $relation = $this->getRelation();
-
- $result1 = new EloquentHasManyThroughModelStub;
- $result1->country_id = 1;
- $result2 = new EloquentHasManyThroughModelStub;
- $result2->country_id = 2;
- $result3 = new EloquentHasManyThroughModelStub;
- $result3->country_id = 2;
-
- $model1 = new EloquentHasManyThroughModelStub;
- $model1->id = 1;
- $model2 = new EloquentHasManyThroughModelStub;
- $model2->id = 2;
- $model3 = new EloquentHasManyThroughModelStub;
- $model3->id = 3;
-
- $relation->getRelated()->shouldReceive('newCollection')->andReturnUsing(function($array) { return new Collection($array); });
- $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2, $result3]), 'foo');
-
- $this->assertEquals(1, $models[0]->foo[0]->country_id);
- $this->assertCount(1, $models[0]->foo);
- $this->assertEquals(2, $models[1]->foo[0]->country_id);
- $this->assertEquals(2, $models[1]->foo[1]->country_id);
- $this->assertCount(2, $models[1]->foo);
- $this->assertEmpty($models[2]->foo);
- }
-
-
- protected function getRelation()
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('join')->once()->with('users', 'users.id', '=', 'posts.user_id');
- $builder->shouldReceive('where')->with('users.country_id', '=', 1);
-
- $country = m::mock(Model::class);
- $country->shouldReceive('getKey')->andReturn(1);
- $country->shouldReceive('getForeignKey')->andReturn('country_id');
- $user = m::mock(Model::class);
- $user->shouldReceive('getTable')->andReturn('users');
- $user->shouldReceive('getQualifiedKeyName')->andReturn('users.id');
- $post = m::mock(Model::class);
- $post->shouldReceive('getTable')->andReturn('posts');
-
- $builder->shouldReceive('getModel')->andReturn($post);
-
- $user->shouldReceive('getKey')->andReturn(1);
- $user->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
- $user->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- return new HasManyThrough($builder, $country, $user, 'country_id', 'user_id');
- }
-
-}
-
-class EloquentHasManyThroughModelStub extends Illuminate\Database\Eloquent\Model {
- public $country_id = 'foreign.value';
-}
diff --git a/tests/Database/DatabaseEloquentHasOneTest.php b/tests/Database/DatabaseEloquentHasOneTest.php
deleted file mode 100755
index be3792d3b..000000000
--- a/tests/Database/DatabaseEloquentHasOneTest.php
+++ /dev/null
@@ -1,139 +0,0 @@
-getRelation();
- $mockModel = $this->getMock(Model::class, ['save']);
- $mockModel->expects($this->once())->method('save')->willReturn(true);
- $result = $relation->save($mockModel);
-
- $attributes = $result->getAttributes();
- $this->assertEquals(1, $attributes['foreign_key']);
- }
-
-
- public function testCreateMethodProperlyCreatesNewModel()
- {
- $relation = $this->getRelation();
- $created = $this->getMock(Model::class, ['save', 'getKey', 'setAttribute']);
- $created->expects($this->once())->method('save')->willReturn(true);
- $relation->getRelated()->shouldReceive('newInstance')->once()->with(['name' => 'taylor'])->andReturn($created);
- $created->expects($this->once())->method('setAttribute')->with('foreign_key', 1);
-
- $this->assertEquals($created, $relation->create(['name' => 'taylor']));
- }
-
-
- public function testUpdateMethodUpdatesModelsWithTimestamps()
- {
- $relation = $this->getRelation();
- $relation->getRelated()->shouldReceive('usesTimestamps')->once()->andReturn(true);
- $relation->getRelated()->shouldReceive('freshTimestamp')->once()->andReturn($carbon = new Carbon());
- $relation->getRelated()->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- $relation->getQuery()->shouldReceive('update')->once()->with(['foo' => 'bar', 'updated_at' => $carbon])->andReturn('results');
-
- $this->assertEquals('results', $relation->update(['foo' => 'bar']));
- }
-
-
- public function testRelationIsProperlyInitialized()
- {
- $relation = $this->getRelation();
- $model = m::mock(Model::class);
- $model->shouldReceive('setRelation')->once()->with('foo', null);
- $models = $relation->initRelation([$model], 'foo');
-
- $this->assertEquals([$model], $models);
- }
-
-
- public function testEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('table.foreign_key', [1, 2]);
- $model1 = new EloquentHasOneModelStub;
- $model1->id = 1;
- $model2 = new EloquentHasOneModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- public function testModelsAreProperlyMatchedToParents()
- {
- $relation = $this->getRelation();
-
- $result1 = new EloquentHasOneModelStub;
- $result1->foreign_key = 1;
- $result2 = new EloquentHasOneModelStub;
- $result2->foreign_key = 2;
-
- $model1 = new EloquentHasOneModelStub;
- $model1->id = 1;
- $model2 = new EloquentHasOneModelStub;
- $model2->id = 2;
- $model3 = new EloquentHasOneModelStub;
- $model3->id = 3;
-
- $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2]), 'foo');
-
- $this->assertEquals(1, $models[0]->foo->foreign_key);
- $this->assertEquals(2, $models[1]->foo->foreign_key);
- $this->assertNull($models[2]->foo);
- }
-
-
- public function testRelationCountQueryCanBeBuilt()
- {
- $relation = $this->getRelation();
- $query = m::mock(Builder::class);
- $query->shouldReceive('select')->once()->with(m::type(Expression::class));
- $relation->getParent()->shouldReceive('getTable')->andReturn('table');
- $query->shouldReceive('where')->once()->with('table.foreign_key', '=', m::type(
- Expression::class
- ));
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($parentQuery = m::mock('StdClass'));
- $parentQuery->shouldReceive('getGrammar')->once()->andReturn($grammar = m::mock('StdClass'));
- $grammar->shouldReceive('wrap')->once()->with('table.id');
-
- $relation->getRelationCountQuery($query, $query);
- }
-
-
- protected function getRelation()
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('where')->with('table.foreign_key', '=', 1);
- $related = m::mock(Model::class);
- $builder->shouldReceive('getModel')->andReturn($related);
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
- $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
- $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- $parent->shouldReceive('newQueryWithoutScopes')->andReturn($builder);
- return new HasOne($builder, $parent, 'table.foreign_key', 'id');
- }
-
-}
-
-class EloquentHasOneModelStub extends Illuminate\Database\Eloquent\Model {
- public $foreign_key = 'foreign.value';
-}
diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php
deleted file mode 100755
index 11f5e6397..000000000
--- a/tests/Database/DatabaseEloquentModelTest.php
+++ /dev/null
@@ -1,1190 +0,0 @@
-name = 'foo';
- $this->assertEquals('foo', $model->name);
- $this->assertTrue(isset($model->name));
- unset($model->name);
- $this->assertFalse(isset($model->name));
-
- // test mutation
- $model->list_items = ['name' => 'taylor'];
- $this->assertEquals(['name' => 'taylor'], $model->list_items);
- $attributes = $model->getAttributes();
- $this->assertEquals(json_encode(['name' => 'taylor']), $attributes['list_items']);
- }
-
-
- public function testDirtyAttributes(): void
- {
- $model = new EloquentModelStub(['foo' => '1', 'bar' => 2, 'baz' => 3]);
- $model->syncOriginal();
- $model->foo = 1;
- $model->bar = 20;
- $model->baz = 30;
-
- $this->assertTrue($model->isDirty());
- $this->assertFalse($model->isDirty('foo'));
- $this->assertTrue($model->isDirty('bar'));
- $this->assertTrue($model->isDirty('foo', 'bar'));
- $this->assertTrue($model->isDirty(['foo', 'bar']));
- }
-
-
- public function testCalculatedAttributes(): void
- {
- $model = new EloquentModelStub;
- $model->password = 'secret';
- $attributes = $model->getAttributes();
-
- // ensure password attribute was not set to null
- $this->assertFalse(array_key_exists('password', $attributes));
- $this->assertEquals('******', $model->password);
- $this->assertEquals('5ebe2294ecd0e0f08eab7690d2a6ee69', $attributes['password_hash']);
- $this->assertEquals('5ebe2294ecd0e0f08eab7690d2a6ee69', $model->password_hash);
- }
-
-
- public function testNewInstanceReturnsNewInstanceWithAttributesSet(): void
- {
- $model = new EloquentModelStub;
- $instance = $model->newInstance(['name' => 'taylor']);
- $this->assertInstanceOf('EloquentModelStub', $instance);
- $this->assertEquals('taylor', $instance->name);
- }
-
-
- public function testHydrateCreatesCollectionOfModels(): void
- {
- $data = [['name' => 'Taylor'], ['name' => 'Otwell']];
- $collection = EloquentModelStub::hydrate($data);
-
- $this->assertInstanceOf(Collection::class, $collection);
- $this->assertCount(2, $collection);
- $this->assertInstanceOf('EloquentModelStub', $collection[0]);
- $this->assertInstanceOf('EloquentModelStub', $collection[1]);
- $this->assertEquals('Taylor', $collection[0]->name);
- $this->assertEquals('Otwell', $collection[1]->name);
- }
-
-
- public function testHydrateRawMakesRawQuery(): void
- {
- $collection = EloquentModelHydrateRawStub::hydrateRaw('SELECT ?', ['foo']);
- $this->assertEquals('hydrated', $collection[0]);
- }
-
-
- public function testCreateMethodSavesNewModel(): void
- {
- $_SERVER['__eloquent.saved'] = false;
- $model = EloquentModelSaveStub::create(['name' => 'taylor']);
- $this->assertTrue($_SERVER['__eloquent.saved']);
- $this->assertEquals('taylor', $model->name);
- }
-
-
- public function testFindMethodCallsQueryBuilderCorrectly(): void
- {
- $result = EloquentModelFindStub::find(1);
- $this->assertEquals('foo', $result);
- }
-
-
- public function testFindMethodUseWritePdo(): void
- {
- EloquentModelFindWithWritePdoStub::onWriteConnection()->find(1);
- }
-
-
- public function testFindOrFailMethodThrowsModelNotFoundException(): void
- {
- $this->expectException(Illuminate\Database\Eloquent\ModelNotFoundException::class);
- $result = EloquentModelFindNotFoundStub::findOrFail(1);
- }
-
-
- public function testFindMethodWithArrayCallsQueryBuilderCorrectly(): void
- {
- $result = EloquentModelFindManyStub::find([1, 2]);
- $this->assertEquals('foo', $result);
- }
-
-
- public function testDestroyMethodCallsQueryBuilderCorrectly(): void
- {
- $result = EloquentModelDestroyStub::destroy(1, 2, 3);
- }
-
-
- public function testWithMethodCallsQueryBuilderCorrectly(): void
- {
- $result = EloquentModelWithStub::with('foo', 'bar');
- $this->assertEquals('foo', $result);
- }
-
-
- public function testWithMethodCallsQueryBuilderCorrectlyWithArray(): void
- {
- $result = EloquentModelWithStub::with(['foo', 'bar']);
- $this->assertEquals('foo', $result);
- }
-
-
- public function testUpdateProcess(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes', 'updateTimestamps']);
- $query = m::mock(Builder::class);
- $query->shouldReceive('where')->once()->with('id', '=', 1);
- $query->shouldReceive('update')->once()->with(['name' => 'taylor']);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->expects($this->once())->method('updateTimestamps');
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('dispatch')->once()->with('eloquent.updated: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($model), $model)->andReturn(true);
-
- $model->id = 1;
- $model->foo = 'bar';
- // make sure foo isn't synced so we can test that dirty attributes only are updated
- $model->syncOriginal();
- $model->name = 'taylor';
- $model->exists = true;
- $this->assertTrue($model->save());
- }
-
-
- public function testUpdateProcessDoesntOverrideTimestamps(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes']);
- $query = m::mock(Builder::class);
- $query->shouldReceive('where')->once()->with('id', '=', 1);
- $query->shouldReceive('update')->once()->with(['created_at' => 'foo', 'updated_at' => 'bar']);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until');
- $events->shouldReceive('dispatch');
-
- $model->id = 1;
- $model->syncOriginal();
- $model->created_at = 'foo';
- $model->updated_at = 'bar';
- $model->exists = true;
- $this->assertTrue($model->save());
- }
-
-
- public function testSaveIsCancelledIfSavingEventReturnsFalse(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes']);
- $query = m::mock(Builder::class);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(false);
- $model->exists = true;
-
- $this->assertFalse($model->save());
- }
-
-
- public function testUpdateIsCancelledIfUpdatingEventReturnsFalse(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes']);
- $query = m::mock(Builder::class);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($model), $model)->andReturn(false);
- $model->exists = true;
- $model->foo = 'bar';
-
- $this->assertFalse($model->save());
- }
-
-
- public function testUpdateProcessWithoutTimestamps(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes', 'updateTimestamps', 'fireModelEvent']);
- $model->timestamps = false;
- $query = m::mock(Builder::class);
- $query->shouldReceive('where')->once()->with('id', '=', 1);
- $query->shouldReceive('update')->once()->with(['name' => 'taylor']);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->expects($this->never())->method('updateTimestamps');
- $model->expects($this->any())->method('fireModelEvent')->willReturn(true);
-
- $model->id = 1;
- $model->syncOriginal();
- $model->name = 'taylor';
- $model->exists = true;
- $this->assertTrue($model->save());
- }
-
-
- public function testUpdateUsesOldPrimaryKey(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes', 'updateTimestamps']);
- $query = m::mock(Builder::class);
- $query->shouldReceive('where')->once()->with('id', '=', 1);
- $query->shouldReceive('update')->once()->with(['id' => 2, 'foo' => 'bar']);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->expects($this->once())->method('updateTimestamps');
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('until')->once()->with('eloquent.updating: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('dispatch')->once()->with('eloquent.updated: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($model), $model)->andReturn(true);
-
- $model->id = 1;
- $model->syncOriginal();
- $model->id = 2;
- $model->foo = 'bar';
- $model->exists = true;
-
- $this->assertTrue($model->save());
- }
-
-
- public function testTimestampsAreReturnedAsObjects(): void
- {
- $model = $this->getMock('EloquentDateModelStub', ['getDateFormat']);
- $model->expects($this->any())->method('getDateFormat')->willReturn('Y-m-d');
- $model->setRawAttributes([
- 'created_at' => '2012-12-04',
- 'updated_at' => '2012-12-05',
- ]);
-
- $this->assertInstanceOf(Carbon::class, $model->created_at);
- $this->assertInstanceOf(Carbon::class, $model->updated_at);
- }
-
-
- public function testTimestampsAreReturnedAsObjectsFromPlainDatesAndTimestamps(): void
- {
- $model = $this->getMock('EloquentDateModelStub', ['getDateFormat']);
- $model->expects($this->any())->method('getDateFormat')->willReturn('Y-m-d H:i:s');
- $model->setRawAttributes([
- 'created_at' => '2012-12-04',
- 'updated_at' => time(),
- ]);
-
- $this->assertInstanceOf(Carbon::class, $model->created_at);
- $this->assertInstanceOf(Carbon::class, $model->updated_at);
- }
-
-
- public function testTimestampsAreReturnedAsObjectsOnCreate(): void
- {
- $timestamps = [
- 'created_at' => Carbon::now(),
- 'updated_at' => Carbon::now()
- ];
- $model = new EloquentDateModelStub;
- Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver = m::mock(
- ConnectionResolverInterface::class
- ));
- $mockConnection = m::mock(Connection::class);
- $mockConnection->allows()->getQueryGrammar()->andReturns($mockConnection);
- $mockConnection->allows()->getDateFormat()->andReturn('Y-m-d H:i:s');
- $resolver->allows()->connection()->withAnyArgs()->andReturn($mockConnection);
-
- $instance = $model->newInstance($timestamps);
- $this->assertInstanceOf(Carbon::class, $instance->updated_at);
- $this->assertInstanceOf(Carbon::class, $instance->created_at);
- }
-
-
- public function testDateTimeAttributesReturnNullIfSetToNull(): void
- {
- $timestamps = [
- 'created_at' => Carbon::now(),
- 'updated_at' => Carbon::now()
- ];
- $model = new EloquentDateModelStub;
- Illuminate\Database\Eloquent\Model::setConnectionResolver($resolver = m::mock(
- ConnectionResolverInterface::class
- ));
- $resolver->shouldReceive('connection')->andReturn($mockConnection = m::mock(Connection::class));
- $mockConnection->shouldReceive('getQueryGrammar')->andReturn($mockConnection);
- $mockConnection->shouldReceive('getDateFormat')->andReturn('Y-m-d H:i:s');
- $instance = $model->newInstance($timestamps);
-
- $instance->created_at = null;
- $this->assertNull($instance->created_at);
- }
-
-
- public function testTimestampsAreCreatedFromStringsAndIntegers(): void
- {
- $model = new EloquentDateModelStub;
- $model->created_at = '2013-05-22 00:00:00';
- $this->assertInstanceOf(Carbon::class, $model->created_at);
-
- $model = new EloquentDateModelStub;
- $model->created_at = time();
- $this->assertInstanceOf(Carbon::class, $model->created_at);
-
- $model = new EloquentDateModelStub;
- $model->created_at = '2012-01-01';
- $this->assertInstanceOf(Carbon::class, $model->created_at);
- }
-
-
- public function testInsertProcess(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes', 'updateTimestamps']);
- $query = m::mock(Builder::class);
- $query->shouldReceive('insertGetId')->once()->with(['name' => 'taylor'], 'id')->andReturn(1);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->expects($this->once())->method('updateTimestamps');
-
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('dispatch')->once()->with('eloquent.created: '.get_class($model), $model);
- $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($model), $model);
-
- $model->name = 'taylor';
- $model->exists = false;
- $this->assertTrue($model->save());
- $this->assertEquals(1, $model->id);
- $this->assertTrue($model->exists);
-
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes', 'updateTimestamps']);
- $query = m::mock(Builder::class);
- $query->shouldReceive('insert')->once()->with(['name' => 'taylor']);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->expects($this->once())->method('updateTimestamps');
- $model->setIncrementing(false);
-
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('dispatch')->once()->with('eloquent.created: '.get_class($model), $model);
- $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($model), $model);
-
- $model->name = 'taylor';
- $model->exists = false;
- $this->assertTrue($model->save());
- $this->assertNull($model->id);
- $this->assertTrue($model->exists);
- }
-
-
- public function testInsertIsCancelledIfCreatingEventReturnsFalse(): void
- {
- $model = $this->getMock('EloquentModelStub', ['newQueryWithoutScopes']);
- $query = m::mock(Builder::class);
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($model), $model)->andReturn(true);
- $events->shouldReceive('until')->once()->with('eloquent.creating: '.get_class($model), $model)->andReturn(false);
-
- $this->assertFalse($model->save());
- $this->assertFalse($model->exists);
- }
-
-
- public function testDeleteProperlyDeletesModel(): void
- {
- $model = $this->getMock(Model::class, ['newQueryWithoutScopes', 'updateTimestamps', 'touchOwners']);
- $query = m::mock(Builder::class);
- $query->shouldReceive('where')->once()->with('id', 1)->andReturn($query);
- $query->shouldReceive('delete')->once();
- $model->expects($this->once())->method('newQueryWithoutScopes')->willReturn($query);
- $model->expects($this->once())->method('touchOwners');
- $model->exists = true;
- $model->id = 1;
- $model->delete();
- }
-
-
- public function testNewQueryReturnsEloquentQueryBuilder(): void
- {
- $conn = m::mock(Connection::class);
- $grammar = m::mock(Grammar::class);
- $processor = m::mock(Processor::class);
- $conn->shouldReceive('getQueryGrammar')->once()->andReturn($grammar);
- $conn->shouldReceive('getPostProcessor')->once()->andReturn($processor);
- EloquentModelStub::setConnectionResolver($resolver = m::mock(
- ConnectionResolverInterface::class
- ));
- $resolver->shouldReceive('connection')->andReturn($conn);
- $model = new EloquentModelStub;
- $builder = $model->newQuery();
- $this->assertInstanceOf(Builder::class, $builder);
- }
-
-
- public function testGetAndSetTableOperations(): void
- {
- $model = new EloquentModelStub;
- $this->assertEquals('stub', $model->getTable());
- $model->setTable('foo');
- $this->assertEquals('foo', $model->getTable());
- }
-
-
- public function testGetKeyReturnsValueOfPrimaryKey(): void
- {
- $model = new EloquentModelStub;
- $model->id = 1;
- $this->assertEquals(1, $model->getKey());
- $this->assertEquals('id', $model->getKeyName());
- }
-
-
- public function testConnectionManagement(): void
- {
- EloquentModelStub::setConnectionResolver($resolver = m::mock(
- ConnectionResolverInterface::class
- ));
- $model = new EloquentModelStub;
- $model->setConnection('foo');
- $resolver->shouldReceive('connection')->once()->with('foo')->andReturn($connection = m::mock(Connection::class));
-
- $this->assertEquals($connection, $model->getConnection());
- }
-
-
- public function testToArray(): void
- {
- $model = new EloquentModelStub;
- $model->name = 'foo';
- $model->age = null;
- $model->password = 'password1';
- $model->setHidden(['password']);
- $model->setRelation('names', new Illuminate\Database\Eloquent\Collection([
- new EloquentModelStub(['bar' => 'baz']), new EloquentModelStub(['bam' => 'boom'])
- ]));
- $model->setRelation('partner', new EloquentModelStub(['name' => 'abby']));
- $model->setRelation('group', null);
- $model->setRelation('multi', new Illuminate\Database\Eloquent\Collection);
- $array = $model->toArray();
-
- $this->assertIsArray($array);
- $this->assertEquals('foo', $array['name']);
- $this->assertEquals('baz', $array['names'][0]['bar']);
- $this->assertEquals('boom', $array['names'][1]['bam']);
- $this->assertEquals('abby', $array['partner']['name']);
- $this->assertNull($array['group']);
- $this->assertEquals([], $array['multi']);
- $this->assertFalse(isset($array['password']));
-
- $model->setAppends(['appendable']);
- $array = $model->toArray();
- $this->assertEquals('appended', $array['appendable']);
- }
-
-
- public function testToArrayIncludesDefaultFormattedTimestamps(): void
- {
- $model = new EloquentDateModelStub;
- $model->setRawAttributes([
- 'created_at' => '2012-12-04',
- 'updated_at' => '2012-12-05',
- ]);
-
- $array = $model->toArray();
-
- $this->assertEquals('2012-12-04 00:00:00', $array['created_at']);
- $this->assertEquals('2012-12-05 00:00:00', $array['updated_at']);
- }
-
-
- public function testToArrayIncludesCustomFormattedTimestamps(): void
- {
- $model = new EloquentDateModelStub;
- $model->setRawAttributes([
- 'created_at' => '2012-12-04',
- 'updated_at' => '2012-12-05',
- ]);
-
- $array = $model->toArray();
-
- $this->assertEquals('2012-12-04 00:00:00', $array['created_at']);
- $this->assertEquals('2012-12-05 00:00:00', $array['updated_at']);
- }
-
-
- public function testVisibleCreatesArrayWhitelist(): void
- {
- $model = new EloquentModelStub;
- $model->setVisible(['name']);
- $model->name = 'Taylor';
- $model->age = 26;
- $array = $model->toArray();
-
- $this->assertEquals(['name' => 'Taylor'], $array);
- }
-
-
- public function testHiddenCanAlsoExcludeRelationships(): void
- {
- $model = new EloquentModelStub;
- $model->name = 'Taylor';
- $model->setRelation('foo', ['bar']);
- $model->setHidden(['foo', 'list_items', 'password']);
- $array = $model->toArray();
-
- $this->assertEquals(['name' => 'Taylor'], $array);
- }
-
-
- public function testToArraySnakeAttributes(): void
- {
- $model = new EloquentModelStub;
- $model->setRelation('namesList', new Illuminate\Database\Eloquent\Collection([
- new EloquentModelStub(['bar' => 'baz']), new EloquentModelStub(['bam' => 'boom'])
- ]));
- $array = $model->toArray();
-
- $this->assertEquals('baz', $array['names_list'][0]['bar']);
- $this->assertEquals('boom', $array['names_list'][1]['bam']);
-
- $model = new EloquentModelCamelStub;
- $model->setRelation('namesList', new Illuminate\Database\Eloquent\Collection([
- new EloquentModelStub(['bar' => 'baz']), new EloquentModelStub(['bam' => 'boom'])
- ]));
- $array = $model->toArray();
-
- $this->assertEquals('baz', $array['namesList'][0]['bar']);
- $this->assertEquals('boom', $array['namesList'][1]['bam']);
- }
-
-
- public function testToArrayUsesMutators(): void
- {
- $model = new EloquentModelStub;
- $model->list_items = [1, 2, 3];
- $array = $model->toArray();
-
- $this->assertEquals([1, 2, 3], $array['list_items']);
- }
-
-
- public function testFillable(): void
- {
- $model = new EloquentModelStub;
- $model->fillable(['name', 'age']);
- $model->fill(['name' => 'foo', 'age' => 'bar']);
- $this->assertEquals('foo', $model->name);
- $this->assertEquals('bar', $model->age);
- }
-
-
- public function testUnguardAllowsAnythingToBeSet(): void
- {
- $model = new EloquentModelStub;
- EloquentModelStub::unguard();
- $model->guard(['*']);
- $model->fill(['name' => 'foo', 'age' => 'bar']);
- $this->assertEquals('foo', $model->name);
- $this->assertEquals('bar', $model->age);
- EloquentModelStub::setUnguardState(false);
- }
-
-
- public function testUnderscorePropertiesAreNotFilled(): void
- {
- $model = new EloquentModelStub;
- $model->fill(['_method' => 'PUT']);
- $this->assertEquals([], $model->getAttributes());
- }
-
-
- public function testGuarded(): void
- {
- $model = new EloquentModelStub;
- $model->guard(['name', 'age']);
- $model->fill(['name' => 'foo', 'age' => 'bar', 'foo' => 'bar']);
- $this->assertFalse(isset($model->name));
- $this->assertFalse(isset($model->age));
- $this->assertEquals('bar', $model->foo);
- }
-
-
- public function testFillableOverridesGuarded(): void
- {
- $model = new EloquentModelStub;
- $model->guard(['name', 'age']);
- $model->fillable(['age', 'foo']);
- $model->fill(['name' => 'foo', 'age' => 'bar', 'foo' => 'bar']);
- $this->assertFalse(isset($model->name));
- $this->assertEquals('bar', $model->age);
- $this->assertEquals('bar', $model->foo);
- }
-
-
- public function testGlobalGuarded(): void
- {
- $this->expectException(Illuminate\Database\Eloquent\MassAssignmentException::class);
- $model = new EloquentModelStub;
- $model->guard(['*']);
- $model->fill(['name' => 'foo', 'age' => 'bar', 'votes' => 'baz']);
- }
-
-
- public function testHasOneCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->hasOne('EloquentModelSaveStub');
- $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getForeignKey());
-
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->hasOne('EloquentModelSaveStub', 'foo');
- $this->assertEquals('save_stub.foo', $relation->getForeignKey());
- $this->assertSame($model, $relation->getParent());
- $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
- }
-
-
- public function testMorphOneCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->morphOne('EloquentModelSaveStub', 'morph');
- $this->assertEquals('save_stub.morph_id', $relation->getForeignKey());
- $this->assertEquals('save_stub.morph_type', $relation->getMorphType());
- $this->assertEquals('EloquentModelStub', $relation->getMorphClass());
- }
-
-
- public function testHasManyCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->hasMany('EloquentModelSaveStub');
- $this->assertEquals('save_stub.eloquent_model_stub_id', $relation->getForeignKey());
-
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->hasMany('EloquentModelSaveStub', 'foo');
- $this->assertEquals('save_stub.foo', $relation->getForeignKey());
- $this->assertSame($model, $relation->getParent());
- $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
- }
-
-
- public function testMorphManyCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->morphMany('EloquentModelSaveStub', 'morph');
- $this->assertEquals('save_stub.morph_id', $relation->getForeignKey());
- $this->assertEquals('save_stub.morph_type', $relation->getMorphType());
- $this->assertEquals('EloquentModelStub', $relation->getMorphClass());
- }
-
-
- public function testBelongsToCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->belongsToStub();
- $this->assertEquals('belongs_to_stub_id', $relation->getForeignKey());
- $this->assertSame($model, $relation->getParent());
- $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
-
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->belongsToExplicitKeyStub();
- $this->assertEquals('foo', $relation->getForeignKey());
- }
-
-
- public function testMorphToCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->morphToStub();
- $this->assertEquals('morph_to_stub_id', $relation->getForeignKey());
- $this->assertSame($model, $relation->getParent());
- $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
- }
-
-
- public function testBelongsToManyCreatesProperRelation(): void
- {
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->belongsToMany('EloquentModelSaveStub');
- $this->assertEquals('eloquent_model_save_stub_eloquent_model_stub.eloquent_model_stub_id', $relation->getForeignKey());
- $this->assertEquals('eloquent_model_save_stub_eloquent_model_stub.eloquent_model_save_stub_id', $relation->getOtherKey());
- $this->assertSame($model, $relation->getParent());
- $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
- $this->assertEquals(__FUNCTION__, $relation->getRelationName());
-
- $model = new EloquentModelStub;
- $this->addMockConnection($model);
- $relation = $model->belongsToMany('EloquentModelSaveStub', 'table', 'foreign', 'other');
- $this->assertEquals('table.foreign', $relation->getForeignKey());
- $this->assertEquals('table.other', $relation->getOtherKey());
- $this->assertSame($model, $relation->getParent());
- $this->assertInstanceOf('EloquentModelSaveStub', $relation->getQuery()->getModel());
- }
-
-
- public function testModelsAssumeTheirName(): void
- {
- $model = new EloquentModelWithoutTableStub;
- $this->assertEquals('eloquent_model_without_table_stubs', $model->getTable());
-
- require_once __DIR__.'/stubs/EloquentModelNamespacedStub.php';
- $namespacedModel = new Foo\Bar\EloquentModelNamespacedStub;
- $this->assertEquals('eloquent_model_namespaced_stubs', $namespacedModel->getTable());
- }
-
-
- public function testTheMutatorCacheIsPopulated(): void
- {
- $class = new EloquentModelStub;
-
- $expectedAttributes = [
- 'list_items',
- 'password',
- 'appendable'
- ];
-
- $this->assertEquals($expectedAttributes, $class->getMutatedAttributes());
- }
-
-
- public function testCloneModelMakesAFreshCopyOfTheModel(): void
- {
- $class = new EloquentModelStub;
- $class->id = 1;
- $class->exists = true;
- $class->first = 'taylor';
- $class->last = 'otwell';
- $class->created_at = $class->freshTimestamp();
- $class->updated_at = $class->freshTimestamp();
- $class->setRelation('foo', ['bar']);
-
- $clone = $class->replicate();
-
- $this->assertNull($clone->id);
- $this->assertFalse($clone->exists);
- $this->assertEquals('taylor', $clone->first);
- $this->assertEquals('otwell', $clone->last);
- $this->assertObjectNotHasProperty('created_at', $clone);
- $this->assertObjectNotHasProperty('updated_at', $clone);
- $this->assertEquals(['bar'], $clone->foo);
- }
-
-
- public function testModelObserversCanBeAttachedToModels(): void
- {
- EloquentModelStub::setEventDispatcher($events = m::mock(Dispatcher::class));
- $events->shouldReceive('listen')->once()->with('eloquent.creating: EloquentModelStub', 'EloquentTestObserverStub@creating');
- $events->shouldReceive('listen')->once()->with('eloquent.saved: EloquentModelStub', 'EloquentTestObserverStub@saved');
- $events->shouldReceive('forget');
- EloquentModelStub::observe(new EloquentTestObserverStub);
- EloquentModelStub::flushEventListeners();
- }
-
-
- public function testSetObservableEvents(): void
- {
- $class = new EloquentModelStub;
- $class->setObservableEvents(['foo']);
-
- $this->assertContains('foo', $class->getObservableEvents());
- }
-
-
- public function testAddObservableEvent(): void
- {
- $class = new EloquentModelStub;
- $class->addObservableEvents('foo');
-
- $this->assertContains('foo', $class->getObservableEvents());
- }
-
- public function testAddMultipleObserveableEvents(): void
- {
- $class = new EloquentModelStub;
- $class->addObservableEvents('foo', 'bar');
-
- $this->assertContains('foo', $class->getObservableEvents());
- $this->assertContains('bar', $class->getObservableEvents());
- }
-
-
- public function testRemoveObservableEvent(): void
- {
- $class = new EloquentModelStub;
- $class->setObservableEvents(['foo', 'bar']);
- $class->removeObservableEvents('bar');
-
- $this->assertNotContains('bar', $class->getObservableEvents());
- }
-
- public function testRemoveMultipleObservableEvents(): void
- {
- $class = new EloquentModelStub;
- $class->setObservableEvents(['foo', 'bar']);
- $class->removeObservableEvents('foo', 'bar');
-
- $this->assertNotContains('foo', $class->getObservableEvents());
- $this->assertNotContains('bar', $class->getObservableEvents());
- }
-
-
- public function testGetModelAttributeMethodThrowsExceptionIfNotRelation(): void
- {
- $this->expectException(LogicException::class);
- $model = new EloquentModelStub;
- $relation = $model->incorrect_relation_stub;
- }
-
-
- public function testModelIsBootedOnUnserialize(): void
- {
- $model = new EloquentModelBootingTestStub;
- $this->assertTrue(EloquentModelBootingTestStub::isBooted());
- $model->foo = 'bar';
- $string = serialize($model);
- $model = null;
- EloquentModelBootingTestStub::unboot();
- $this->assertFalse(EloquentModelBootingTestStub::isBooted());
- $model = unserialize($string);
- $this->assertTrue(EloquentModelBootingTestStub::isBooted());
- }
-
-
- public function testAppendingOfAttributes(): void
- {
- $model = new EloquentModelAppendsStub;
-
- $this->assertTrue(isset($model->is_admin));
- $this->assertTrue(isset($model->camelCased));
- $this->assertTrue(isset($model->StudlyCased));
-
- $this->assertEquals('admin', $model->is_admin);
- $this->assertEquals('camelCased', $model->camelCased);
- $this->assertEquals('StudlyCased', $model->StudlyCased);
-
- $model->setHidden(['is_admin', 'camelCased', 'StudlyCased']);
- $this->assertEquals([], $model->toArray());
-
- $model->setVisible([]);
- $this->assertEquals([], $model->toArray());
- }
-
-
- public function testReplicateCreatesANewModelInstanceWithSameAttributeValues(): void
- {
- $model = new EloquentModelStub;
- $model->id = 'id';
- $model->foo = 'bar';
- $model->created_at = new DateTime;
- $model->updated_at = new DateTime;
- $replicated = $model->replicate();
-
- $this->assertNull($replicated->id);
- $this->assertEquals('bar', $replicated->foo);
- $this->assertNull($replicated->created_at);
- $this->assertNull($replicated->updated_at);
- }
-
-
- public function testIncrementOnExistingModelCallsQueryAndSetsAttribute(): void
- {
- $model = m::mock('EloquentModelStub[newQuery]');
- $model->exists = true;
- $model->id = 1;
- $model->syncOriginalAttribute('id');
- $model->foo = 2;
-
- $model->allows()->newQuery()->andReturn($query = m::mock(Builder::class));
- $query->allows()->where()->withAnyArgs()->andReturn($query);
- $query->allows()->increment()->withAnyArgs()->andReturn(1);
-
- $model->publicIncrement('foo');
-
- $this->assertEquals(3, $model->foo);
- $this->assertFalse($model->isDirty());
- }
-
- public function testRelationshipTouchOwnersIsPropagated(): void
- {
- $relation = $this->getMockBuilder(BelongsTo::class)->onlyMethods(['touch'])->disableOriginalConstructor()->getMock();
- $relation->expects($this->once())->method('touch');
-
- $model = m::mock('EloquentModelStub[partner]');
- $this->addMockConnection($model);
- $model->shouldReceive('partner')->once()->andReturn($relation);
- $model->setTouchedRelations(['partner']);
-
- $mockPartnerModel = m::mock('EloquentModelStub[touchOwners]');
- $mockPartnerModel->shouldReceive('touchOwners')->once();
- $model->setRelation('partner', $mockPartnerModel);
-
- $model->touchOwners();
- }
-
-
- public function testRelationshipTouchOwnersIsNotPropagatedIfNoRelationshipResult(): void
- {
- $relation = $this->getMockBuilder(BelongsTo::class)->onlyMethods(['touch'])->disableOriginalConstructor()->getMock();
- $relation->expects($this->once())->method('touch');
-
- $model = m::mock('EloquentModelStub[partner]');
- $this->addMockConnection($model);
- $model->shouldReceive('partner')->once()->andReturn($relation);
- $model->setTouchedRelations(['partner']);
-
- $model->setRelation('partner', null);
-
- $model->touchOwners();
- }
-
-
- public function testTimestampsAreNotUpdatedWithTimestampsFalseSaveOption(): void
- {
- $model = m::mock('EloquentModelStub[newQueryWithoutScopes]');
- $query = m::mock(Builder::class);
- $query->shouldReceive('where')->once()->with('id', '=', 1);
- $query->shouldReceive('update')->once()->with(['name' => 'taylor']);
- $model->shouldReceive('newQueryWithoutScopes')->once()->andReturn($query);
-
- $model->id = 1;
- $model->syncOriginal();
- $model->name = 'taylor';
- $model->exists = true;
- $this->assertTrue($model->save(['timestamps' => false]));
- $this->assertNull($model->updated_at);
- }
-
-
- protected function addMockConnection($model): void
- {
- $model->setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class));
- $resolver->shouldReceive('connection')->andReturn(m::mock(Connection::class));
- $model->getConnection()->shouldReceive('getQueryGrammar')->andReturn(m::mock(
- Grammar::class
- ));
- $model->getConnection()->shouldReceive('getPostProcessor')->andReturn(m::mock(
- Processor::class
- ));
- }
-
-}
-
-class EloquentTestObserverStub {
- public function creating(): void
- {}
- public function saved(): void
- {}
-}
-
-class EloquentModelStub extends Illuminate\Database\Eloquent\Model {
- protected string $table = 'stub';
- protected array $guarded = [];
- protected string $morph_to_stub_type = 'EloquentModelSaveStub';
- public function getListItemsAttribute($value)
- {
- return json_decode((string) $value, true);
- }
- public function setListItemsAttribute($value): void
- {
- $this->attributes['list_items'] = json_encode($value);
- }
- public function getPasswordAttribute(): string
- {
- return '******';
- }
- public function setPasswordAttribute($value): void
- {
- $this->attributes['password_hash'] = md5((string) $value);
- }
- public function publicIncrement($column, $amount = 1): int
- {
- return $this->increment($column, $amount);
- }
- public function belongsToStub(): BelongsTo
- {
- return $this->belongsTo('EloquentModelSaveStub');
- }
- public function morphToStub(): \Illuminate\Database\Eloquent\Relations\MorphTo
- {
- return $this->morphTo();
- }
- public function belongsToExplicitKeyStub(): BelongsTo
- {
- return $this->belongsTo('EloquentModelSaveStub', 'foo');
- }
- public function incorrectRelationStub(): string
- {
- return 'foo';
- }
- #[\Override]
- public function getDates(): array
- {
- return [];
- }
- public function getAppendableAttribute(): string
- {
- return 'appended';
- }
-}
-
-class EloquentModelCamelStub extends EloquentModelStub {
- public static bool $snakeAttributes = false;
-}
-
-class EloquentDateModelStub extends EloquentModelStub {
- #[\Override]
- public function getDates(): array
- {
- return ['created_at', 'updated_at'];
- }
-}
-
-class EloquentModelSaveStub extends Illuminate\Database\Eloquent\Model {
- protected string $table = 'save_stub';
- protected array $guarded = [];
- #[\Override]
- public function save(array $options = []): bool { $_SERVER['__eloquent.saved'] = true; return true; }
- #[\Override]
- public function setIncrementing($value): void
- {
- $this->incrementing = $value;
- }
-}
-
-class EloquentModelFindStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public function newQuery()
- {
- $mock = m::mock(Builder::class);
- $mock->shouldReceive('find')->once()->with(1, ['*'])->andReturn('foo');
- return $mock;
- }
-}
-
-class EloquentModelFindWithWritePdoStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public function newQuery()
- {
- $mock = m::mock(Builder::class);
- $mock->expects('useWritePdo')->andReturnSelf();
- $mock->expects('find')->with(1)->andReturns('foo');
-
- return $mock;
- }
-}
-
-class EloquentModelFindNotFoundStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public function newQuery()
- {
- $mock = m::mock(Builder::class);
- $mock->shouldReceive('find')->once()->with(1, ['*'])->andReturn(null);
- return $mock;
- }
-}
-
-class EloquentModelDestroyStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public function newQuery()
- {
- $mock = m::mock(Builder::class);
- $mock->shouldReceive('whereIn')->once()->with('id', [1, 2, 3])->andReturn($mock);
- $mock->shouldReceive('get')->once()->andReturn([$model = m::mock('StdClass')]);
- $model->shouldReceive('delete')->once();
- return $mock;
- }
-}
-
-class EloquentModelHydrateRawStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public static function hydrate(array $items, $connection = null): Collection { return new Collection(['hydrated']); }
- #[\Override]
- public function getConnection(): Connection
- {
- $mock = m::mock(Connection::class);
- $mock->shouldReceive('select')->once()->with('SELECT ?', ['foo'])->andReturn([]);
- return $mock;
- }
-}
-
-class EloquentModelFindManyStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public function newQuery()
- {
- $mock = m::mock(Builder::class);
- $mock->shouldReceive('find')->once()->with([1, 2], ['*'])->andReturn('foo');
- return $mock;
- }
-}
-
-class EloquentModelWithStub extends Illuminate\Database\Eloquent\Model {
- #[\Override]
- public function newQuery()
- {
- $mock = m::mock(Builder::class);
- $mock->shouldReceive('with')->once()->with(['foo', 'bar'])->andReturn('foo');
- return $mock;
- }
-}
-
-class EloquentModelWithoutTableStub extends Illuminate\Database\Eloquent\Model {}
-
-class EloquentModelBootingTestStub extends Illuminate\Database\Eloquent\Model {
- public static function unboot(): void
- {
- unset(static::$booted[static::class]);
- }
- public static function isBooted(): bool
- {
- return array_key_exists(static::class, static::$booted);
- }
-}
-
-class EloquentModelAppendsStub extends Illuminate\Database\Eloquent\Model {
- protected array $appends = ['is_admin', 'camelCased', 'StudlyCased'];
- public function getIsAdminAttribute(): string
- {
- return 'admin';
- }
- public function getCamelCasedAttribute(): string
- {
- return 'camelCased';
- }
- public function getStudlyCasedAttribute(): string
- {
- return 'StudlyCased';
- }
-}
diff --git a/tests/Database/DatabaseEloquentMorphTest.php b/tests/Database/DatabaseEloquentMorphTest.php
deleted file mode 100755
index a34492bd2..000000000
--- a/tests/Database/DatabaseEloquentMorphTest.php
+++ /dev/null
@@ -1,120 +0,0 @@
-getOneRelation();
- }
-
-
- public function testMorphOneEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getOneRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('table.morph_id', [1, 2]);
- $relation->getQuery()->shouldReceive('where')->once()->with('table.morph_type', get_class($relation->getParent()));
-
- $model1 = new EloquentMorphResetModelStub;
- $model1->id = 1;
- $model2 = new EloquentMorphResetModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- /**
- * Note that the tests are the exact same for morph many because the classes share this code...
- * Will still test to be safe.
- */
- public function testMorphManySetsProperConstraints()
- {
- $relation = $this->getManyRelation();
- }
-
-
- public function testMorphManyEagerConstraintsAreProperlyAdded()
- {
- $relation = $this->getManyRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('table.morph_id', [1, 2]);
- $relation->getQuery()->shouldReceive('where')->once()->with('table.morph_type', get_class($relation->getParent()));
-
- $model1 = new EloquentMorphResetModelStub;
- $model1->id = 1;
- $model2 = new EloquentMorphResetModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- public function testCreateFunctionOnMorph()
- {
- // Doesn't matter which relation type we use since they share the code...
- $relation = $this->getOneRelation();
- $created = m::mock(Model::class);
- $created->shouldReceive('setAttribute')->once()->with('morph_id', 1);
- $created->shouldReceive('setAttribute')->once()->with('morph_type', get_class($relation->getParent()));
- $relation->getRelated()->shouldReceive('newInstance')->once()->with(['name' => 'taylor'])->andReturn($created);
- $created->shouldReceive('save')->once()->andReturn(true);
-
- $this->assertEquals($created, $relation->create(['name' => 'taylor']));
- }
-
-
- protected function getOneRelation()
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);
- $related = m::mock(Model::class);
- $builder->shouldReceive('getModel')->andReturn($related);
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
- $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));
- $builder->shouldReceive('where')->once()->with('table.morph_type', get_class($parent));
- return new MorphOne($builder, $parent, 'table.morph_type', 'table.morph_id', 'id');
- }
-
-
- protected function getManyRelation()
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('where')->once()->with('table.morph_id', '=', 1);
- $related = m::mock(Model::class);
- $builder->shouldReceive('getModel')->andReturn($related);
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
- $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));
- $builder->shouldReceive('where')->once()->with('table.morph_type', get_class($parent));
- return new MorphMany($builder, $parent, 'table.morph_type', 'table.morph_id', 'id');
- }
-
-}
-
-
-class EloquentMorphResetModelStub extends Illuminate\Database\Eloquent\Model {}
-
-
-class EloquentMorphResetBuilderStub extends Illuminate\Database\Eloquent\Builder {
- public function __construct() { $this->query = new EloquentRelationQueryStub; }
- #[\Override]
- public function getModel() { return new EloquentMorphResetModelStub; }
- public function isSoftDeleting() { return false; }
-}
-
-
-class EloquentMorphQueryStub extends Illuminate\Database\Query\Builder {
- public function __construct() {}
-}
diff --git a/tests/Database/DatabaseEloquentMorphToManyTest.php b/tests/Database/DatabaseEloquentMorphToManyTest.php
deleted file mode 100644
index 0f925721c..000000000
--- a/tests/Database/DatabaseEloquentMorphToManyTest.php
+++ /dev/null
@@ -1,120 +0,0 @@
-getRelation();
- $relation->getQuery()->shouldReceive('whereIn')->once()->with('taggables.taggable_id', [1, 2]);
- $relation->getQuery()->shouldReceive('where')->once()->with(
- 'taggables.taggable_type',
- get_class($relation->getParent())
- );
- $model1 = new EloquentMorphToManyModelStub;
- $model1->id = 1;
- $model2 = new EloquentMorphToManyModelStub;
- $model2->id = 2;
- $relation->addEagerConstraints([$model1, $model2]);
- }
-
-
- public function testAttachInsertsPivotTableRecord(): void
- {
- $relation = $this->getMock(MorphToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('taggables')->andReturn($query);
- $query->shouldReceive('insert')->once()->with(
- [['taggable_id' => 1, 'taggable_type' => get_class($relation->getParent()), 'tag_id' => 2, 'foo' => 'bar']]
- )->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $relation->attach(2, ['foo' => 'bar']);
- }
-
-
- public function testDetachRemovesPivotTableRecord(): void
- {
- $relation = $this->getMock(MorphToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('taggables')->andReturn($query);
- $query->shouldReceive('where')->once()->with('taggable_id', 1)->andReturn($query);
- $query->shouldReceive('where')->once()->with('taggable_type', get_class($relation->getParent()))->andReturn($query);
- $query->shouldReceive('whereIn')->once()->with('tag_id', [1, 2, 3]);
- $query->shouldReceive('delete')->once()->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertTrue($relation->detach([1, 2, 3]));
- }
-
-
- public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven(): void
- {
- $relation = $this->getMock(MorphToMany::class, ['touchIfTouching'], $this->getRelationArguments());
- $query = m::mock('stdClass');
- $query->shouldReceive('from')->once()->with('taggables')->andReturn($query);
- $query->shouldReceive('where')->once()->with('taggable_id', 1)->andReturn($query);
- $query->shouldReceive('where')->once()->with('taggable_type', get_class($relation->getParent()))->andReturn($query);
- $query->shouldReceive('whereIn')->never();
- $query->shouldReceive('delete')->once()->andReturn(true);
- $relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
- $mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
- $relation->expects($this->once())->method('touchIfTouching');
-
- $this->assertTrue($relation->detach());
- }
-
-
- public function getRelation(): MorphToMany
- {
- [$builder, $parent] = $this->getRelationArguments();
-
- return new MorphToMany($builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id');
- }
-
-
- public function getRelationArguments():array
- {
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));
- $parent->shouldReceive('getKey')->andReturn(1);
- $parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
- $parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- $parent->shouldReceive('getMorphClass')->andReturn(get_class($parent));
-
- $builder = m::mock(Builder::class);
- $related = m::mock(Model::class);
- $builder->shouldReceive('getModel')->andReturn($related);
-
- $related->shouldReceive('getTable')->andReturn('tags');
- $related->shouldReceive('getKeyName')->andReturn('id');
- $related->shouldReceive('getMorphClass')->andReturn(get_class($related));
-
- $builder->shouldReceive('join')->once()->with('taggables', 'tags.id', '=', 'taggables.tag_id');
- $builder->shouldReceive('where')->once()->with('taggables.taggable_id', '=', 1);
- $builder->shouldReceive('where')->once()->with('taggables.taggable_type', get_class($parent));
-
- return [$builder, $parent, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'relation_name', false];
- }
-
-}
-
-class EloquentMorphToManyModelStub extends Illuminate\Database\Eloquent\Model {
- protected array $guarded = [];
-}
diff --git a/tests/Database/DatabaseEloquentMorphToTest.php b/tests/Database/DatabaseEloquentMorphToTest.php
deleted file mode 100644
index 07538756e..000000000
--- a/tests/Database/DatabaseEloquentMorphToTest.php
+++ /dev/null
@@ -1,155 +0,0 @@
-getRelation();
- $relation->addEagerConstraints(
- [
- $one = (object)['morph_type' => 'morph_type_1', 'foreign_key' => 'foreign_key_1'],
- $two = (object) ['morph_type' => 'morph_type_1', 'foreign_key' => 'foreign_key_1'],
- $three = (object) ['morph_type' => 'morph_type_2', 'foreign_key' => 'foreign_key_2'],
- ]
- );
-
- $dictionary = $relation->getDictionary();
-
- $this->assertEquals([
- 'morph_type_1' => [
- 'foreign_key_1' => [
- $one,
- $two
- ]
- ],
- 'morph_type_2' => [
- 'foreign_key_2' => [
- $three
- ]
- ],
- ], $dictionary);
- }
-
-
- public function testModelsAreProperlyPulledAndMatched()
- {
- $relation = $this->getRelation();
-
- $one = m::mock('StdClass');
- $one->morph_type = 'morph_type_1';
- $one->foreign_key = 'foreign_key_1';
-
- $two = m::mock('StdClass');
- $two->morph_type = 'morph_type_1';
- $two->foreign_key = 'foreign_key_1';
-
- $three = m::mock('StdClass');
- $three->morph_type = 'morph_type_2';
- $three->foreign_key = 'foreign_key_2';
-
- $relation->addEagerConstraints([$one, $two, $three]);
-
- $relation->shouldReceive('createModelByType')->once()->with('morph_type_1')->andReturn($firstQuery = m::mock(
- Builder::class
- ));
- $relation->shouldReceive('createModelByType')->once()->with('morph_type_2')->andReturn($secondQuery = m::mock(
- Builder::class
- ));
- $firstQuery->shouldReceive('getKeyName')->andReturn('id');
- $secondQuery->shouldReceive('getKeyName')->andReturn('id');
-
- $firstQuery->shouldReceive('newQuery')->once()->andReturn($firstQuery);
- $secondQuery->shouldReceive('newQuery')->once()->andReturn($secondQuery);
-
- $firstQuery->shouldReceive('whereIn')->once()->with('id', ['foreign_key_1'])->andReturn($firstQuery);
- $firstQuery->shouldReceive('get')->once()->andReturn(Collection::make([$resultOne = m::mock('StdClass')]));
- $resultOne->shouldReceive('getKey')->andReturn('foreign_key_1');
-
- $secondQuery->shouldReceive('whereIn')->once()->with('id', ['foreign_key_2'])->andReturn($secondQuery);
- $secondQuery->shouldReceive('get')->once()->andReturn(Collection::make([$resultTwo = m::mock('StdClass')]));
- $resultTwo->shouldReceive('getKey')->andReturn('foreign_key_2');
-
- $one->shouldReceive('setRelation')->once()->with('relation', $resultOne);
- $two->shouldReceive('setRelation')->once()->with('relation', $resultOne);
- $three->shouldReceive('setRelation')->once()->with('relation', $resultTwo);
-
- $relation->getEager();
- }
-
- public function testModelsWithSoftDeleteAreProperlyPulled()
- {
- $builder = m::mock(Builder::class);
-
- $relation = $this->getRelation(null, $builder);
-
- $builder->shouldReceive('getMacro')->once()->with('withTrashed')->andReturn(function() { return true; });
- $builder->shouldReceive('withTrashed')->once();
-
- $relation->withTrashed();
- }
-
- public function testAssociateMethodSetsForeignKeyAndTypeOnModel()
- {
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->once()->with('foreign_key')->andReturn('foreign.value');
-
- $relation = $this->getRelationAssociate($parent);
-
- $associate = m::mock(Model::class);
- $associate->shouldReceive('getKey')->once()->andReturn(1);
- $associate->shouldReceive('getMorphClass')->once()->andReturn('Model');
-
- $parent->shouldReceive('setAttribute')->once()->with('foreign_key', 1);
- $parent->shouldReceive('setAttribute')->once()->with('morph_type', 'Model');
- $parent->shouldReceive('setRelation')->once()->with('relation', $associate);
-
- $relation->associate($associate);
- }
-
-
- protected function getRelationAssociate($parent)
- {
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value');
- $related = m::mock(Model::class);
- $related->shouldReceive('getKey')->andReturn(1);
- $related->shouldReceive('getTable')->andReturn('relation');
- $builder->shouldReceive('getModel')->andReturn($related);
- return new MorphTo($builder, $parent, 'foreign_key', 'id', 'morph_type', 'relation');
- }
-
-
- public function getRelation($parent = null, $builder = null)
- {
- $builder = $builder ?: m::mock(Builder::class);
- $builder->shouldReceive('where')->with('relation.id', '=', 'foreign.value');
- $related = m::mock(Model::class);
- $related->shouldReceive('getKeyName')->andReturn('id');
- $related->shouldReceive('getTable')->andReturn('relation');
- $builder->shouldReceive('getModel')->andReturn($related);
- $parent = $parent ?: new EloquentMorphToModelStub;
- $morphTo = m::mock('Illuminate\Database\Eloquent\Relations\MorphTo[createModelByType]', [$builder, $parent, 'foreign_key', 'id', 'morph_type', 'relation']
- );
- return $morphTo;
- }
-
-}
-
-
-class EloquentMorphToModelStub extends Illuminate\Database\Eloquent\Model {
- public $foreign_key = 'foreign.value';
-}
diff --git a/tests/Database/DatabaseEloquentPivotTest.php b/tests/Database/DatabaseEloquentPivotTest.php
deleted file mode 100755
index b7b7f6df5..000000000
--- a/tests/Database/DatabaseEloquentPivotTest.php
+++ /dev/null
@@ -1,104 +0,0 @@
-shouldReceive('getConnectionName')->once()->andReturn('connection');
- $pivot = new Pivot($parent, ['foo' => 'bar'], 'table', true);
-
- $this->assertEquals(['foo' => 'bar'], $pivot->getAttributes());
- $this->assertEquals('connection', $pivot->getConnectionName());
- $this->assertEquals('table', $pivot->getTable());
- $this->assertTrue($pivot->exists);
- }
-
-
- public function testPropertiesUnchangedAreNotDirty(): void
- {
- $parent = m::mock('Illuminate\Database\Eloquent\Model[getConnectionName]');
- $parent->shouldReceive('getConnectionName')->once()->andReturn('connection');
- $pivot = new Pivot($parent, ['foo' => 'bar', 'shimy' => 'shake'], 'table', true);
-
- $this->assertEquals([], $pivot->getDirty());
- }
-
-
- public function testPropertiesChangedAreDirty(): void
- {
- $parent = m::mock('Illuminate\Database\Eloquent\Model[getConnectionName]');
- $parent->shouldReceive('getConnectionName')->once()->andReturn('connection');
- $pivot = new Pivot($parent, ['foo' => 'bar', 'shimy' => 'shake'], 'table', true);
- $pivot->shimy = 'changed';
-
- $this->assertEquals(['shimy' => 'changed'], $pivot->getDirty());
- }
-
-
- public function testTimestampPropertyIsSetIfCreatedAtInAttributes(): void
- {
- $parent = m::mock('Illuminate\Database\Eloquent\Model[getConnectionName,getDates]');
- $parent->shouldReceive('getConnectionName')->andReturn('connection');
- $parent->shouldReceive('getDates')->andReturn([]);
- $pivot = new DatabaseEloquentPivotTestDateStub($parent, ['foo' => 'bar', 'created_at' => 'foo'], 'table');
- $this->assertTrue($pivot->timestamps);
-
- $pivot = new DatabaseEloquentPivotTestDateStub($parent, ['foo' => 'bar'], 'table');
- $this->assertFalse($pivot->timestamps);
- }
-
-
- public function testKeysCanBeSetProperly(): void
- {
- $parent = m::mock('Illuminate\Database\Eloquent\Model[getConnectionName]');
- $parent->shouldReceive('getConnectionName')->once()->andReturn('connection');
- $pivot = new Pivot($parent, ['foo' => 'bar'], 'table');
- $pivot->setPivotKeys('foreign', 'other');
-
- $this->assertEquals('foreign', $pivot->getForeignKey());
- $this->assertEquals('other', $pivot->getOtherKey());
- }
-
-
- public function testDeleteMethodDeletesModelByKeys(): void
- {
- $parent = m::mock('Illuminate\Database\Eloquent\Model[getConnectionName]');
- $parent->guard([]);
- $parent->shouldReceive('getConnectionName')->once()->andReturn('connection');
- $pivot = $this->getMock(Pivot::class, ['newQuery'], [$parent, ['foo' => 'bar'], 'table']);
- $pivot->setPivotKeys('foreign', 'other');
- $pivot->foreign = 'foreign.value';
- $pivot->other = 'other.value';
- $query = m::mock('stdClass');
- $query->shouldReceive('where')->once()->with('foreign', 'foreign.value')->andReturn($query);
- $query->shouldReceive('where')->once()->with('other', 'other.value')->andReturn($query);
- $query->shouldReceive('delete')->once()->andReturn(true);
- $pivot->expects($this->once())->method('newQuery')->willReturn($query);
-
- $this->assertTrue($pivot->delete());
- }
-
-}
-
-
-class DatabaseEloquentPivotTestModelStub extends Illuminate\Database\Eloquent\Model {}
-
-class DatabaseEloquentPivotTestDateStub extends Illuminate\Database\Eloquent\Relations\Pivot {
- #[\Override]
- public function getDates(): array
- {
- return [];
- }
-}
diff --git a/tests/Database/DatabaseEloquentRelationTest.php b/tests/Database/DatabaseEloquentRelationTest.php
deleted file mode 100755
index dfbdcea11..000000000
--- a/tests/Database/DatabaseEloquentRelationTest.php
+++ /dev/null
@@ -1,118 +0,0 @@
-setRelation('test', $relation);
- $parent->setRelation('foo','bar');
- $this->assertTrue(!array_key_exists('foo', $parent->toArray()));
- }
-
-
- public function testTouchMethodUpdatesRelatedTimestamps()
- {
- $builder = m::mock(\Illuminate\Database\Eloquent\Builder::class);
- $parent = m::mock(Model::class);
- $parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
- $builder->shouldReceive('getModel')->andReturn($related = m::mock('StdClass'));
- $builder->shouldReceive('where');
- $relation = new HasOne($builder, $parent, 'foreign_key', 'id');
- $related->shouldReceive('getTable')->andReturn('table');
- $related->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
- $related->shouldReceive('freshTimestampString')->andReturn(Carbon::now());
- $builder->shouldReceive('update')->once()->with(['updated_at' => Carbon::now()]);
-
- $relation->touch();
- }
-
- /**
- * Testing to ensure loop does not occur during relational queries in global scopes
- *
- * Executing parent model's global scopes could result in an infinite loop when the
- * parent model's global scope utilizes a relation in a query like has or whereHas
- */
- public function testDonNotRunParentModelGlobalScopes()
- {
- /** @var Mockery\MockInterface $parent */
- $eloquentBuilder = m::mock(\Illuminate\Database\Eloquent\Builder::class);
- $queryBuilder = m::mock(Builder::class);
- $parent = m::mock('EloquentRelationResetModelStub')->makePartial();
- $grammar = m::mock(Grammar::class);
-
- $eloquentBuilder->shouldReceive('getModel')->andReturn($related = m::mock('StdClass'));
- $eloquentBuilder->shouldReceive('getQuery')->andReturn($queryBuilder);
- $queryBuilder->shouldReceive('getGrammar')->andReturn($grammar);
- $grammar->shouldReceive('wrap');
- $parent->shouldReceive('newQueryWithoutScopes')->andReturn($eloquentBuilder);
-
- //Test Condition
- $parent->shouldReceive('applyGlobalScopes')->andReturn($eloquentBuilder)->never();
-
- $relation = new EloquentRelationStub($eloquentBuilder, $parent);
- $relation->wrap('test');
- }
-
-}
-
-class EloquentRelationResetModelStub extends Illuminate\Database\Eloquent\Model {
- //Override method call which would normally go through __call()
- public function getQuery()
- {
- return $this->newQuery()->getQuery();
- }
-}
-
-
-class EloquentRelationResetStub extends Illuminate\Database\Eloquent\Builder {
- public function __construct() { $this->query = new EloquentRelationQueryStub; }
- #[\Override]
- public function getModel() { return new EloquentRelationResetModelStub; }
-}
-
-
-class EloquentRelationQueryStub extends Illuminate\Database\Query\Builder {
- public function __construct() {}
-}
-
-class EloquentRelationStub extends Relation
-{
- public function addConstraints()
- {
- }
-
- public function addEagerConstraints(array $models)
- {
- }
-
- public function initRelation(array $models, $relation)
- {
- }
-
- public function match(array $models, Collection $results, $relation)
- {
- }
-
- public function getResults()
- {
- }
-}
diff --git a/tests/Database/DatabaseMigrationCreatorTest.php b/tests/Database/DatabaseMigrationCreatorTest.php
deleted file mode 100755
index be3591431..000000000
--- a/tests/Database/DatabaseMigrationCreatorTest.php
+++ /dev/null
@@ -1,67 +0,0 @@
-getCreator();
- unset($_SERVER['__migration.creator']);
- $creator->afterCreate(
- function () {
- $_SERVER['__migration.creator'] = true;
- }
- );
- $creator->expects($this->any())->method('getDatePrefix')->willReturn('foo');
- $creator->getFilesystem()->shouldReceive('get')->once()->with($creator->getStubPath().'/blank.stub')->andReturn('{{class}}');
- $creator->getFilesystem()->shouldReceive('put')->once()->with('foo/foo_create_bar.php', 'CreateBar');
-
- $creator->create('create_bar', 'foo');
-
- $this->assertTrue($_SERVER['__migration.creator']);
-
- unset($_SERVER['__migration.creator']);
- }
-
-
- public function testTableUpdateMigrationStoresMigrationFile()
- {
- $creator = $this->getCreator();
- $creator->expects($this->any())->method('getDatePrefix')->willReturn('foo');
- $creator->getFilesystem()->shouldReceive('get')->once()->with($creator->getStubPath().'/update.stub')->andReturn('{{class}} {{table}}');
- $creator->getFilesystem()->shouldReceive('put')->once()->with('foo/foo_create_bar.php', 'CreateBar baz');
-
- $creator->create('create_bar', 'foo', 'baz');
- }
-
-
- public function testTableCreationMigrationStoresMigrationFile()
- {
- $creator = $this->getCreator();
- $creator->expects($this->any())->method('getDatePrefix')->willReturn('foo');
- $creator->getFilesystem()->shouldReceive('get')->once()->with($creator->getStubPath().'/create.stub')->andReturn('{{class}} {{table}}');
- $creator->getFilesystem()->shouldReceive('put')->once()->with('foo/foo_create_bar.php', 'CreateBar baz');
-
- $creator->create('create_bar', 'foo', 'baz', true);
- }
-
-
- protected function getCreator()
- {
- $files = m::mock(Filesystem::class);
-
- return $this->getMock(MigrationCreator::class, ['getDatePrefix'], [$files]);
- }
-
-}
diff --git a/tests/Database/DatabaseMigrationInstallCommandTest.php b/tests/Database/DatabaseMigrationInstallCommandTest.php
deleted file mode 100755
index fef7eec3e..000000000
--- a/tests/Database/DatabaseMigrationInstallCommandTest.php
+++ /dev/null
@@ -1,33 +0,0 @@
-shouldReceive('setSource')->once()->with('foo');
- $repo->shouldReceive('createRepository')->once();
-
- $this->runCommand($command, ['--database' => 'foo']);
- }
-
-
- protected function runCommand($command, $options = [])
- {
- return $command->run(new Symfony\Component\Console\Input\ArrayInput($options), new Symfony\Component\Console\Output\NullOutput);
- }
-
-}
diff --git a/tests/Database/DatabaseMigrationMakeCommandTest.php b/tests/Database/DatabaseMigrationMakeCommandTest.php
deleted file mode 100755
index 1065386e6..000000000
--- a/tests/Database/DatabaseMigrationMakeCommandTest.php
+++ /dev/null
@@ -1,98 +0,0 @@
- __DIR__];
- $command->setLaravel($app);
- $creator->allows()->create()
- ->once()
- ->with('create_foo', __DIR__.'/database/migrations', null, false)
- ->andReturn($app['path']);
-
- $this->runCommand($command, ['name' => 'create_foo']);
- }
-
-
- public function testBasicCreateGivesCreatorProperArgumentsWhenTableIsSet()
- {
- $command = new DatabaseMigrationMakeCommandTestStub($creator = m::mock(
- MigrationCreator::class
- ), __DIR__.'/vendor');
- $app = ['path' => __DIR__];
- $command->setLaravel($app);
- $creator->allows()->create()
- ->once()
- ->with('create_foo', __DIR__.'/database/migrations', 'users', true)
- ->andReturn($app['path']);
-
- $this->runCommand($command, ['name' => 'create_foo', '--create' => 'users']);
- }
-
-
- public function testPackagePathsMayBeUsed()
- {
- $command = new DatabaseMigrationMakeCommandTestStub($creator = m::mock(
- MigrationCreator::class
- ), __DIR__.'/vendor');
- $app = ['path' => __DIR__];
- $command->setLaravel($app);
- $creator->allows()->create()
- ->once()
- ->with('create_foo', __DIR__.'/vendor/bar/src/migrations', null, false)
- ->andReturn($app['path']);
-
- $this->runCommand($command, ['name' => 'create_foo', '--package' => 'bar']);
- }
-
-
- public function testPackageFallsBackToVendorDirWhenNotExplicit()
- {
- $command = new DatabaseMigrationMakeCommandTestStub($creator = m::mock(
- MigrationCreator::class
- ), __DIR__.'/vendor');
- $creator->allows()->create()
- ->once()
- ->with('create_foo', __DIR__.'/vendor/foo/bar/src/migrations', null, false)
- ->andReturn(__DIR__);
-
- $this->runCommand($command, ['name' => 'create_foo', '--package' => 'foo/bar']);
- }
-
-
- protected function runCommand($command, $input = [])
- {
- return $command->run(
- new Symfony\Component\Console\Input\ArrayInput($input),
- new Symfony\Component\Console\Output\NullOutput
- );
- }
-
-}
-
-
-
-class DatabaseMigrationMakeCommandTestStub extends MigrateMakeCommand
-{
- #[\Override]
- public function call($command, array $arguments = [])
- {
- //
- }
-}
diff --git a/tests/Database/DatabaseMigrationMigrateCommandTest.php b/tests/Database/DatabaseMigrationMigrateCommandTest.php
deleted file mode 100755
index e454aeda7..000000000
--- a/tests/Database/DatabaseMigrationMigrateCommandTest.php
+++ /dev/null
@@ -1,123 +0,0 @@
- __DIR__]);
- $command->setLaravel($app);
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
- $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
-
- $this->runCommand($command);
- }
-
-
- public function testMigrationRepositoryCreatedWhenNecessary()
- {
- $params = [$migrator = m::mock(Migrator::class), __DIR__.'/vendor'];
- $command = $this->getMock(MigrateCommand::class, ['call'], $params);
- $app = new ApplicationDatabaseMigrationStub(['path' => __DIR__]);
- $command->setLaravel($app);
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
- $migrator->shouldReceive('repositoryExists')->once()->andReturn(false);
- $command->expects($this->once())->method('call')->with($this->equalTo('migrate:install'), $this->equalTo(
- ['--database' => null]
- ));
-
- $this->runCommand($command);
- }
-
-
- public function testPackageIsRespectedWhenMigrating()
- {
- $command = new MigrateCommand($migrator = m::mock(Migrator::class), __DIR__.'/vendor');
- $command->setLaravel(new ApplicationDatabaseMigrationStub());
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('run')->once()->with(__DIR__.'/vendor/bar/src/migrations', false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
- $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
-
- $this->runCommand($command, ['--package' => 'bar']);
- }
-
-
- public function testVendorPackageIsRespectedWhenMigrating()
- {
- $command = new MigrateCommand($migrator = m::mock(Migrator::class), __DIR__.'/vendor');
- $command->setLaravel(new ApplicationDatabaseMigrationStub());
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('run')->once()->with(__DIR__.'/vendor/foo/bar/src/migrations', false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
- $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
-
- $this->runCommand($command, ['--package' => 'foo/bar']);
- }
-
-
- public function testTheCommandMayBePretended()
- {
- $command = new MigrateCommand($migrator = m::mock(Migrator::class), __DIR__.'/vendor');
- $app = new ApplicationDatabaseMigrationStub(['path' => __DIR__]);
- $command->setLaravel($app);
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', true);
- $migrator->shouldReceive('getNotes')->andReturn([]);
- $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
-
- $this->runCommand($command, ['--pretend' => true]);
- }
-
-
- public function testTheDatabaseMayBeSet()
- {
- $command = new MigrateCommand($migrator = m::mock(Migrator::class), __DIR__.'/vendor');
- $app = new ApplicationDatabaseMigrationStub(['path' => __DIR__]);
- $command->setLaravel($app);
- $migrator->shouldReceive('setConnection')->once()->with('foo');
- $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
- $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
-
- $this->runCommand($command, ['--database' => 'foo']);
- }
-
-
- protected function runCommand($command, $input = [])
- {
- return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), new Symfony\Component\Console\Output\NullOutput);
- }
-
-}
-
-class ApplicationDatabaseMigrationStub implements ArrayAccess {
- public $content = [];
- public $env = 'development';
- public function __construct(array $data = []) { $this->content = $data; }
- public function offsetExists($offset): bool
- { return isset($this->content[$offset]); }
- public function offsetGet($offset): mixed { return $this->content[$offset]; }
- public function offsetSet($offset, $value): void { $this->content[$offset] = $value; }
- public function offsetUnset($offset): void { unset($this->content[$offset]); }
- public function environment() { return $this->env; }
-}
diff --git a/tests/Database/DatabaseMigrationRepositoryTest.php b/tests/Database/DatabaseMigrationRepositoryTest.php
deleted file mode 100755
index 7f289c7e7..000000000
--- a/tests/Database/DatabaseMigrationRepositoryTest.php
+++ /dev/null
@@ -1,119 +0,0 @@
-getRepository();
- $query = m::mock('stdClass');
- $connectionMock = m::mock(Connection::class);
- $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
- $repo->getConnection()->shouldReceive('table')->once()->with('migrations')->andReturn($query);
- $query->shouldReceive('pluck')->once()->with('migration')->andReturn('bar');
-
- $this->assertEquals('bar', $repo->getRan());
- }
-
-
- public function testGetLastMigrationsGetsAllMigrationsWithTheLatestBatchNumber()
- {
- $repo = $this->getMock(DatabaseMigrationRepository::class, ['getLastBatchNumber'], [
- $resolver = m::mock(ConnectionResolverInterface::class), 'migrations'
- ]);
- $repo->expects($this->once())->method('getLastBatchNumber')->willReturn(1);
- $query = m::mock('stdClass');
- $connectionMock = m::mock(Connection::class);
- $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
- $repo->getConnection()->shouldReceive('table')->once()->with('migrations')->andReturn($query);
- $query->shouldReceive('where')->once()->with('batch', 1)->andReturn($query);
- $query->shouldReceive('orderBy')->once()->with('migration', 'desc')->andReturn($query);
- $query->shouldReceive('get')->once()->andReturn('foo');
-
- $this->assertEquals('foo', $repo->getLast());
- }
-
-
- public function testLogMethodInsertsRecordIntoMigrationTable()
- {
- $repo = $this->getRepository();
- $query = m::mock('stdClass');
- $connectionMock = m::mock(Connection::class);
- $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
- $repo->getConnection()->shouldReceive('table')->once()->with('migrations')->andReturn($query);
- $query->shouldReceive('insert')->once()->with(['migration' => 'bar', 'batch' => 1]);
-
- $repo->log('bar', 1);
- }
-
-
- public function testDeleteMethodRemovesAMigrationFromTheTable()
- {
- $repo = $this->getRepository();
- $query = m::mock('stdClass');
- $connectionMock = m::mock(Connection::class);
- $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
- $repo->getConnection()->shouldReceive('table')->once()->with('migrations')->andReturn($query);
- $query->shouldReceive('where')->once()->with('migration', 'foo')->andReturn($query);
- $query->shouldReceive('delete')->once();
- $migration = (object) ['migration' => 'foo'];
-
- $repo->delete($migration);
- }
-
-
- public function testGetNextBatchNumberReturnsLastBatchNumberPlusOne()
- {
- $repo = $this->getMock(DatabaseMigrationRepository::class, ['getLastBatchNumber'], [
- m::mock(ConnectionResolverInterface::class), 'migrations'
- ]);
- $repo->expects($this->once())->method('getLastBatchNumber')->willReturn(1);
-
- $this->assertEquals(2, $repo->getNextBatchNumber());
- }
-
-
- public function testGetLastBatchNumberReturnsMaxBatch()
- {
- $repo = $this->getRepository();
- $query = m::mock('stdClass');
- $connectionMock = m::mock(Connection::class);
- $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
- $repo->getConnection()->shouldReceive('table')->once()->with('migrations')->andReturn($query);
- $query->shouldReceive('max')->once()->andReturn(1);
-
- $this->assertEquals(1, $repo->getLastBatchNumber());
- }
-
-
- public function testCreateRepositoryCreatesProperDatabaseTable()
- {
- $repo = $this->getRepository();
- $schema = m::mock('stdClass');
- $connectionMock = m::mock(Connection::class);
- $repo->getConnectionResolver()->shouldReceive('connection')->with(null)->andReturn($connectionMock);
- $repo->getConnection()->shouldReceive('getSchemaBuilder')->once()->andReturn($schema);
- $schema->shouldReceive('create')->once()->with('migrations', m::type('Closure'));
-
- $repo->createRepository();
- }
-
-
- protected function getRepository()
- {
- return new DatabaseMigrationRepository(m::mock(ConnectionResolverInterface::class), 'migrations');
- }
-
-}
diff --git a/tests/Database/DatabaseMigrationResetCommandTest.php b/tests/Database/DatabaseMigrationResetCommandTest.php
deleted file mode 100755
index 6ac4e6275..000000000
--- a/tests/Database/DatabaseMigrationResetCommandTest.php
+++ /dev/null
@@ -1,50 +0,0 @@
-setLaravel(new AppDatabaseMigrationStub());
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('rollback')->twice()->with(false)->andReturn(true, false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
-
- $this->runCommand($command);
- }
-
-
- public function testResetCommandCanBePretended()
- {
- $command = new ResetCommand($migrator = m::mock(Migrator::class));
- $command->setLaravel(new AppDatabaseMigrationStub());
- $migrator->shouldReceive('setConnection')->once()->with('foo');
- $migrator->shouldReceive('rollback')->twice()->with(true)->andReturn(true, false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
-
- $this->runCommand($command, ['--pretend' => true, '--database' => 'foo']);
- }
-
-
- protected function runCommand($command, $input = [])
- {
- return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), new Symfony\Component\Console\Output\NullOutput);
- }
-}
-
-class AppDatabaseMigrationStub {
- public $env = 'development';
- public function environment() { return $this->env; }
-}
diff --git a/tests/Database/DatabaseMigrationRollbackCommandTest.php b/tests/Database/DatabaseMigrationRollbackCommandTest.php
deleted file mode 100755
index c9fad6a20..000000000
--- a/tests/Database/DatabaseMigrationRollbackCommandTest.php
+++ /dev/null
@@ -1,51 +0,0 @@
-setLaravel(new AppDatabaseMigrationRollbackStub());
- $migrator->shouldReceive('setConnection')->once()->with(null);
- $migrator->shouldReceive('rollback')->once()->with(false);
- $migrator->shouldReceive('getNotes')->andReturn([]);
-
- $this->runCommand($command);
- }
-
-
- public function testRollbackCommandCanBePretended()
- {
- $command = new RollbackCommand($migrator = m::mock(Migrator::class));
- $command->setLaravel(new AppDatabaseMigrationRollbackStub());
- $migrator->shouldReceive('setConnection')->once()->with('foo');
- $migrator->shouldReceive('rollback')->once()->with(true);
- $migrator->shouldReceive('getNotes')->andReturn([]);
-
- $this->runCommand($command, ['--pretend' => true, '--database' => 'foo']);
- }
-
-
- protected function runCommand($command, $input = [])
- {
- return $command->run(new Symfony\Component\Console\Input\ArrayInput($input), new Symfony\Component\Console\Output\NullOutput);
- }
-
-}
-
-class AppDatabaseMigrationRollbackStub {
- public $env = 'development';
- public function environment() { return $this->env; }
-}
diff --git a/tests/Database/DatabaseMigratorTest.php b/tests/Database/DatabaseMigratorTest.php
deleted file mode 100755
index 5b236a5bc..000000000
--- a/tests/Database/DatabaseMigratorTest.php
+++ /dev/null
@@ -1,223 +0,0 @@
-getMock(
- Migrator::class,
- ['resolve'],
- [
- m::mock(MigrationRepositoryInterface::class),
- $resolver = m::mock(ConnectionResolverInterface::class),
- m::mock(Filesystem::class),
- ]
- );
- $migrator->getFilesystem()->shouldReceive('glob')->once()->with(__DIR__.'/*_*.php')->andReturn([
- __DIR__.'/2_bar.php',
- __DIR__.'/1_foo.php',
- __DIR__.'/3_baz.php',
- ]);
-
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/2_bar.php');
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/1_foo.php');
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/3_baz.php');
-
- $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([
- '1_foo',
- ]);
- $migrator->getRepository()->shouldReceive('getNextBatchNumber')->once()->andReturn(1);
- $migrator->getRepository()->shouldReceive('log')->once()->with('2_bar', 1);
- $migrator->getRepository()->shouldReceive('log')->once()->with('3_baz', 1);
- $barMock = m::mock(stdClass::class);
- $barMock->shouldReceive('up')->once();
- $bazMock = m::mock(stdClass::class);
- $bazMock->shouldReceive('up')->once();
-
- $migrator
- ->expects($this->exactly(2))
- ->method('resolve')
- ->withConsecutive([$this->equalTo('2_bar')], [$this->equalTo('3_baz')])
- ->willReturnOnConsecutiveCalls($barMock, $bazMock);
-
- $migrator->run(__DIR__);
- }
-
-
- public function testUpMigrationCanBePretended()
- {
- $migrator = $this->getMock(Migrator::class, ['resolve'], [
- m::mock(MigrationRepositoryInterface::class),
- $resolver = m::mock(ConnectionResolverInterface::class),
- m::mock(Filesystem::class),
- ]);
- $migrator->getFilesystem()->shouldReceive('glob')->once()->with(__DIR__.'/*_*.php')->andReturn([
- __DIR__.'/2_bar.php',
- __DIR__.'/1_foo.php',
- __DIR__.'/3_baz.php',
- ]);
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/2_bar.php');
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/1_foo.php');
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/3_baz.php');
- $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([
- '1_foo',
- ]);
- $migrator->getRepository()->shouldReceive('getNextBatchNumber')->once()->andReturn(1);
-
- $barMock = m::mock(stdClass::class);
- $barMock->shouldReceive('getConnection')->once()->andReturn(null);
- $barMock->shouldReceive('up')->once();
-
- $bazMock = m::mock(stdClass::class);
- $bazMock->shouldReceive('getConnection')->once()->andReturn(null);
- $bazMock->shouldReceive('up')->once();
-
- $migrator
- ->expects($this->exactly(2))
- ->method('resolve')
- ->withConsecutive([$this->equalTo('2_bar')], [$this->equalTo('3_baz')])
- ->willReturnOnConsecutiveCalls($barMock, $bazMock);
-
- $connection = m::mock(stdClass::class);
- $connection->shouldReceive('pretend')->with(m::type('Closure'))->andReturnUsing(function($closure)
- {
- $closure();
- return [['query' => 'foo']];
- },
- function($closure)
- {
- $closure();
- return [['query' => 'bar']];
- });
- $resolver->shouldReceive('connection')->with(null)->andReturn($connection);
-
- $migrator->run(__DIR__, true);
- }
-
-
- public function testNothingIsDoneWhenNoMigrationsAreOutstanding()
- {
- $migrator = $this->getMock(Migrator::class, ['resolve'], [
- m::mock(MigrationRepositoryInterface::class),
- $resolver = m::mock(ConnectionResolverInterface::class),
- m::mock(Filesystem::class),
- ]);
- $migrator->getFilesystem()->shouldReceive('glob')->once()->with(__DIR__.'/*_*.php')->andReturn([
- __DIR__.'/1_foo.php',
- ]);
- $migrator->getFilesystem()->shouldReceive('requireOnce')->with(__DIR__.'/1_foo.php');
- $migrator->getRepository()->shouldReceive('getRan')->once()->andReturn([
- '1_foo',
- ]);
-
- $migrator->run(__DIR__);
- }
-
-
- public function testLastBatchOfMigrationsCanBeRolledBack()
- {
- $migrator = $this->getMock(Migrator::class, ['resolve'], [
- m::mock(MigrationRepositoryInterface::class),
- $resolver = m::mock(ConnectionResolverInterface::class),
- m::mock(Filesystem::class),
- ]);
- $migrator->getRepository()->shouldReceive('getLast')->once()->andReturn([
- $fooMigration = new MigratorTestMigrationStub('foo'),
- $barMigration = new MigratorTestMigrationStub('bar'),
- ]);
-
- $barMock = m::mock(stdClass::class);
- $barMock->shouldReceive('down')->once();
-
- $fooMock = m::mock(stdClass::class);
- $fooMock->shouldReceive('down')->once();
-
- $migrator
- ->expects($this->exactly(2))
- ->method('resolve')
- ->withConsecutive([$this->equalTo('foo')], [$this->equalTo('bar')])
- ->willReturnOnConsecutiveCalls($barMock, $fooMock);
-
- $migrator->getRepository()->shouldReceive('delete')->once()->with($barMigration);
- $migrator->getRepository()->shouldReceive('delete')->once()->with($fooMigration);
-
- $migrator->rollback();
- }
-
-
- public function testRollbackMigrationsCanBePretended()
- {
- $migrator = $this->getMock(Migrator::class, ['resolve'], [
- m::mock(MigrationRepositoryInterface::class),
- $resolver = m::mock(ConnectionResolverInterface::class),
- m::mock(Filesystem::class),
- ]);
- $migrator->getRepository()->shouldReceive('getLast')->once()->andReturn([
- $fooMigration = new MigratorTestMigrationStub('foo'),
- $barMigration = new MigratorTestMigrationStub('bar'),
- ]);
-
- $barMock = m::mock(stdClass::class);
- $barMock->shouldReceive('getConnection')->once()->andReturn(null);
- $barMock->shouldReceive('down')->once();
-
- $fooMock = m::mock(stdClass::class);
- $fooMock->shouldReceive('getConnection')->once()->andReturn(null);
- $fooMock->shouldReceive('down')->once();
-
- $migrator
- ->expects($this->exactly(2))
- ->method('resolve')
- ->withConsecutive([$this->equalTo('foo')], [$this->equalTo('bar')])
- ->willReturnOnConsecutiveCalls($barMock, $fooMock);
-
- $connection = m::mock(stdClass::class);
- $connection->shouldReceive('pretend')->with(m::type('Closure'))->andReturnUsing(function($closure)
- {
- $closure();
- return [['query' => 'bar']];
- },
- function($closure)
- {
- $closure();
- return [['query' => 'foo']];
- });
- $resolver->shouldReceive('connection')->with(null)->andReturn($connection);
-
- $migrator->rollback(true);
- }
-
-
- public function testNothingIsRolledBackWhenNothingInRepository()
- {
- $migrator = $this->getMock(Migrator::class, ['resolve'], [
- m::mock(MigrationRepositoryInterface::class),
- $resolver = m::mock(ConnectionResolverInterface::class),
- m::mock(Filesystem::class),
- ]);
- $migrator->getRepository()->shouldReceive('getLast')->once()->andReturn([]);
-
- $migrator->rollback();
- }
-
-}
-
-
-class MigratorTestMigrationStub {
- public function __construct($migration) { $this->migration = $migration; }
- public $migration;
-}
diff --git a/tests/Database/DatabaseMySqlProcessorTest.php b/tests/Database/DatabaseMySqlProcessorTest.php
deleted file mode 100644
index 2ef41c893..000000000
--- a/tests/Database/DatabaseMySqlProcessorTest.php
+++ /dev/null
@@ -1,22 +0,0 @@
- 'id'], ['column_name' => 'name'], ['column_name' => 'email']];
- $expected = ['id', 'name', 'email'];
- $this->assertEquals($expected, $processor->processColumnListing($listing));
-
- // convert listing to objects to simulate PDO::FETCH_CLASS
- foreach($listing as &$row) {
- $row = (object) $row;
- }
-
- $this->assertEquals($expected, $processor->processColumnListing($listing));
- }
-
-}
diff --git a/tests/Database/DatabaseMySqlSchemaGrammarTest.php b/tests/Database/DatabaseMySqlSchemaGrammarTest.php
deleted file mode 100755
index fb852688b..000000000
--- a/tests/Database/DatabaseMySqlSchemaGrammarTest.php
+++ /dev/null
@@ -1,544 +0,0 @@
-create();
- $blueprint->increments('id');
- $blueprint->string('email');
-
- $conn = $this->getConnection();
- $conn->shouldReceive('getConfig')->once()->with('charset')->andReturn('utf8');
- $conn->shouldReceive('getConfig')->once()->with('collation')->andReturn('utf8_unicode_ci');
-
- $statements = $blueprint->toSql($conn, $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate utf8_unicode_ci', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $blueprint->string('email');
-
- $conn = $this->getConnection();
- $conn->shouldReceive('getConfig')->andReturn(null);
-
- $statements = $blueprint->toSql($conn, $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `id` int unsigned not null auto_increment primary key, add `email` varchar(255) not null', $statements[0]);
- }
-
-
- public function testBasicCreateTableWithPrefix()
- {
- $blueprint = new Blueprint('users');
- $blueprint->create();
- $blueprint->increments('id');
- $blueprint->string('email');
- $grammar = $this->getGrammar();
- $grammar->setTablePrefix('prefix_');
-
- $conn = $this->getConnection();
- $conn->shouldReceive('getConfig')->andReturn(null);
-
- $statements = $blueprint->toSql($conn, $grammar);
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table `prefix_users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null)', $statements[0]);
- }
-
-
- public function testDropTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->drop();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table `users`', $statements[0]);
- }
-
-
- public function testDropTableIfExists()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIfExists();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table if exists `users`', $statements[0]);
- }
-
-
- public function testDropColumn()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop `foo`', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn(['foo', 'bar']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop `foo`, drop `bar`', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop `foo`, drop `bar`', $statements[0]);
- }
-
-
- public function testDropPrimary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropPrimary();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop primary key', $statements[0]);
- }
-
-
- public function testDropUnique()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropUnique('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop index foo', $statements[0]);
- }
-
-
- public function testDropIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIndex('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop index foo', $statements[0]);
- }
-
-
- public function testDropForeign()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropForeign('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop foreign key foo', $statements[0]);
- }
-
-
- public function testDropTimestamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropTimestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` drop `created_at`, drop `updated_at`', $statements[0]);
- }
-
-
- public function testRenameTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rename('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('rename table `users` to `foo`', $statements[0]);
- }
-
-
- public function testAddingPrimaryKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->primary('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add primary key bar(`foo`)', $statements[0]);
- }
-
-
- public function testAddingUniqueKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->unique('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add unique bar(`foo`)', $statements[0]);
- }
-
-
- public function testAddingIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->index(['foo', 'bar'], 'baz');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add index baz(`foo`, `bar`)', $statements[0]);
- }
-
-
- public function testAddingForeignKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->foreign('foo_id')->references('id')->on('orders');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add constraint users_foo_id_foreign foreign key (`foo_id`) references `orders` (`id`)', $statements[0]);
- }
-
-
- public function testAddingIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `id` int unsigned not null auto_increment primary key', $statements[0]);
- }
-
-
- public function testAddingBigIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigIncrements('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `id` bigint unsigned not null auto_increment primary key', $statements[0]);
- }
-
-
- public function testAddingColumnAfterAnotherColumn()
- {
- $blueprint = new Blueprint('users');
- $blueprint->string('name')->after('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `name` varchar(255) not null after `foo`', $statements[0]);
- }
-
-
- public function testAddingString()
- {
- $blueprint = new Blueprint('users');
- $blueprint->string('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` varchar(255) not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` varchar(100) not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100)->nullable()->default('bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` varchar(100) null default \'bar\'', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100)->nullable()->default(new Illuminate\Database\Query\Expression('CURRENT TIMESTAMP'));
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` varchar(100) null default CURRENT TIMESTAMP', $statements[0]);
- }
-
-
- public function testAddingText()
- {
- $blueprint = new Blueprint('users');
- $blueprint->text('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` text not null', $statements[0]);
- }
-
-
- public function testAddingBigInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` bigint not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` bigint not null auto_increment primary key', $statements[0]);
- }
-
-
- public function testAddingInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` int not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` int not null auto_increment primary key', $statements[0]);
- }
-
-
- public function testAddingMediumInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->mediumInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` mediumint not null', $statements[0]);
- }
-
-
- public function testAddingSmallInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->smallInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` smallint not null', $statements[0]);
- }
-
-
- public function testAddingTinyInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->tinyInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` tinyint not null', $statements[0]);
- }
-
-
- public function testAddingFloat()
- {
- $blueprint = new Blueprint('users');
- $blueprint->float('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` float(5, 2) not null', $statements[0]);
- }
-
-
- public function testAddingDouble()
- {
- $blueprint = new Blueprint('users');
- $blueprint->double('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` double not null', $statements[0]);
- }
-
-
- public function testAddingDoubleSpecifyingPrecision()
- {
- $blueprint = new Blueprint('users');
- $blueprint->double('foo', 15, 8);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` double(15, 8) not null', $statements[0]);
- }
-
-
- public function testAddingDecimal()
- {
- $blueprint = new Blueprint('users');
- $blueprint->decimal('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` decimal(5, 2) not null', $statements[0]);
- }
-
-
- public function testAddingBoolean()
- {
- $blueprint = new Blueprint('users');
- $blueprint->boolean('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` tinyint(1) not null', $statements[0]);
- }
-
-
- public function testAddingEnum()
- {
- $blueprint = new Blueprint('users');
- $blueprint->enum('foo', ['bar', 'baz']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` enum(\'bar\', \'baz\') not null', $statements[0]);
- }
-
-
- public function testAddingDate()
- {
- $blueprint = new Blueprint('users');
- $blueprint->date('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` date not null', $statements[0]);
- }
-
-
- public function testAddingDateTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dateTime('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` datetime not null', $statements[0]);
- }
-
-
- public function testAddingTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->time('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` time not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamp()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamp('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` timestamp default 0 not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `created_at` datetime not null, add `updated_at` datetime not null', $statements[0]);
- }
-
-
- public function testAddingTimeStampsWithRealTimestampColumnType()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestampsWithTimestampColumnType();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `created_at` timestamp default 0 not null, add `updated_at` timestamp default 0 not null', $statements[0]);
- }
-
-
- public function testAddingNullableTimeStamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->nullableTimestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `created_at` datetime null, add `updated_at` datetime null', $statements[0]);
- }
-
-
- public function testAddingRememberToken()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rememberToken();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `remember_token` varchar(100) null', $statements[0]);
- }
-
-
- public function testAddingBinary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->binary('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table `users` add `foo` blob not null', $statements[0]);
- }
-
-
- protected function getConnection()
- {
- return m::mock(Connection::class);
- }
-
-
- public function getGrammar()
- {
- return new Illuminate\Database\Schema\Grammars\MySqlGrammar;
- }
-
-}
diff --git a/tests/Database/DatabasePostgresProcessorTest.php b/tests/Database/DatabasePostgresProcessorTest.php
deleted file mode 100644
index abef1d890..000000000
--- a/tests/Database/DatabasePostgresProcessorTest.php
+++ /dev/null
@@ -1,25 +0,0 @@
- 'id'], ['column_name' => 'name'], ['column_name' => 'email']];
- $expected = ['id', 'name', 'email'];
-
- $this->assertEquals($expected, $processor->processColumnListing($listing));
-
- // convert listing to objects to simulate PDO::FETCH_CLASS
- foreach($listing as &$row)
- {
- $row = (object) $row;
- }
-
- $this->assertEquals($expected, $processor->processColumnListing($listing));
- }
-
-}
diff --git a/tests/Database/DatabasePostgresSchemaGrammarTest.php b/tests/Database/DatabasePostgresSchemaGrammarTest.php
deleted file mode 100755
index d616ec689..000000000
--- a/tests/Database/DatabasePostgresSchemaGrammarTest.php
+++ /dev/null
@@ -1,443 +0,0 @@
-create();
- $blueprint->increments('id');
- $blueprint->string('email');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table "users" ("id" serial primary key not null, "email" varchar(255) not null)', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $blueprint->string('email');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "id" serial primary key not null, add column "email" varchar(255) not null', $statements[0]);
- }
-
-
- public function testDropTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->drop();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table "users"', $statements[0]);
- }
-
-
- public function testDropTableIfExists()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIfExists();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table if exists "users"', $statements[0]);
- }
-
-
- public function testDropColumn()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "foo"', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn(['foo', 'bar']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "foo", drop column "bar"', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "foo", drop column "bar"', $statements[0]);
- }
-
-
- public function testDropPrimary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropPrimary();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop constraint users_pkey', $statements[0]);
- }
-
-
- public function testDropUnique()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropUnique('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop constraint foo', $statements[0]);
- }
-
-
- public function testDropIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIndex('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop index foo', $statements[0]);
- }
-
-
- public function testDropForeign()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropForeign('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop constraint foo', $statements[0]);
- }
-
-
- public function testDropTimestamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropTimestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "created_at", drop column "updated_at"', $statements[0]);
- }
-
-
- public function testRenameTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rename('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" rename to "foo"', $statements[0]);
- }
-
-
- public function testAddingPrimaryKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->primary('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add primary key ("foo")', $statements[0]);
- }
-
-
- public function testAddingUniqueKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->unique('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add constraint bar unique ("foo")', $statements[0]);
- }
-
-
- public function testAddingIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->index(['foo', 'bar'], 'baz');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create index baz on "users" ("foo", "bar")', $statements[0]);
- }
-
-
- public function testAddingIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "id" serial primary key not null', $statements[0]);
- }
-
-
- public function testAddingBigIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigIncrements('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "id" bigserial primary key not null', $statements[0]);
- }
-
-
- public function testAddingString()
- {
- $blueprint = new Blueprint('users');
- $blueprint->string('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar(255) not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar(100) not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100)->nullable()->default('bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar(100) null default \'bar\'', $statements[0]);
- }
-
-
- public function testAddingText()
- {
- $blueprint = new Blueprint('users');
- $blueprint->text('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]);
- }
-
-
- public function testAddingBigInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" bigint not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" bigserial primary key not null', $statements[0]);
- }
-
-
- public function testAddingInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" serial primary key not null', $statements[0]);
- }
-
-
- public function testAddingMediumInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->mediumInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
- }
-
-
- public function testAddingTinyInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->tinyInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" smallint not null', $statements[0]);
- }
-
-
- public function testAddingSmallInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->smallInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" smallint not null', $statements[0]);
- }
-
-
- public function testAddingFloat()
- {
- $blueprint = new Blueprint('users');
- $blueprint->float('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" real not null', $statements[0]);
- }
-
-
- public function testAddingDouble()
- {
- $blueprint = new Blueprint('users');
- $blueprint->double('foo', 15, 8);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" double precision not null', $statements[0]);
- }
-
-
- public function testAddingDecimal()
- {
- $blueprint = new Blueprint('users');
- $blueprint->decimal('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" decimal(5, 2) not null', $statements[0]);
- }
-
-
- public function testAddingBoolean()
- {
- $blueprint = new Blueprint('users');
- $blueprint->boolean('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" boolean not null', $statements[0]);
- }
-
-
- public function testAddingEnum()
- {
- $blueprint = new Blueprint('users');
- $blueprint->enum('foo', ['bar', 'baz']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar(255) check ("foo" in (\'bar\', \'baz\')) not null', $statements[0]);
- }
-
-
- public function testAddingDate()
- {
- $blueprint = new Blueprint('users');
- $blueprint->date('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" date not null', $statements[0]);
- }
-
-
- public function testAddingDateTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dateTime('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" timestamp not null', $statements[0]);
- }
-
-
- public function testAddingTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->time('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" time not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamp()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamp('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" timestamp not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "created_at" timestamp not null, add column "updated_at" timestamp not null', $statements[0]);
- }
-
-
- public function testAddingBinary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->binary('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" bytea not null', $statements[0]);
- }
-
-
- protected function getConnection()
- {
- return m::mock(Connection::class);
- }
-
-
- public function getGrammar()
- {
- return new Illuminate\Database\Schema\Grammars\PostgresGrammar;
- }
-
-}
diff --git a/tests/Database/DatabaseProcessorTest.php b/tests/Database/DatabaseProcessorTest.php
deleted file mode 100755
index 9575845ff..000000000
--- a/tests/Database/DatabaseProcessorTest.php
+++ /dev/null
@@ -1,43 +0,0 @@
-createMock(ProcessorTestPDOStub::class);
- $pdo->expects($this->once())->method('lastInsertId')->with($this->equalTo('id'))->willReturn('1');
- $connection = m::mock(Connection::class);
- $connection->shouldReceive('insert')->once()->with('sql', ['foo']);
- $connection->shouldReceive('getPdo')->once()->andReturn($pdo);
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('getConnection')->andReturn($connection);
- $processor = new Illuminate\Database\Query\Processors\Processor;
- $result = $processor->processInsertGetId($builder, 'sql', ['foo'], 'id');
- $this->assertSame(1, $result);
- }
-
-}
-
-class ProcessorTestPDOStub extends PDO {
-
- public function __construct() {
- //
- }
-
- public function lastInsertId($sequence = null): string|false {
- //
- }
-
-}
diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php
deleted file mode 100755
index ffc73c47c..000000000
--- a/tests/Database/DatabaseQueryBuilderTest.php
+++ /dev/null
@@ -1,1530 +0,0 @@
-getBuilder();
- $builder->select('*')->from('users');
- $this->assertEquals('select * from "users"', $builder->toSql());
- }
-
-
- public function testBasicSelectUseWritePdo(): void
- {
- $builder = $this->getMySqlBuilderWithProcessor();
- $builder->getConnection()->shouldReceive('select')->once()
- ->with('select * from `users`', [], false);
- $builder->useWritePdo()->select('*')->from('users')->get();
-
- $builder = $this->getMySqlBuilderWithProcessor();
- $builder->getConnection()->shouldReceive('select')->once()
- ->with('select * from `users`', []);
- $builder->select('*')->from('users')->get();
- }
-
-
- public function testBasicTableWrappingProtectsQuotationMarks(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('some"table');
- $this->assertEquals('select * from "some""table"', $builder->toSql());
- }
-
- public function testAliasWrappingAsWholeConstant(): void
- {
- $builder = $this->getBuilder();
- $builder->select('x.y as foo.bar')->from('baz');
- $this->assertEquals('select "x"."y" as "foo.bar" from "baz"', $builder->toSql());
- }
-
- public function testAddingSelects(): void
- {
- $builder = $this->getBuilder();
- $builder->select('foo')->addSelect('bar')->addSelect(['baz', 'boom'])->from('users');
- $this->assertEquals('select "foo", "bar", "baz", "boom" from "users"', $builder->toSql());
- }
-
-
- public function testBasicSelectWithPrefix(): void
- {
- $builder = $this->getBuilder();
- $builder->getGrammar()->setTablePrefix('prefix_');
- $builder->select('*')->from('users');
- $this->assertEquals('select * from "prefix_users"', $builder->toSql());
- }
-
-
- public function testBasicSelectDistinct(): void
- {
- $builder = $this->getBuilder();
- $builder->distinct()->select('foo', 'bar')->from('users');
- $this->assertEquals('select distinct "foo", "bar" from "users"', $builder->toSql());
- }
-
-
- public function testSelectWithCaching(): void
- {
- $cache = m::mock('stdClass');
- $driver = m::mock('stdClass');
- $query = $this->setupCacheTestQuery($cache, $driver);
-
- $query = $query->remember(5);
-
- $driver->shouldReceive('remember')
- ->once()
- ->with($query->getCacheKey(), m::type(\DateTimeInterface::class), m::type('Closure'))
- ->andReturnUsing(function($key, $minutes, $callback) { return $callback(); });
-
-
- $this->assertEquals($query->get(), ['results']);
- }
-
-
- public function testSelectWithCachingForever(): void
- {
- $cache = m::mock('stdClass');
- $driver = m::mock('stdClass');
- $query = $this->setupCacheTestQuery($cache, $driver);
-
- $query = $query->rememberForever();
-
- $driver->shouldReceive('rememberForever')
- ->once()
- ->with($query->getCacheKey(), m::type('Closure'))
- ->andReturnUsing(function($key, $callback) { return $callback(); });
-
-
-
- $this->assertEquals($query->get(), ['results']);
- }
-
-
- public function testSelectWithCachingAndTags(): void
- {
- $taggedCache = m::mock('StdClass');
- $cache = m::mock('stdClass');
- $driver = m::mock('stdClass');
-
- $driver->shouldReceive('tags')
- ->once()
- ->with(['foo','bar'])
- ->andReturn($taggedCache);
-
- $query = $this->setupCacheTestQuery($cache, $driver);
- $query = $query->cacheTags(['foo', 'bar'])->remember(5);
-
- $taggedCache->shouldReceive('remember')
- ->once()
- ->with($query->getCacheKey(), m::type(\DateTimeInterface::class), m::type('Closure'))
- ->andReturnUsing(function($key, $minutes, $callback) { return $callback(); });
-
- $this->assertEquals($query->get(), ['results']);
- }
-
-
- public function testBasicAlias(): void
- {
- $builder = $this->getBuilder();
- $builder->select('foo as bar')->from('users');
- $this->assertEquals('select "foo" as "bar" from "users"', $builder->toSql());
- }
-
-
- public function testBasicTableWrapping(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('public.users');
- $this->assertEquals('select * from "public"."users"', $builder->toSql());
- }
-
-
- public function testBasicWheres(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $this->assertEquals('select * from "users" where "id" = ?', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testMySqlWrappingProtectsQuotationMarks(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->From('some`table');
- $this->assertEquals('select * from `some``table`', $builder->toSql());
- }
-
-
- public function testWhereDayMySql(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users')->whereDay('created_at', '=', 1);
- $this->assertEquals('select * from `users` where day(`created_at`) = ?', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testWhereMonthMySql(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users')->whereMonth('created_at', '=', 5);
- $this->assertEquals('select * from `users` where month(`created_at`) = ?', $builder->toSql());
- $this->assertEquals([0 => 5], $builder->getBindings());
- }
-
-
- public function testWhereYearMySql(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users')->whereYear('created_at', '=', 2014);
- $this->assertEquals('select * from `users` where year(`created_at`) = ?', $builder->toSql());
- $this->assertEquals([0 => 2014], $builder->getBindings());
- }
-
-
- public function testWhereDayPostgres(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('users')->whereDay('created_at', '=', 1);
- $this->assertEquals('select * from "users" where day("created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testWhereMonthPostgres(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('users')->whereMonth('created_at', '=', 5);
- $this->assertEquals('select * from "users" where month("created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 5], $builder->getBindings());
- }
-
-
- public function testWhereYearPostgres(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('users')->whereYear('created_at', '=', 2014);
- $this->assertEquals('select * from "users" where year("created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 2014], $builder->getBindings());
- }
-
-
- public function testWhereDaySqlite(): void
- {
- $builder = $this->getSQLiteBuilder();
- $builder->select('*')->from('users')->whereDay('created_at', '=', 1);
- $this->assertEquals('select * from "users" where strftime(\'%d\', "created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testWhereMonthSqlite(): void
- {
- $builder = $this->getSQLiteBuilder();
- $builder->select('*')->from('users')->whereMonth('created_at', '=', 5);
- $this->assertEquals('select * from "users" where strftime(\'%m\', "created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 5], $builder->getBindings());
- }
-
-
- public function testWhereYearSqlite(): void
- {
- $builder = $this->getSQLiteBuilder();
- $builder->select('*')->from('users')->whereYear('created_at', '=', 2014);
- $this->assertEquals('select * from "users" where strftime(\'%Y\', "created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 2014], $builder->getBindings());
- }
-
-
- public function testWhereDaySqlServer(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('users')->whereDay('created_at', '=', 1);
- $this->assertEquals('select * from "users" where day("created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testWhereMonthSqlServer(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('users')->whereMonth('created_at', '=', 5);
- $this->assertEquals('select * from "users" where month("created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 5], $builder->getBindings());
- }
-
-
- public function testWhereYearSqlServer(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('users')->whereYear('created_at', '=', 2014);
- $this->assertEquals('select * from "users" where year("created_at") = ?', $builder->toSql());
- $this->assertEquals([0 => 2014], $builder->getBindings());
- }
-
-
- public function testWhereBetweens(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereBetween('id', [1, 2]);
- $this->assertEquals('select * from "users" where "id" between ? and ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereNotBetween('id', [1, 2]);
- $this->assertEquals('select * from "users" where "id" not between ? and ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
- }
-
-
- public function testBasicOrWheres(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhere('email', '=', 'foo');
- $this->assertEquals('select * from "users" where "id" = ? or "email" = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());
- }
-
-
- public function testRawWheres(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereRaw('id = ? or email = ?', [1, 'foo']);
- $this->assertEquals('select * from "users" where id = ? or email = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());
- }
-
-
- public function testRawOrWheres(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhereRaw('email = ?', ['foo']);
- $this->assertEquals('select * from "users" where "id" = ? or email = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());
- }
-
-
- public function testBasicWhereIns(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereIn('id', [1, 2, 3]);
- $this->assertEquals('select * from "users" where "id" in (?, ?, ?)', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2, 2 => 3], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhereIn('id', [1, 2, 3]);
- $this->assertEquals('select * from "users" where "id" = ? or "id" in (?, ?, ?)', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 1, 2 => 2, 3 => 3], $builder->getBindings());
- }
-
-
- public function testBasicWhereNotIns(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereNotIn('id', [1, 2, 3]);
- $this->assertEquals('select * from "users" where "id" not in (?, ?, ?)', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2, 2 => 3], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNotIn('id', [1, 2, 3]);
- $this->assertEquals('select * from "users" where "id" = ? or "id" not in (?, ?, ?)', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 1, 2 => 2, 3 => 3], $builder->getBindings());
- }
-
-
- public function testEmptyWhereIns(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereIn('id', []);
- $this->assertEquals('select * from "users" where 0 = 1', $builder->toSql());
- $this->assertEquals([], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhereIn('id', []);
- $this->assertEquals('select * from "users" where "id" = ? or 0 = 1', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testEmptyWhereNotIns(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereNotIn('id', []);
- $this->assertEquals('select * from "users" where 1 = 1', $builder->toSql());
- $this->assertEquals([], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNotIn('id', []);
- $this->assertEquals('select * from "users" where "id" = ? or 1 = 1', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testUnions(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2));
- $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
-
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->union($this->getMySqlBuilder()->select('*')->from('users')->where('id', '=', 2));
- $this->assertEquals('(select * from `users` where `id` = ?) union (select * from `users` where `id` = ?)', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
- }
-
-
- public function testUnionAlls(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 2));
- $this->assertEquals('select * from "users" where "id" = ? union all select * from "users" where "id" = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
- }
-
-
- public function testMultipleUnions(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2));
- $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 3));
- $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ? union select * from "users" where "id" = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2, 2 => 3], $builder->getBindings());
- }
-
-
- public function testMultipleUnionAlls(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 2));
- $builder->unionAll($this->getBuilder()->select('*')->from('users')->where('id', '=', 3));
- $this->assertEquals('select * from "users" where "id" = ? union all select * from "users" where "id" = ? union all select * from "users" where "id" = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2, 2 => 3], $builder->getBindings());
- }
-
-
- public function testUnionOrderBys(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->union($this->getBuilder()->select('*')->from('users')->where('id', '=', 2));
- $builder->orderBy('id', 'desc');
- $this->assertEquals('select * from "users" where "id" = ? union select * from "users" where "id" = ? order by "id" desc', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
- }
-
-
- public function testUnionLimitsAndOffsets(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users');
- $builder->union($this->getBuilder()->select('*')->from('dogs'));
- $builder->skip(5)->take(10);
- $this->assertEquals('select * from "users" union select * from "dogs" limit 10 offset 5', $builder->toSql());
- }
-
-
- public function testMySqlUnionOrderBys(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1);
- $builder->union($this->getMySqlBuilder()->select('*')->from('users')->where('id', '=', 2));
- $builder->orderBy('id', 'desc');
- $this->assertEquals('(select * from `users` where `id` = ?) union (select * from `users` where `id` = ?) order by `id` desc', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
- }
-
-
- public function testMySqlUnionLimitsAndOffsets(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users');
- $builder->union($this->getMySqlBuilder()->select('*')->from('dogs'));
- $builder->skip(5)->take(10);
- $this->assertEquals('(select * from `users`) union (select * from `dogs`) limit 10 offset 5', $builder->toSql());
- }
-
-
- public function testSubSelectWhereIns(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereIn('id', function($q)
- {
- $q->select('id')->from('users')->where('age', '>', 25)->take(3);
- });
- $this->assertEquals('select * from "users" where "id" in (select "id" from "users" where "age" > ? limit 3)', $builder->toSql());
- $this->assertEquals([25], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereNotIn('id', function($q)
- {
- $q->select('id')->from('users')->where('age', '>', 25)->take(3);
- });
- $this->assertEquals('select * from "users" where "id" not in (select "id" from "users" where "age" > ? limit 3)', $builder->toSql());
- $this->assertEquals([25], $builder->getBindings());
- }
-
-
- public function testBasicWhereNulls(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereNull('id');
- $this->assertEquals('select * from "users" where "id" is null', $builder->toSql());
- $this->assertEquals([], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '=', 1)->orWhereNull('id');
- $this->assertEquals('select * from "users" where "id" = ? or "id" is null', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testBasicWhereNotNulls(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->whereNotNull('id');
- $this->assertEquals('select * from "users" where "id" is not null', $builder->toSql());
- $this->assertEquals([], $builder->getBindings());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', '>', 1)->orWhereNotNull('id');
- $this->assertEquals('select * from "users" where "id" > ? or "id" is not null', $builder->toSql());
- $this->assertEquals([0 => 1], $builder->getBindings());
- }
-
-
- public function testGroupBys(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->groupBy('id', 'email');
- $this->assertEquals('select * from "users" group by "id", "email"', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->groupBy(['id', 'email']);
- $this->assertEquals('select * from "users" group by "id", "email"', $builder->toSql());
- }
-
-
- public function testOrderBys(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->orderBy('email')->orderBy('age', 'desc');
- $this->assertEquals('select * from "users" order by "email" asc, "age" desc', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->orderBy('email')->orderByRaw('"age" ? desc', ['foo']);
- $this->assertEquals('select * from "users" order by "email" asc, "age" ? desc', $builder->toSql());
- $this->assertEquals(['foo'], $builder->getBindings());
- }
-
-
- public function testHavings(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->having('email', '>', 1);
- $this->assertEquals('select * from "users" having "email" > ?', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')
- ->orHaving('email', '=', 'test@example.com')
- ->orHaving('email', '=', 'test2@example.com');
- $this->assertEquals('select * from "users" having "email" = ? or "email" = ?', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->groupBy('email')->having('email', '>', 1);
- $this->assertEquals('select * from "users" group by "email" having "email" > ?', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('email as foo_email')->from('users')->having('foo_email', '>', 1);
- $this->assertEquals('select "email" as "foo_email" from "users" having "foo_email" > ?', $builder->toSql());
- }
-
-
- public function testRawHavings(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->havingRaw('user_foo < user_bar');
- $this->assertEquals('select * from "users" having user_foo < user_bar', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->having('baz', '=', 1)->orHavingRaw('user_foo < user_bar');
- $this->assertEquals('select * from "users" having "baz" = ? or user_foo < user_bar', $builder->toSql());
- }
-
-
- public function testLimitsAndOffsets(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->offset(5)->limit(10);
- $this->assertEquals('select * from "users" limit 10 offset 5', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->skip(5)->take(10);
- $this->assertEquals('select * from "users" limit 10 offset 5', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->skip(-5)->take(10);
- $this->assertEquals('select * from "users" limit 10 offset 0', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->forPage(2, 15);
- $this->assertEquals('select * from "users" limit 15 offset 15', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->forPage(-2, 15);
- $this->assertEquals('select * from "users" limit 15 offset 0', $builder->toSql());
- }
-
-
- public function testWhereShortcut(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('id', 1)->orWhere('name', 'foo');
- $this->assertEquals('select * from "users" where "id" = ? or "name" = ?', $builder->toSql());
- $this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings());
- }
-
-
- public function testNestedWheres(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere(function($q)
- {
- $q->where('name', '=', 'bar')->where('age', '=', 25);
- });
- $this->assertEquals('select * from "users" where "email" = ? or ("name" = ? and "age" = ?)', $builder->toSql());
- $this->assertEquals([0 => 'foo', 1 => 'bar', 2 => 25], $builder->getBindings());
- }
-
-
- public function testFullSubSelects(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere('id', '=', function($q)
- {
- $q->select(new Raw('max(id)'))->from('users')->where('email', '=', 'bar');
- });
-
- $this->assertEquals('select * from "users" where "email" = ? or "id" = (select max(id) from "users" where "email" = ?)', $builder->toSql());
- $this->assertEquals([0 => 'foo', 1 => 'bar'], $builder->getBindings());
- }
-
-
- public function testWhereExists(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('orders')->whereExists(function($q)
- {
- $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'));
- });
- $this->assertEquals('select * from "orders" where exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('orders')->whereNotExists(function($q)
- {
- $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'));
- });
- $this->assertEquals('select * from "orders" where not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('orders')->where('id', '=', 1)->orWhereExists(function($q)
- {
- $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'));
- });
- $this->assertEquals('select * from "orders" where "id" = ? or exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('orders')->where('id', '=', 1)->orWhereNotExists(function($q)
- {
- $q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'));
- });
- $this->assertEquals('select * from "orders" where "id" = ? or not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
- }
-
-
- public function testBasicJoins(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->leftJoin('photos', 'users.id', '=', 'photos.id');
- $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" left join "photos" on "users"."id" = "photos"."id"', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->leftJoinWhere('photos', 'users.id', '=', 'bar')->joinWhere('photos', 'users.id', '=', 'foo');
- $this->assertEquals('select * from "users" left join "photos" on "users"."id" = ? inner join "photos" on "users"."id" = ?', $builder->toSql());
- $this->assertEquals(['bar', 'foo'], $builder->getBindings());
- }
-
-
- public function testComplexJoin(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->join('contacts', function($j)
- {
- $j->on('users.id', '=', 'contacts.id')->orOn('users.name', '=', 'contacts.name');
- });
- $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" or "users"."name" = "contacts"."name"', $builder->toSql());
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->join('contacts', function($j)
- {
- $j->where('users.id', '=', 'foo')->orWhere('users.name', '=', 'bar');
- });
- $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = ? or "users"."name" = ?', $builder->toSql());
- $this->assertEquals(['foo', 'bar'], $builder->getBindings());
-
- // Run the assertions again
- $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = ? or "users"."name" = ?', $builder->toSql());
- $this->assertEquals(['foo', 'bar'], $builder->getBindings());
- }
-
- public function testJoinWhereNull(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->join('contacts', function($j)
- {
- $j->on('users.id', '=', 'contacts.id')->whereNull('contacts.deleted_at');
- });
- $this->assertEquals('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id" and "contacts"."deleted_at" is null', $builder->toSql());
- }
-
- public function testRawExpressionsInSelect(): void
- {
- $builder = $this->getBuilder();
- $builder->select(new Raw('substr(foo, 6)'))->from('users');
- $this->assertEquals('select substr(foo, 6) from "users"', $builder->toSql());
- }
-
-
- public function testFindReturnsFirstResultByID(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1]
- )->andReturn([['foo' => 'bar']]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['foo' => 'bar']])->andReturnUsing(function($query, $results) { return $results; });
- $results = $builder->from('users')->find(1);
- $this->assertEquals(['foo' => 'bar'], $results);
- }
-
-
- public function testFirstMethodReturnsFirstResult(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1]
- )->andReturn([['foo' => 'bar']]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['foo' => 'bar']])->andReturnUsing(function($query, $results) { return $results; });
- $results = $builder->from('users')->where('id', '=', 1)->first();
- $this->assertEquals(['foo' => 'bar'], $results);
- }
-
-
- public function testListMethodsGetsArrayOfColumnValues(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->andReturn([['foo' => 'bar'], ['foo' => 'baz']]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['foo' => 'bar'], ['foo' => 'baz']]
- )->andReturnUsing(function($query, $results)
- {
- return $results;
- });
- $results = $builder->from('users')->where('id', '=', 1)->pluck('foo');
- $this->assertEquals(['bar', 'baz'], $results);
-
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->andReturn(
- [['id' => 1, 'foo' => 'bar'], ['id' => 10, 'foo' => 'baz']]
- );
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['id' => 1, 'foo' => 'bar'], ['id' => 10, 'foo' => 'baz']]
- )->andReturnUsing(function($query, $results)
- {
- return $results;
- });
- $results = $builder->from('users')->where('id', '=', 1)->pluck('foo', 'id');
- $this->assertEquals([1 => 'bar', 10 => 'baz'], $results);
- }
-
-
- public function testImplode(): void
- {
- // Test without glue.
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->andReturn([['foo' => 'bar'], ['foo' => 'baz']]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['foo' => 'bar'], ['foo' => 'baz']]
- )->andReturnUsing(function($query, $results)
- {
- return $results;
- });
- $results = $builder->from('users')->where('id', '=', 1)->implode('foo');
- $this->assertEquals('barbaz', $results);
-
- // Test with glue.
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->andReturn([['foo' => 'bar'], ['foo' => 'baz']]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['foo' => 'bar'], ['foo' => 'baz']]
- )->andReturnUsing(function($query, $results)
- {
- return $results;
- });
- $results = $builder->from('users')->where('id', '=', 1)->implode('foo', ',');
- $this->assertEquals('bar,baz', $results);
- }
-
-
- public function testPaginateCorrectlyCreatesPaginatorInstance(): void
- {
- $connection = m::mock(ConnectionInterface::class);
- $grammar = m::mock(Grammar::class);
- $processor = m::mock(Processor::class);
- $builder = $this->getMock(Builder::class, ['getPaginationCount', 'forPage', 'get'], [$connection, $grammar, $processor]
- );
- $paginator = m::mock(Factory::class);
- $paginator->shouldReceive('getCurrentPage')->once()->andReturn(1);
- $connection->shouldReceive('getPaginator')->once()->andReturn($paginator);
- $builder->expects($this->once())->method('forPage')->with($this->equalTo(1), $this->equalTo(15))->willReturn(
- $builder
- );
- $builder->expects($this->once())->method('get')->with($this->equalTo(['*']))->willReturn(['foo']);
- $builder->expects($this->once())->method('getPaginationCount')->willReturn(10);
- $paginator->shouldReceive('make')->once()->with(['foo'], 10, 15)->andReturn(['results']);
-
- $this->assertEquals(['results'], $builder->paginate(15, ['*']));
- }
-
-
- public function testPaginateCorrectlyCreatesPaginatorInstanceForGroupedQuery(): void
- {
- $connection = m::mock(ConnectionInterface::class);
- $grammar = m::mock(Grammar::class);
- $processor = m::mock(Processor::class);
- $builder = $this->getMock(Builder::class, ['get'], [$connection, $grammar, $processor]);
- $paginator = m::mock(Factory::class);
- $paginator->shouldReceive('getCurrentPage')->once()->andReturn(2);
- $connection->shouldReceive('getPaginator')->once()->andReturn($paginator);
- $builder->expects($this->once())->method('get')->with($this->equalTo(['*']))->willReturn(
- ['foo', 'bar', 'baz']
- );
- $paginator->shouldReceive('make')->once()->with(['baz'], 3, 2)->andReturn(['results']);
-
- $this->assertEquals(['results'], $builder->groupBy('foo')->paginate(2, ['*']));
- }
-
-
- public function testGetPaginationCountGetsResultCount(): void
- {
- unset($_SERVER['orders']);
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select count(*) as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($query, $results)
- {
- $_SERVER['orders'] = $query->orders;
- return $results;
- });
- $results = $builder->from('users')->orderBy('foo', 'desc')->getPaginationCount();
-
- $this->assertNull($_SERVER['orders']);
- unset($_SERVER['orders']);
-
- $this->assertEquals([0 => ['column' => 'foo', 'direction' => 'desc']], $builder->orders);
- $this->assertEquals(1, $results);
- }
-
-
- public function testQuickPaginateCorrectlyCreatesPaginatorInstance(): void
- {
- $connection = m::mock(ConnectionInterface::class);
- $grammar = m::mock(Grammar::class);
- $processor = m::mock(Processor::class);
- $builder = $this->getMock(Builder::class, ['skip', 'take', 'get'], [$connection, $grammar, $processor]);
- $paginator = m::mock(Factory::class);
- $paginator->shouldReceive('getCurrentPage')->once()->andReturn(1);
- $connection->shouldReceive('getPaginator')->once()->andReturn($paginator);
- $builder->expects($this->once())->method('skip')->with($this->equalTo(0))->willReturn($builder);
- $builder->expects($this->once())->method('take')->with($this->equalTo(16))->willReturn($builder);
- $builder->expects($this->once())->method('get')->with($this->equalTo(['*']))->willReturn(['foo']);
- $paginator->shouldReceive('make')->once()->with(['foo'], 15)->andReturn(['results']);
-
- $this->assertEquals(['results'], $builder->simplePaginate(15, ['*']));
- }
-
-
-public function testValueMethodReturnsSingleColumn(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select "foo" from "users" where "id" = ? limit 1', [1]
- )->andReturn([['foo' => 'bar']]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['foo' => 'bar']])->andReturn(
- [['foo' => 'bar']]
- );
- $results = $builder->from('users')->where('id', '=', 1)->value('foo');
- $this->assertEquals('bar', $results);
- }
-
-
- public function testAggregateFunctions(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select count(*) as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($builder, $results) { return $results; });
- $results = $builder->from('users')->count();
- $this->assertEquals(1, $results);
-
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select count(*) as aggregate from "users" limit 1', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($builder, $results) { return $results; });
- $results = $builder->from('users')->exists();
- $this->assertTrue($results);
-
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select max("id") as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($builder, $results) { return $results; });
- $results = $builder->from('users')->max('id');
- $this->assertEquals(1, $results);
-
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select min("id") as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($builder, $results) { return $results; });
- $results = $builder->from('users')->min('id');
- $this->assertEquals(1, $results);
-
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select sum("id") as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function($builder, $results) { return $results; });
- $results = $builder->from('users')->sum('id');
- $this->assertEquals(1, $results);
- }
-
-
- public function testAggregateResetFollowedByGet(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select count(*) as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getConnection()->shouldReceive('select')->once()->with('select sum("id") as aggregate from "users"', []
- )->andReturn([['aggregate' => 2]]);
- $builder->getConnection()->shouldReceive('select')->once()->with('select "column1", "column2" from "users"', [])->andReturn(
- [['column1' => 'foo', 'column2' => 'bar']]
- );
- $builder->getProcessor()->shouldReceive('processSelect')->andReturnUsing(function($builder, $results) { return $results; });
- $builder->from('users')->select('column1', 'column2');
- $count = $builder->count();
- $this->assertEquals(1, $count);
- $sum = $builder->sum('id');
- $this->assertEquals(2, $sum);
- $result = $builder->get();
- $this->assertEquals([['column1' => 'foo', 'column2' => 'bar']], $result);
- }
-
-
- public function testAggregateResetFollowedBySelectGet(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select count("column1") as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getConnection()->shouldReceive('select')->once()->with('select "column2", "column3" from "users"', [])->andReturn(
- [['column2' => 'foo', 'column3' => 'bar']]
- );
- $builder->getProcessor()->shouldReceive('processSelect')->andReturnUsing(function($builder, $results) { return $results; });
- $builder->from('users');
- $count = $builder->count('column1');
- $this->assertEquals(1, $count);
- $result = $builder->select('column2', 'column3')->get();
- $this->assertEquals([['column2' => 'foo', 'column3' => 'bar']], $result);
- }
-
-
- public function testAggregateResetFollowedByGetWithColumns(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('select')->once()->with('select count("column1") as aggregate from "users"', []
- )->andReturn([['aggregate' => 1]]);
- $builder->getConnection()->shouldReceive('select')->once()->with('select "column2", "column3" from "users"', [])->andReturn(
- [['column2' => 'foo', 'column3' => 'bar']]
- );
- $builder->getProcessor()->shouldReceive('processSelect')->andReturnUsing(function($builder, $results) { return $results; });
- $builder->from('users');
- $count = $builder->count('column1');
- $this->assertEquals(1, $count);
- $result = $builder->get(['column2', 'column3']);
- $this->assertEquals([['column2' => 'foo', 'column3' => 'bar']], $result);
- }
-
-
- public function testInsertMethod(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('insert')->once()->with('insert into "users" ("email") values (?)', ['foo']
- )->andReturn(true);
- $result = $builder->from('users')->insert(['email' => 'foo']);
- $this->assertTrue($result);
- }
-
-
- public function testSQLiteMultipleInserts(): void
- {
- $builder = $this->getSQLiteBuilder();
- $builder->getConnection()->shouldReceive('insert')->once()->with('insert into "users" ("email", "name") select ? as "email", ? as "name" union select ? as "email", ? as "name"', ['foo', 'taylor', 'bar', 'dayle']
- )->andReturn(true);
- $result = $builder->from('users')->insert(
- [['email' => 'foo', 'name' => 'taylor'], ['email' => 'bar', 'name' => 'dayle']]
- );
- $this->assertTrue($result);
- }
-
-
- public function testInsertGetIdMethod(): void
- {
- $builder = $this->getBuilder();
- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'insert into "users" ("email") values (?)', ['foo'], 'id')->andReturn(1);
- $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id');
- $this->assertEquals(1, $result);
- }
-
-
- public function testInsertGetIdMethodRemovesExpressions(): void
- {
- $builder = $this->getBuilder();
- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'insert into "users" ("email", "bar") values (?, bar)', ['foo'], 'id')->andReturn(1);
- $result = $builder->from('users')->insertGetId(
- ['email' => 'foo', 'bar' => new Illuminate\Database\Query\Expression('bar')], 'id');
- $this->assertEquals(1, $result);
- }
-
-
- public function testInsertMethodRespectsRawBindings(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('insert')->once()->with('insert into "users" ("email") values (CURRENT TIMESTAMP)', []
- )->andReturn(true);
- $result = $builder->from('users')->insert(['email' => new Raw('CURRENT TIMESTAMP')]);
- $this->assertTrue($result);
- }
-
-
- public function testUpdateMethod(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('update')->once()->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1]
- )->andReturn(1);
- $result = $builder->from('users')->where('id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']);
- $this->assertEquals(1, $result);
-
- $builder = $this->getMySqlBuilder();
- $builder->getConnection()->shouldReceive('update')->once()->with('update `users` set `email` = ?, `name` = ? where `id` = ? order by `foo` desc limit 5', ['foo', 'bar', 1]
- )->andReturn(1);
- $result = $builder->from('users')->where('id', '=', 1)->orderBy('foo', 'desc')->limit(5)->update(
- ['email' => 'foo', 'name' => 'bar']
- );
- $this->assertEquals(1, $result);
- }
-
-
- public function testUpdateMethodWithJoins(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('update')->once()->with('update "users" inner join "orders" on "users"."id" = "orders"."user_id" set "email" = ?, "name" = ? where "users"."id" = ?', ['foo', 'bar', 1]
- )->andReturn(1);
- $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(
- ['email' => 'foo', 'name' => 'bar']
- );
- $this->assertEquals(1, $result);
- }
-
-
- public function testUpdateMethodWithoutJoinsOnPostgres(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->getConnection()->shouldReceive('update')->once()->with('update "users" set "email" = ?, "name" = ? where "id" = ?', ['foo', 'bar', 1]
- )->andReturn(1);
- $result = $builder->from('users')->where('id', '=', 1)->update(['email' => 'foo', 'name' => 'bar']);
- $this->assertEquals(1, $result);
- }
-
-
- public function testUpdateMethodWithJoinsOnPostgres(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->getConnection()->shouldReceive('update')->once()->with('update "users" set "email" = ?, "name" = ? from "orders" where "users"."id" = ? and "users"."id" = "orders"."user_id"', ['foo', 'bar', 1]
- )->andReturn(1);
- $result = $builder->from('users')->join('orders', 'users.id', '=', 'orders.user_id')->where('users.id', '=', 1)->update(
- ['email' => 'foo', 'name' => 'bar']
- );
- $this->assertEquals(1, $result);
- }
-
-
- public function testUpdateMethodRespectsRaw(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('update')->once()->with('update "users" set "email" = foo, "name" = ? where "id" = ?', ['bar', 1]
- )->andReturn(1);
- $result = $builder->from('users')->where('id', '=', 1)->update(['email' => new Raw('foo'), 'name' => 'bar']);
- $this->assertEquals(1, $result);
- }
-
-
- public function testDeleteMethod(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('delete')->once()->with('delete from "users" where "email" = ?', ['foo']
- )->andReturn(1);
- $result = $builder->from('users')->where('email', '=', 'foo')->delete();
- $this->assertEquals(1, $result);
-
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('delete')->once()->with('delete from "users" where "id" = ?', [1])->andReturn(1);
- $result = $builder->from('users')->delete(1);
- $this->assertEquals(1, $result);
- }
-
-
- public function testDeleteWithJoinMethod(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->getConnection()->shouldReceive('delete')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `email` = ?', ['foo']
- )->andReturn(1);
- $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->where('email', '=', 'foo')->delete();
- $this->assertEquals(1, $result);
-
- $builder = $this->getMySqlBuilder();
- $builder->getConnection()->shouldReceive('delete')->once()->with('delete `users` from `users` inner join `contacts` on `users`.`id` = `contacts`.`id` where `id` = ?', [1]
- )->andReturn(1);
- $result = $builder->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->delete(1);
- $this->assertEquals(1, $result);
- }
-
-
- public function testTruncateMethod(): void
- {
- $builder = $this->getBuilder();
- $builder->getConnection()->shouldReceive('statement')->once()->with('truncate "users"', []);
- $builder->from('users')->truncate();
-
- $sqlite = new Illuminate\Database\Query\Grammars\SQLiteGrammar;
- $builder = $this->getBuilder();
- $builder->from('users');
- $this->assertEquals([
- 'delete from sqlite_sequence where name = ?' => ['users'],
- 'delete from "users"' => [],
- ], $sqlite->compileTruncate($builder));
- }
-
-
- public function testPostgresInsertGetId(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->getProcessor()->shouldReceive('processInsertGetId')->once()->with($builder, 'insert into "users" ("email") values (?) returning "id"', ['foo'], 'id')->andReturn(1);
- $result = $builder->from('users')->insertGetId(['email' => 'foo'], 'id');
- $this->assertEquals(1, $result);
- }
-
-
- public function testMySqlWrapping(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('users');
- $this->assertEquals('select * from `users`', $builder->toSql());
- }
-
-
- public function testSQLiteOrderBy(): void
- {
- $builder = $this->getSQLiteBuilder();
- $builder->select('*')->from('users')->orderBy('email', 'desc');
- $this->assertEquals('select * from "users" order by "email" desc', $builder->toSql());
- }
-
-
- public function testSqlServerLimitsAndOffsets(): void
- {
- $builder = $this->getSqlServerBuilder();
- $builder->select('*')->from('users')->take(10);
- $this->assertEquals('select top 10 * from [users]', $builder->toSql());
-
- $builder = $this->getSqlServerBuilder();
- $builder->select('*')->from('users')->skip(10);
- $this->assertEquals('select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num >= 11', $builder->toSql());
-
- $builder = $this->getSqlServerBuilder();
- $builder->select('*')->from('users')->skip(10)->take(10);
- $this->assertEquals('select * from (select *, row_number() over (order by (select 0)) as row_num from [users]) as temp_table where row_num between 11 and 20', $builder->toSql());
-
- $builder = $this->getSqlServerBuilder();
- $builder->select('*')->from('users')->skip(10)->take(10)->orderBy('email', 'desc');
- $this->assertEquals('select * from (select *, row_number() over (order by [email] desc) as row_num from [users]) as temp_table where row_num between 11 and 20', $builder->toSql());
- }
-
-
- public function testMergeWheresCanMergeWheresAndBindings(): void
- {
- $builder = $this->getBuilder();
- $builder->wheres = ['foo'];
- $builder->mergeWheres(['wheres'], [12 => 'foo', 13 => 'bar']);
- $this->assertEquals(['foo', 'wheres'], $builder->wheres);
- $this->assertEquals(['foo', 'bar'], $builder->getBindings());
- }
-
-
- public function testProvidingNullOrFalseAsSecondParameterBuildsCorrectly(): void
- {
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->where('foo', null);
- $this->assertEquals('select * from "users" where "foo" is null', $builder->toSql());
- }
-
-
- public function testDynamicWhere(): void
- {
- $method = 'whereFooBarAndBazOrQux';
- $parameters = ['corge', 'waldo', 'fred'];
- $builder = m::mock(Builder::class)->makePartial();
-
- $builder->shouldReceive('where')->with('foo_bar', '=', $parameters[0], 'and')->once()->andReturn($builder);
- $builder->shouldReceive('where')->with('baz', '=', $parameters[1], 'and')->once()->andReturn($builder);
- $builder->shouldReceive('where')->with('qux', '=', $parameters[2], 'or')->once()->andReturn($builder);
-
- $this->assertEquals($builder, $builder->dynamicWhere($method, $parameters));
- }
-
-
- public function testDynamicWhereIsNotGreedy(): void
- {
- $method = 'whereIosVersionAndAndroidVersionOrOrientation';
- $parameters = ['6.1', '4.2', 'Vertical'];
- $builder = m::mock(Builder::class)->makePartial();
-
- $builder->shouldReceive('where')->with('ios_version', '=', '6.1', 'and')->once()->andReturn($builder);
- $builder->shouldReceive('where')->with('android_version', '=', '4.2', 'and')->once()->andReturn($builder);
- $builder->shouldReceive('where')->with('orientation', '=', 'Vertical', 'or')->once()->andReturn($builder);
-
- $builder->dynamicWhere($method, $parameters);
- }
-
-
- public function testCallTriggersDynamicWhere(): void
- {
- $builder = $this->getBuilder();
-
- $this->assertEquals($builder, $builder->whereFooAndBar('baz', 'qux'));
- $this->assertCount(2, $builder->wheres);
- }
-
-
- public function testBuilderThrowsExpectedExceptionWithUndefinedMethod(): void
- {
- $this->expectException(BadMethodCallException::class);
- $builder = $this->getBuilder();
-
- $builder->noValidMethodHere();
- }
-
-
- public function setupCacheTestQuery($cache, $driver): Builder
- {
- $connection = m::mock(ConnectionInterface::class);
- $connection->shouldReceive('getName')->andReturn('connection_name');
- $connection->shouldReceive('getCacheManager')->once()->andReturn($cache);
- $cache->shouldReceive('driver')->once()->andReturn($driver);
- $grammar = new Illuminate\Database\Query\Grammars\Grammar;
- $processor = m::mock(Processor::class);
-
- $builder = $this->getMock(Builder::class, ['getFresh'], [$connection, $grammar, $processor]);
- $builder->expects($this->once())->method('getFresh')->with($this->equalTo(['*']))->willReturn(
- ['results']
- );
- return $builder->select('*')->from('users')->where('email', 'foo@bar.com');
- }
-
-
- public function testMySqlLock(): void
- {
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock();
- $this->assertEquals('select * from `foo` where `bar` = ? for update', $builder->toSql());
- $this->assertEquals(['baz'], $builder->getBindings());
-
- $builder = $this->getMySqlBuilder();
- $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false);
- $this->assertEquals('select * from `foo` where `bar` = ? lock in share mode', $builder->toSql());
- $this->assertEquals(['baz'], $builder->getBindings());
- }
-
-
- public function testPostgresLock(): void
- {
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock();
- $this->assertEquals('select * from "foo" where "bar" = ? for update', $builder->toSql());
- $this->assertEquals(['baz'], $builder->getBindings());
-
- $builder = $this->getPostgresBuilder();
- $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false);
- $this->assertEquals('select * from "foo" where "bar" = ? for share', $builder->toSql());
- $this->assertEquals(['baz'], $builder->getBindings());
- }
-
-
- public function testSqlServerLock(): void
- {
- $builder = $this->getSqlServerBuilder();
- $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock();
- $this->assertEquals('select * from [foo] with(rowlock,updlock,holdlock) where [bar] = ?', $builder->toSql());
- $this->assertEquals(['baz'], $builder->getBindings());
-
- $builder = $this->getSqlServerBuilder();
- $builder->select('*')->from('foo')->where('bar', '=', 'baz')->lock(false);
- $this->assertEquals('select * from [foo] with(rowlock,holdlock) where [bar] = ?', $builder->toSql());
- $this->assertEquals(['baz'], $builder->getBindings());
- }
-
-
- public function testBindingOrder(): void
- {
- $expectedSql = 'select * from "users" inner join "othertable" on "bar" = ? where "registered" = ? group by "city" having "population" > ? order by match ("foo") against(?)';
- $expectedBindings = ['foo', 1, 3, 'bar'];
-
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->join('othertable', function($join) { $join->where('bar', '=', 'foo'); })->where('registered', 1)->groupBy('city')->having('population', '>', 3)->orderByRaw('match ("foo") against(?)', ['bar']
- );
- $this->assertEquals($expectedSql, $builder->toSql());
- $this->assertEquals($expectedBindings, $builder->getBindings());
-
- // order of statements reversed
- $builder = $this->getBuilder();
- $builder->select('*')->from('users')->orderByRaw('match ("foo") against(?)', ['bar'])->having('population', '>', 3)->groupBy('city')->where('registered', 1)->join('othertable', function($join) { $join->where('bar', '=', 'foo'); });
- $this->assertEquals($expectedSql, $builder->toSql());
- $this->assertEquals($expectedBindings, $builder->getBindings());
- }
-
-
- public function testAddBindingWithArrayMergesBindings(): void
- {
- $builder = $this->getBuilder();
- $builder->addBinding(['foo', 'bar']);
- $builder->addBinding(['baz']);
- $this->assertEquals(['foo', 'bar', 'baz'], $builder->getBindings());
- }
-
-
- public function testAddBindingWithArrayMergesBindingsInCorrectOrder(): void
- {
- $builder = $this->getBuilder();
- $builder->addBinding(['bar', 'baz'], 'having');
- $builder->addBinding(['foo'], 'where');
- $this->assertEquals(['foo', 'bar', 'baz'], $builder->getBindings());
- }
-
-
- public function testMergeBuilders(): void
- {
- $builder = $this->getBuilder();
- $builder->addBinding(['foo', 'bar']);
- $otherBuilder = $this->getBuilder();
- $otherBuilder->addBinding(['baz']);
- $builder->mergeBindings($otherBuilder);
- $this->assertEquals(['foo', 'bar', 'baz'], $builder->getBindings());
- }
-
-
- public function testMergeBuildersBindingOrder(): void
- {
- $builder = $this->getBuilder();
- $builder->addBinding('foo', 'where');
- $builder->addBinding('baz', 'having');
- $otherBuilder = $this->getBuilder();
- $otherBuilder->addBinding('bar', 'where');
- $builder->mergeBindings($otherBuilder);
- $this->assertEquals(['foo', 'bar', 'baz'], $builder->getBindings());
- }
-
- public function testChunkByIdOnArrays(): void
- {
- $builder = $this->getMockQueryBuilder();
- $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
-
- $chunk1 = [['someIdField' => 1], ['someIdField' => 2]];
- $chunk2 = [['someIdField' => 10], ['someIdField' => 11]];
- $chunk3 = [];
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 11, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3);
-
- $callbackAssertor = m::mock(stdClass::class);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
- $callbackAssertor->shouldReceive('doSomething')->never()->with($chunk3);
-
- $builder->chunkById(2, function ($results) use ($callbackAssertor) {
- $callbackAssertor->doSomething($results);
- }, 'someIdField');
- }
-
- public function testChunkPaginatesUsingIdWithLastChunkComplete(): void
- {
- $builder = $this->getMockQueryBuilder();
- $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
-
- $chunk1 = [(object) ['someIdField' => 1], (object) ['someIdField' => 2]];
- $chunk2 = [(object) ['someIdField' => 10], (object) ['someIdField' => 11]];
- $chunk3 = [];
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 11, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('get')->times(3)->andReturn($chunk1, $chunk2, $chunk3);
-
- $callbackAssertor = m::mock(stdClass::class);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
- $callbackAssertor->shouldReceive('doSomething')->never()->with($chunk3);
-
- $builder->chunkById(2, function ($results) use ($callbackAssertor) {
- $callbackAssertor->doSomething($results);
- }, 'someIdField');
- }
-
- public function testChunkPaginatesUsingIdWithLastChunkPartial(): void
- {
- $builder = $this->getMockQueryBuilder();
- $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
-
- $chunk1 = [(object) ['someIdField' => 1], (object) ['someIdField' => 2]];
- $chunk2 = [(object) ['someIdField' => 10]];
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 2, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('get')->times(2)->andReturn($chunk1, $chunk2);
-
- $callbackAssertor = m::mock(stdClass::class);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk2);
-
- $builder->chunkById(2, function ($results) use ($callbackAssertor) {
- $callbackAssertor->doSomething($results);
- }, 'someIdField');
- }
-
- public function testChunkPaginatesUsingIdWithCountZero(): void
- {
- $builder = $this->getMockQueryBuilder();
- $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
-
- $chunk = [];
- $builder->shouldReceive('forPageAfterId')->once()->with(0, 0, 'someIdField')->andReturnSelf();
- $builder->shouldReceive('get')->times(1)->andReturn($chunk);
-
- $callbackAssertor = m::mock(stdClass::class);
- $callbackAssertor->shouldReceive('doSomething')->never();
-
- $builder->chunkById(0, function ($results) use ($callbackAssertor) {
- $callbackAssertor->doSomething($results);
- }, 'someIdField');
- }
-
- public function testChunkPaginatesUsingIdWithAlias(): void
- {
- $builder = $this->getMockQueryBuilder();
- $builder->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
-
- $chunk1 = [(object) ['table_id' => 1], (object) ['table_id' => 10]];
- $chunk2 = [];
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'table.id')->andReturnSelf();
- $builder->shouldReceive('forPageAfterId')->once()->with(2, 10, 'table.id')->andReturnSelf();
- $builder->shouldReceive('get')->times(2)->andReturn($chunk1, $chunk2);
-
- $callbackAssertor = m::mock(stdClass::class);
- $callbackAssertor->shouldReceive('doSomething')->once()->with($chunk1);
- $callbackAssertor->shouldReceive('doSomething')->never()->with($chunk2);
-
- $builder->chunkById(2, function ($results) use ($callbackAssertor) {
- $callbackAssertor->doSomething($results);
- }, 'table.id', 'table_id');
- }
-
- protected function getBuilder(): Builder
- {
- $grammar = new Illuminate\Database\Query\Grammars\Grammar;
- $processor = m::mock(Processor::class);
- return new Builder(m::mock(ConnectionInterface::class), $grammar, $processor);
- }
-
-
- protected function getPostgresBuilder(): Builder
- {
- $grammar = new Illuminate\Database\Query\Grammars\PostgresGrammar;
- $processor = m::mock(Processor::class);
- return new Builder(m::mock(ConnectionInterface::class), $grammar, $processor);
- }
-
-
- protected function getMySqlBuilder(): Builder
- {
- $grammar = new Illuminate\Database\Query\Grammars\MySqlGrammar;
- $processor = m::mock(Processor::class);
- return new Builder(m::mock(ConnectionInterface::class), $grammar, $processor);
- }
-
-
- protected function getSQLiteBuilder(): Builder
- {
- $grammar = new Illuminate\Database\Query\Grammars\SQLiteGrammar;
- $processor = m::mock(Processor::class);
- return new Builder(m::mock(ConnectionInterface::class), $grammar, $processor);
- }
-
-
- protected function getSqlServerBuilder(): Builder
- {
- $grammar = new Illuminate\Database\Query\Grammars\SqlServerGrammar;
- $processor = m::mock(Processor::class);
- return new Builder(m::mock(ConnectionInterface::class), $grammar, $processor);
- }
-
-
- protected function getMySqlBuilderWithProcessor(): Builder
- {
- $grammar = new Illuminate\Database\Query\Grammars\MySqlGrammar;
- $processor = new Illuminate\Database\Query\Processors\MySqlProcessor;
- return new Builder(m::mock(ConnectionInterface::class), $grammar, $processor);
- }
-
- /**
- * @return MockInterface|\Illuminate\Database\Query\Builder
- */
- protected function getMockQueryBuilder(): MockInterface|Builder
- {
- return m::mock(Builder::class, [
- m::mock(ConnectionInterface::class),
- new Grammar,
- m::mock(Processor::class),
- ])->makePartial()->shouldAllowMockingProtectedMethods();
- }
-
-}
diff --git a/tests/Database/DatabaseSQLiteProcessorTest.php b/tests/Database/DatabaseSQLiteProcessorTest.php
deleted file mode 100644
index 183ac2006..000000000
--- a/tests/Database/DatabaseSQLiteProcessorTest.php
+++ /dev/null
@@ -1,25 +0,0 @@
- 'id'], ['name' => 'name'], ['name' => 'email']];
- $expected = ['id', 'name', 'email'];
-
- $this->assertEquals($expected, $processor->processColumnListing($listing));
-
- // convert listing to objects to simulate PDO::FETCH_CLASS
- foreach($listing as &$row)
- {
- $row = (object) $row;
- }
-
- $this->assertEquals($expected, $processor->processColumnListing($listing));
- }
-
-}
diff --git a/tests/Database/DatabaseSQLiteSchemaGrammarTest.php b/tests/Database/DatabaseSQLiteSchemaGrammarTest.php
deleted file mode 100755
index bd346fb8c..000000000
--- a/tests/Database/DatabaseSQLiteSchemaGrammarTest.php
+++ /dev/null
@@ -1,419 +0,0 @@
-create();
- $blueprint->increments('id');
- $blueprint->string('email');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table "users" ("id" integer not null primary key autoincrement, "email" varchar not null)', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $blueprint->string('email');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(2, $statements);
- $expected = [
- 'alter table "users" add column "id" integer not null primary key autoincrement',
- 'alter table "users" add column "email" varchar not null',
- ];
- $this->assertEquals($expected, $statements);
- }
-
-
- public function testDropTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->drop();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table "users"', $statements[0]);
- }
-
-
- public function testDropTableIfExists()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIfExists();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table if exists "users"', $statements[0]);
- }
-
-
- public function testDropUnique()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropUnique('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop index foo', $statements[0]);
- }
-
-
- public function testDropIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIndex('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop index foo', $statements[0]);
- }
-
-
- public function testRenameTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rename('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" rename to "foo"', $statements[0]);
- }
-
-
- public function testAddingPrimaryKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->create();
- $blueprint->string('foo')->primary();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table "users" ("foo" varchar not null, primary key ("foo"))', $statements[0]);
- }
-
-
- public function testAddingForeignKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->create();
- $blueprint->string('foo')->primary();
- $blueprint->string('order_id');
- $blueprint->foreign('order_id')->references('id')->on('orders');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table "users" ("foo" varchar not null, "order_id" varchar not null, foreign key("order_id") references "orders"("id"), primary key ("foo"))', $statements[0]);
- }
-
-
- public function testAddingUniqueKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->unique('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create unique index bar on "users" ("foo")', $statements[0]);
- }
-
-
- public function testAddingIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->index(['foo', 'bar'], 'baz');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create index baz on "users" ("foo", "bar")', $statements[0]);
- }
-
-
- public function testAddingIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]);
- }
-
-
- public function testAddingBigIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigIncrements('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]);
- }
-
-
- public function testAddingString()
- {
- $blueprint = new Blueprint('users');
- $blueprint->string('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100)->nullable()->default('bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar null default \'bar\'', $statements[0]);
- }
-
-
- public function testAddingText()
- {
- $blueprint = new Blueprint('users');
- $blueprint->text('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]);
- }
-
-
- public function testAddingBigInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
- }
-
-
- public function testAddingInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
- }
-
-
- public function testAddingMediumInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->mediumInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
- }
-
-
- public function testAddingTinyInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->tinyInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
- }
-
-
- public function testAddingSmallInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->smallInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
- }
-
-
- public function testAddingFloat()
- {
- $blueprint = new Blueprint('users');
- $blueprint->float('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]);
- }
-
-
- public function testAddingDouble()
- {
- $blueprint = new Blueprint('users');
- $blueprint->double('foo', 15, 8);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]);
- }
-
-
- public function testAddingDecimal()
- {
- $blueprint = new Blueprint('users');
- $blueprint->decimal('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]);
- }
-
-
- public function testAddingBoolean()
- {
- $blueprint = new Blueprint('users');
- $blueprint->boolean('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" tinyint not null', $statements[0]);
- }
-
-
- public function testAddingEnum()
- {
- $blueprint = new Blueprint('users');
- $blueprint->enum('foo', ['bar', 'baz']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
- }
-
-
- public function testAddingDate()
- {
- $blueprint = new Blueprint('users');
- $blueprint->date('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" date not null', $statements[0]);
- }
-
-
- public function testAddingDateTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dateTime('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]);
- }
-
-
- public function testAddingTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->time('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" time not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamp()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamp('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(2, $statements);
- $expected = [
- 'alter table "users" add column "created_at" datetime not null',
- 'alter table "users" add column "updated_at" datetime not null',
- ];
- $this->assertEquals($expected, $statements);
- }
-
-
- public function testAddingRememberToken()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rememberToken();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "remember_token" varchar null', $statements[0]);
- }
-
-
- public function testAddingBinary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->binary('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add column "foo" blob not null', $statements[0]);
- }
-
-
- protected function getConnection()
- {
- return m::mock(Connection::class);
- }
-
-
- public function getGrammar()
- {
- return new Illuminate\Database\Schema\Grammars\SQLiteGrammar;
- }
-
-}
diff --git a/tests/Database/DatabaseSchemaBlueprintTest.php b/tests/Database/DatabaseSchemaBlueprintTest.php
deleted file mode 100755
index 93e741a94..000000000
--- a/tests/Database/DatabaseSchemaBlueprintTest.php
+++ /dev/null
@@ -1,61 +0,0 @@
-shouldReceive('statement')->once()->with('foo');
- $conn->shouldReceive('statement')->once()->with('bar');
- $grammar = m::mock(MySqlGrammar::class);
- $blueprint = $this->getMock(Blueprint::class, ['toSql'], ['users']);
- $blueprint->expects($this->once())->method('toSql')->with($this->equalTo($conn), $this->equalTo($grammar))->willReturn(
- ['foo', 'bar']
- );
-
- $blueprint->build($conn, $grammar);
- }
-
-
- public function testIndexDefaultNames()
- {
- $blueprint = new Blueprint('users');
- $blueprint->unique(['foo', 'bar']);
- $commands = $blueprint->getCommands();
- $this->assertEquals('users_foo_bar_unique', $commands[0]->index);
-
- $blueprint = new Blueprint('users');
- $blueprint->index('foo');
- $commands = $blueprint->getCommands();
- $this->assertEquals('users_foo_index', $commands[0]->index);
- }
-
-
- public function testDropIndexDefaultNames()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropUnique(['foo', 'bar']);
- $commands = $blueprint->getCommands();
- $this->assertEquals('users_foo_bar_unique', $commands[0]->index);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropIndex(['foo']);
- $commands = $blueprint->getCommands();
- $this->assertEquals('users_foo_index', $commands[0]->index);
- }
-
-
-}
diff --git a/tests/Database/DatabaseSchemaBuilderTest.php b/tests/Database/DatabaseSchemaBuilderTest.php
deleted file mode 100755
index 6d86feabb..000000000
--- a/tests/Database/DatabaseSchemaBuilderTest.php
+++ /dev/null
@@ -1,30 +0,0 @@
-shouldReceive('getSchemaGrammar')->andReturn($grammar);
- $builder = new Builder($connection);
- $grammar->shouldReceive('compileTableExists')->once()->andReturn('sql');
- $connection->shouldReceive('getTablePrefix')->once()->andReturn('prefix_');
- $connection->shouldReceive('select')->once()->with('sql', ['prefix_table'])->andReturn(['prefix_table']);
-
- $this->assertTrue($builder->hasTable('table'));
- }
-
-}
diff --git a/tests/Database/DatabaseSeederTest.php b/tests/Database/DatabaseSeederTest.php
deleted file mode 100755
index e50ccff84..000000000
--- a/tests/Database/DatabaseSeederTest.php
+++ /dev/null
@@ -1,52 +0,0 @@
-setContainer($container = m::mock(Container::class));
- $output = m::mock(OutputInterface::class);
- $output->shouldReceive('writeln')->once()->andReturn('foo');
- $command = m::mock(Command::class);
- $command->shouldReceive('getOutput')->once()->andReturn($output);
- $seeder->setCommand($command);
- $container->shouldReceive('make')->once()->with('ClassName')->andReturn($child = m::mock('StdClass'));
- $child->shouldReceive('setContainer')->once()->with($container)->andReturn($child);
- $child->shouldReceive('setCommand')->once()->with($command)->andReturn($child);
- $child->shouldReceive('run')->once();
-
- $seeder->call('ClassName');
- }
-
-
- public function testSetContainer()
- {
- $seeder = new Seeder;
- $container = m::mock(Container::class);
- $this->assertEquals($seeder->setContainer($container), $seeder);
- }
-
-
- public function testSetCommand()
- {
- $seeder = new Seeder;
- $command = m::mock(Command::class);
- $this->assertEquals($seeder->setCommand($command), $seeder);
- }
-
-}
diff --git a/tests/Database/DatabaseSoftDeletingScopeTest.php b/tests/Database/DatabaseSoftDeletingScopeTest.php
deleted file mode 100644
index 144cef105..000000000
--- a/tests/Database/DatabaseSoftDeletingScopeTest.php
+++ /dev/null
@@ -1,122 +0,0 @@
-shouldReceive('getModel')->once()->andReturn($model = m::mock('StdClass'));
- $model->shouldReceive('getQualifiedDeletedAtColumn')->once()->andReturn('table.deleted_at');
- $builder->shouldReceive('whereNull')->once()->with('table.deleted_at');
- $scope->shouldReceive('extend')->once();
-
- $scope->apply($builder);
- }
-
-
- public function testScopeCanRemoveDeletedAtConstraints()
- {
- $scope = new Illuminate\Database\Eloquent\SoftDeletingScope;
- $builder = m::mock(Builder::class);
- $builder->shouldReceive('getModel')->andReturn($model = m::mock('StdClass'));
- $model->shouldReceive('getQualifiedDeletedAtColumn')->andReturn('table.deleted_at');
- $builder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass'));
- $query->wheres = [['type' => 'Null', 'column' => 'foo'], ['type' => 'Null', 'column' => 'table.deleted_at']];
- $scope->remove($builder);
-
- $this->assertEquals($query->wheres, [['type' => 'Null', 'column' => 'foo']]);
- }
-
-
- public function testForceDeleteExtension()
- {
- $builder = m::mock(Builder::class);
- $builder->makePartial();
- $scope = new Illuminate\Database\Eloquent\SoftDeletingScope;
- $scope->extend($builder);
- $callback = $builder->getMacro('forceDelete');
- $givenBuilder = m::mock(Builder::class);
- $givenBuilder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass'));
- $query->shouldReceive('delete')->once();
-
- $callback($givenBuilder);
- }
-
-
- public function testRestoreExtension()
- {
- $builder = m::mock(Builder::class);
- $builder->makePartial();
- $scope = new Illuminate\Database\Eloquent\SoftDeletingScope;
- $scope->extend($builder);
- $callback = $builder->getMacro('restore');
- $givenBuilder = m::mock(Builder::class);
- $givenBuilder->shouldReceive('withTrashed')->once();
- $givenBuilder->shouldReceive('getModel')->once()->andReturn($model = m::mock('StdClass'));
- $model->shouldReceive('getDeletedAtColumn')->once()->andReturn('deleted_at');
- $givenBuilder->shouldReceive('update')->once()->with(['deleted_at' => null]);
-
- $callback($givenBuilder);
- }
-
-
- public function testWithTrashedExtension()
- {
- $builder = m::mock(Builder::class);
- $builder->makePartial();
- $scope = m::mock('Illuminate\Database\Eloquent\SoftDeletingScope[remove]');
- $scope->extend($builder);
- $callback = $builder->getMacro('withTrashed');
- $givenBuilder = m::mock(Builder::class);
- $scope->shouldReceive('remove')->once()->with($givenBuilder);
- $result = $callback($givenBuilder);
-
- $this->assertEquals($givenBuilder, $result);
- }
-
-
- public function testOnlyTrashedExtension()
- {
- $builder = m::mock(Builder::class);
- $builder->makePartial();
- $scope = m::mock('Illuminate\Database\Eloquent\SoftDeletingScope[remove]');
- $scope->extend($builder);
- $callback = $builder->getMacro('onlyTrashed');
- $givenBuilder = m::mock(Builder::class);
- $scope->shouldReceive('remove')->once()->with($givenBuilder);
- $givenBuilder->shouldReceive('getQuery')->andReturn($query = m::mock('StdClass'));
- $givenBuilder->shouldReceive('getModel')->andReturn($model = m::mock('StdClass'));
- $model->shouldReceive('getQualifiedDeletedAtColumn')->andReturn('table.deleted_at');
- $query->shouldReceive('whereNotNull')->once()->with('table.deleted_at');
- $result = $callback($givenBuilder);
-
- $this->assertEquals($givenBuilder, $result);
- }
-
-}
-
-
-class DatabaseSoftDeletingScopeBuilderStub {
- public $extensions = [];
- public $onDelete;
- public function extend($name, $callback)
- {
- $this->extensions[$name] = $callback;
- }
- public function onDelete($callback)
- {
- $this->onDelete = $callback;
- }
-}
diff --git a/tests/Database/DatabaseSoftDeletingTraitTest.php b/tests/Database/DatabaseSoftDeletingTraitTest.php
deleted file mode 100644
index f3ce3e492..000000000
--- a/tests/Database/DatabaseSoftDeletingTraitTest.php
+++ /dev/null
@@ -1,91 +0,0 @@
-makePartial();
- $model->shouldReceive('newQuery')->andReturn($query = m::mock('StdClass'));
- $query->shouldReceive('where')->once()->with('id', 1)->andReturn($query);
- $query->shouldReceive('update')->once()->with(['deleted_at' => 'date-time']);
- $model->delete();
-
- $this->assertInstanceOf(Carbon::class, $model->deleted_at);
- }
-
-
- public function testRestore()
- {
- $model = m::mock('DatabaseSoftDeletingTraitStub');
- $model->makePartial();
- $model->shouldReceive('fireModelEvent')->with('restoring')->andReturn(true);
- $model->shouldReceive('save')->once();
- $model->shouldReceive('fireModelEvent')->with('restored', false)->andReturn(true);
-
- $model->restore();
-
- $this->assertNull($model->deleted_at);
- }
-
-
- public function testRestoreCancel()
- {
- $model = m::mock('DatabaseSoftDeletingTraitStub');
- $model->makePartial();
- $model->shouldReceive('fireModelEvent')->with('restoring')->andReturn(false);
- $model->shouldReceive('save')->never();
-
- $this->assertFalse($model->restore());
- }
-
-}
-
-
-class DatabaseSoftDeletingTraitStub {
- use Illuminate\Database\Eloquent\SoftDeletes;
- public $deleted_at;
- public function newQuery()
- {
- //
- }
- public function getKey()
- {
- return 1;
- }
- public function getKeyName()
- {
- return 'id';
- }
- public function save()
- {
- //
- }
- public function delete()
- {
- return $this->performDeleteOnModel();
- }
- public function fireModelEvent()
- {
- //
- }
- public function freshTimestamp()
- {
- return Carbon::now();
- }
- public function fromDateTime()
- {
- return 'date-time';
- }
-}
diff --git a/tests/Database/DatabaseSqlServerSchemaGrammarTest.php b/tests/Database/DatabaseSqlServerSchemaGrammarTest.php
deleted file mode 100755
index f6e01fa90..000000000
--- a/tests/Database/DatabaseSqlServerSchemaGrammarTest.php
+++ /dev/null
@@ -1,443 +0,0 @@
-create();
- $blueprint->increments('id');
- $blueprint->string('email');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create table "users" ("id" int identity primary key not null, "email" nvarchar(255) not null)', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $blueprint->string('email');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "id" int identity primary key not null, "email" nvarchar(255) not null', $statements[0]);
- }
-
-
- public function testDropTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->drop();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop table "users"', $statements[0]);
- }
-
-
- public function testDropColumn()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "foo"', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn(['foo', 'bar']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "foo", "bar"', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->dropColumn('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "foo", "bar"', $statements[0]);
- }
-
-
- public function testDropPrimary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropPrimary('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop constraint foo', $statements[0]);
- }
-
-
- public function testDropUnique()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropUnique('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop index foo on "users"', $statements[0]);
- }
-
-
- public function testDropIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropIndex('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('drop index foo on "users"', $statements[0]);
- }
-
-
- public function testDropForeign()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropForeign('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop constraint foo', $statements[0]);
- }
-
-
- public function testDropTimestamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dropTimestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" drop column "created_at", "updated_at"', $statements[0]);
- }
-
-
- public function testRenameTable()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rename('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('sp_rename "users", "foo"', $statements[0]);
- }
-
-
- public function testAddingPrimaryKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->primary('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add constraint bar primary key ("foo")', $statements[0]);
- }
-
-
- public function testAddingUniqueKey()
- {
- $blueprint = new Blueprint('users');
- $blueprint->unique('foo', 'bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create unique index bar on "users" ("foo")', $statements[0]);
- }
-
-
- public function testAddingIndex()
- {
- $blueprint = new Blueprint('users');
- $blueprint->index(['foo', 'bar'], 'baz');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('create index baz on "users" ("foo", "bar")', $statements[0]);
- }
-
-
- public function testAddingIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->increments('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "id" int identity primary key not null', $statements[0]);
- }
-
-
- public function testAddingBigIncrementingID()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigIncrements('id');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "id" bigint identity primary key not null', $statements[0]);
- }
-
-
- public function testAddingString()
- {
- $blueprint = new Blueprint('users');
- $blueprint->string('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" nvarchar(255) not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" nvarchar(100) not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->string('foo', 100)->nullable()->default('bar');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" nvarchar(100) null default \'bar\'', $statements[0]);
- }
-
-
- public function testAddingText()
- {
- $blueprint = new Blueprint('users');
- $blueprint->text('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" nvarchar(max) not null', $statements[0]);
- }
-
-
- public function testAddingBigInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" bigint not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->bigInteger('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" bigint identity primary key not null', $statements[0]);
- }
-
-
- public function testAddingInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" int not null', $statements[0]);
-
- $blueprint = new Blueprint('users');
- $blueprint->integer('foo', true);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" int identity primary key not null', $statements[0]);
- }
-
-
- public function testAddingMediumInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->mediumInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" int not null', $statements[0]);
- }
-
-
- public function testAddingTinyInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->tinyInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" tinyint not null', $statements[0]);
- }
-
-
- public function testAddingSmallInteger()
- {
- $blueprint = new Blueprint('users');
- $blueprint->smallInteger('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" smallint not null', $statements[0]);
- }
-
-
- public function testAddingFloat()
- {
- $blueprint = new Blueprint('users');
- $blueprint->float('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" float not null', $statements[0]);
- }
-
-
- public function testAddingDouble()
- {
- $blueprint = new Blueprint('users');
- $blueprint->double('foo', 15, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" float not null', $statements[0]);
- }
-
-
- public function testAddingDecimal()
- {
- $blueprint = new Blueprint('users');
- $blueprint->decimal('foo', 5, 2);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" decimal(5, 2) not null', $statements[0]);
- }
-
-
- public function testAddingBoolean()
- {
- $blueprint = new Blueprint('users');
- $blueprint->boolean('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" bit not null', $statements[0]);
- }
-
-
- public function testAddingEnum()
- {
- $blueprint = new Blueprint('users');
- $blueprint->enum('foo', ['bar', 'baz']);
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" nvarchar(255) not null', $statements[0]);
- }
-
-
- public function testAddingDate()
- {
- $blueprint = new Blueprint('users');
- $blueprint->date('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" date not null', $statements[0]);
- }
-
-
- public function testAddingDateTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->dateTime('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" datetime not null', $statements[0]);
- }
-
-
- public function testAddingTime()
- {
- $blueprint = new Blueprint('users');
- $blueprint->time('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" time not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamp()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamp('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" datetime not null', $statements[0]);
- }
-
-
- public function testAddingTimeStamps()
- {
- $blueprint = new Blueprint('users');
- $blueprint->timestamps();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "created_at" datetime not null, "updated_at" datetime not null', $statements[0]);
- }
-
-
- public function testAddingRememberToken()
- {
- $blueprint = new Blueprint('users');
- $blueprint->rememberToken();
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "remember_token" nvarchar(100) null', $statements[0]);
- }
-
-
- public function testAddingBinary()
- {
- $blueprint = new Blueprint('users');
- $blueprint->binary('foo');
- $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
-
- $this->assertCount(1, $statements);
- $this->assertEquals('alter table "users" add "foo" varbinary(max) not null', $statements[0]);
- }
-
-
- protected function getConnection()
- {
- return m::mock(Connection::class);
- }
-
-
- public function getGrammar()
- {
- return new Illuminate\Database\Schema\Grammars\SqlServerGrammar;
- }
-
-}
diff --git a/tests/Database/stubs/EloquentModelNamespacedStub.php b/tests/Database/stubs/EloquentModelNamespacedStub.php
deleted file mode 100755
index 39872488c..000000000
--- a/tests/Database/stubs/EloquentModelNamespacedStub.php
+++ /dev/null
@@ -1,7 +0,0 @@
-getEncrypter();
- $this->assertNotEquals('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', $e->encrypt('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'));
- $encrypted = $e->encrypt('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
- $this->assertEquals('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', $e->decrypt($encrypted));
- }
-
-
- public function testEncryptionWithCustomCipher()
- {
- $e = $this->getEncrypter();
- $this->assertNotEquals('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', $e->encrypt('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'));
- $encrypted = $e->encrypt('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
- $this->assertEquals('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', $e->decrypt($encrypted));
- }
-
- public function testExceptionThrownWhenPayloadIsInvalid()
- {
- $this->expectException(Illuminate\Contracts\Encryption\DecryptException::class);
- $this->expectExceptionMessage("The payload is invalid.");
- $e = $this->getEncrypter();
- $payload = $e->encrypt('foo');
- $payload = str_shuffle((string) $payload);
- $e->decrypt($payload);
- }
-
-
- protected function getEncrypter()
- {
- return new Encrypter(str_repeat('a', 32));
- }
-
-}
diff --git a/tests/Events/EventsDispatcherTest.php b/tests/Events/EventsDispatcherTest.php
deleted file mode 100755
index c98c29162..000000000
--- a/tests/Events/EventsDispatcherTest.php
+++ /dev/null
@@ -1,133 +0,0 @@
-listen(
- 'foo',
- function ($foo) {
- $_SERVER['__event.test'] = $foo;
- }
- );
- $d->fire('foo', ['bar']);
- $this->assertEquals('bar', $_SERVER['__event.test']);
- }
-
-
- public function testDispatchIsCanonicalAndFireDelegates()
- {
- $d = new Dispatcher;
- $d->listen('foo', function ($x) { return 'heard:'.$x; });
-
- $this->assertSame(['heard:bar'], $d->dispatch('foo', ['bar']));
- // fire() is the L4.2 alias — identical behaviour, removed at L13 swap
- $this->assertSame($d->dispatch('foo', ['bar']), $d->fire('foo', ['bar']));
- // halt returns the first non-null response
- $this->assertSame('heard:bar', $d->dispatch('foo', ['bar'], true));
- }
-
-
- public function testContainerResolutionOfEventHandlers()
- {
- $d = new Dispatcher($container = m::mock(Container::class));
- $container->shouldReceive('make')->once()->with('FooHandler')->andReturn($handler = m::mock('StdClass'));
- $handler->shouldReceive('onFooEvent')->once()->with('foo', 'bar');
- $d->listen('foo', 'FooHandler@onFooEvent');
- $d->fire('foo', ['foo', 'bar']);
- }
-
-
- public function testContainerResolutionOfEventHandlersWithDefaultMethods()
- {
- $d = new Dispatcher($container = m::mock(Container::class));
- $container->shouldReceive('make')->once()->with('FooHandler')->andReturn($handler = m::mock('StdClass'));
- $handler->shouldReceive('handle')->once()->with('foo', 'bar');
- $d->listen('foo', 'FooHandler');
- $d->fire('foo', ['foo', 'bar']);
- }
-
-
- public function testQueuedEventsAreFired()
- {
- unset($_SERVER['__event.test']);
- $d = new Dispatcher;
- $d->queue('update', ['name' => 'taylor']);
- $d->listen('update', function($name)
- {
- $_SERVER['__event.test'] = $name;
- });
-
- $this->assertFalse(isset($_SERVER['__event.test']));
- $d->flush('update');
- $this->assertEquals('taylor', $_SERVER['__event.test']);
- }
-
-
- public function testQueuedEventsCanBeForgotten()
- {
- $_SERVER['__event.test'] = 'unset';
- $d = new Dispatcher;
- $d->queue('update', ['name' => 'taylor']);
- $d->listen('update', function($name)
- {
- $_SERVER['__event.test'] = $name;
- });
-
- $d->forgetQueued();
- $d->flush('update');
- $this->assertEquals('unset', $_SERVER['__event.test']);
- }
-
-
- public function testWildcardListeners()
- {
- unset($_SERVER['__event.test']);
- $d = new Dispatcher;
- $d->listen('foo.bar', function() { $_SERVER['__event.test'] = 'regular'; });
- $d->listen('foo.*', function() { $_SERVER['__event.test'] = 'wildcard'; });
- $d->listen('bar.*', function() { $_SERVER['__event.test'] = 'nope'; });
- $d->fire('foo.bar');
-
- $this->assertEquals('wildcard', $_SERVER['__event.test']);
- }
-
-
- public function testListenersCanBeRemoved()
- {
- unset($_SERVER['__event.test']);
- $d = new Dispatcher;
- $d->listen('foo', function() { $_SERVER['__event.test'] = 'foo'; });
- $d->forget('foo');
- $d->fire('foo');
-
- $this->assertFalse(isset($_SERVER['__event.test']));
- }
-
-
- public function testFiringReturnsCurrentlyFiredEvent()
- {
- unset($_SERVER['__event.test']);
- $d = new Dispatcher;
- $d->listen('foo', function() use ($d) { $_SERVER['__event.test'] = $d->firing(); $d->fire('bar'); });
- $d->listen('bar', function() use ($d) { $_SERVER['__event.test'] = $d->firing(); });
- $d->fire('foo');
-
- $this->assertEquals('bar', $_SERVER['__event.test']);
- }
-
-}
diff --git a/tests/Filesystem/FilesystemTest.php b/tests/Filesystem/FilesystemTest.php
deleted file mode 100755
index 4e671f521..000000000
--- a/tests/Filesystem/FilesystemTest.php
+++ /dev/null
@@ -1,130 +0,0 @@
-assertEquals('Hello World', $files->get(__DIR__.'/file.txt'));
- @unlink(__DIR__.'/file.txt');
- }
-
-
- public function testPutStoresFiles()
- {
- $files = new Filesystem;
- $files->put(__DIR__.'/file.txt', 'Hello World');
- $this->assertEquals('Hello World', file_get_contents(__DIR__.'/file.txt'));
- @unlink(__DIR__.'/file.txt');
- }
-
-
- public function testDeleteRemovesFiles()
- {
- file_put_contents(__DIR__.'/file.txt', 'Hello World');
- $files = new Filesystem;
- $files->delete(__DIR__.'/file.txt');
- $this->assertFileDoesNotExist(__DIR__ . '/file.txt');
- @unlink(__DIR__.'/file.txt');
- }
-
-
- public function testPrependExistingFiles()
- {
- $files = new Filesystem;
- $files->put(__DIR__.'/file.txt', 'World');
- $files->prepend(__DIR__.'/file.txt', 'Hello ');
- $this->assertEquals('Hello World', file_get_contents(__DIR__.'/file.txt'));
- @unlink(__DIR__.'/file.txt');
- }
-
-
- public function testPrependNewFiles()
- {
- $files = new Filesystem;
- $files->prepend(__DIR__.'/file.txt', 'Hello World');
- $this->assertEquals('Hello World', file_get_contents(__DIR__.'/file.txt'));
- @unlink(__DIR__.'/file.txt');
- }
-
-
- public function testDeleteDirectory()
- {
- mkdir(__DIR__.'/foo');
- file_put_contents(__DIR__.'/foo/file.txt', 'Hello World');
- $files = new Filesystem;
- $files->deleteDirectory(__DIR__.'/foo');
- $this->assertDirectoryDoesNotExist(__DIR__ . '/foo');
- $this->assertFileDoesNotExist(__DIR__ . '/foo/file.txt');
- }
-
-
- public function testCleanDirectory()
- {
- mkdir(__DIR__.'/foo');
- file_put_contents(__DIR__.'/foo/file.txt', 'Hello World');
- $files = new Filesystem;
- $files->cleanDirectory(__DIR__.'/foo');
- $this->assertDirectoryExists(__DIR__ . '/foo');
- $this->assertFileDoesNotExist(__DIR__ . '/foo/file.txt');
- @rmdir(__DIR__.'/foo');
- }
-
-
- public function testFilesMethod()
- {
- mkdir(__DIR__.'/foo');
- file_put_contents(__DIR__.'/foo/1.txt', '1');
- file_put_contents(__DIR__.'/foo/2.txt', '2');
- mkdir(__DIR__.'/foo/bar');
- $files = new Filesystem;
- $this->assertEquals([__DIR__.'/foo/1.txt', __DIR__.'/foo/2.txt'], $files->files(__DIR__.'/foo'));
- unset($files);
- @unlink(__DIR__.'/foo/1.txt');
- @unlink(__DIR__.'/foo/2.txt');
- @rmdir(__DIR__.'/foo/bar');
- @rmdir(__DIR__.'/foo');
- }
-
-
- public function testCopyDirectoryReturnsFalseIfSourceIsntDirectory()
- {
- $files = new Filesystem;
- $this->assertFalse($files->copyDirectory(__DIR__.'/foo/bar/baz/breeze/boom', __DIR__));
- }
-
-
- public function testCopyDirectoryMovesEntireDirectory()
- {
- mkdir(__DIR__.'/tmp', 0777, true);
- file_put_contents(__DIR__.'/tmp/foo.txt', '');
- file_put_contents(__DIR__.'/tmp/bar.txt', '');
- mkdir(__DIR__.'/tmp/nested', 0777, true);
- file_put_contents(__DIR__.'/tmp/nested/baz.txt', '');
-
- $files = new Filesystem;
- $files->copyDirectory(__DIR__.'/tmp', __DIR__.'/tmp2');
- $this->assertDirectoryExists(__DIR__ . '/tmp2');
- $this->assertFileExists(__DIR__ . '/tmp2/foo.txt');
- $this->assertFileExists(__DIR__ . '/tmp2/bar.txt');
- $this->assertDirectoryExists(__DIR__ . '/tmp2/nested');
- $this->assertFileExists(__DIR__ . '/tmp2/nested/baz.txt');
-
- unlink(__DIR__.'/tmp/nested/baz.txt');
- rmdir(__DIR__.'/tmp/nested');
- unlink(__DIR__.'/tmp/bar.txt');
- unlink(__DIR__.'/tmp/foo.txt');
- rmdir(__DIR__.'/tmp');
-
- unlink(__DIR__.'/tmp2/nested/baz.txt');
- rmdir(__DIR__.'/tmp2/nested');
- unlink(__DIR__.'/tmp2/foo.txt');
- unlink(__DIR__.'/tmp2/bar.txt');
- rmdir(__DIR__.'/tmp2');
- }
-
-}
diff --git a/tests/Http/HttpJsonResponseTest.php b/tests/Http/HttpJsonResponseTest.php
deleted file mode 100644
index 6f79a83d0..000000000
--- a/tests/Http/HttpJsonResponseTest.php
+++ /dev/null
@@ -1,34 +0,0 @@
- 'bar']);
- $data = $response->getData();
- $this->assertInstanceOf('StdClass', $data);
- $this->assertEquals('bar', $data->foo);
- }
-
-
- public function testSetAndRetrieveOptions()
- {
- $response = new Illuminate\Http\JsonResponse(['foo' => 'bar']);
- $response->setJsonOptions(JSON_PRETTY_PRINT);
- $this->assertSame(JSON_PRETTY_PRINT, $response->getJsonOptions());
- }
-
-
- public function testSetAndRetrieveStatusCode()
- {
- $response = new Illuminate\Http\JsonResponse(['foo' => 'bar'], 404);
- $this->assertSame(404, $response->getStatusCode());
-
- $response = new Illuminate\Http\JsonResponse(['foo' => 'bar']);
- $response->setStatusCode(404);
- $this->assertSame(404, $response->getStatusCode());
- }
-
-}
diff --git a/tests/Http/HttpRedirectResponseTest.php b/tests/Http/HttpRedirectResponseTest.php
deleted file mode 100755
index 5c2fde8e4..000000000
--- a/tests/Http/HttpRedirectResponseTest.php
+++ /dev/null
@@ -1,142 +0,0 @@
-assertNull($response->headers->get('foo'));
- $response->header('foo', 'bar');
- $this->assertEquals('bar', $response->headers->get('foo'));
- $response->header('foo', 'baz', false);
- $this->assertEquals('bar', $response->headers->get('foo'));
- $response->header('foo', 'baz');
- $this->assertEquals('baz', $response->headers->get('foo'));
- }
-
-
- public function testWithOnRedirect()
-{
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('flash')->twice();
- $response->with(['name', 'age']);
- }
-
-
- public function testWithCookieOnRedirect()
- {
- $response = new RedirectResponse('foo.bar');
- $this->assertCount(0, $response->headers->getCookies());
- $this->assertEquals($response, $response->withCookie(new Cookie('foo', 'bar')));
- $cookies = $response->headers->getCookies();
- $this->assertCount(1, $cookies);
- $this->assertEquals('foo', $cookies[0]->getName());
- $this->assertEquals('bar', $cookies[0]->getValue());
- }
-
-
- public function testInputOnRedirect()
- {
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('flashInput')->once()->with(['name' => 'Taylor', 'age' => 26]);
- $response->withInput();
- }
-
-
- public function testOnlyInputOnRedirect()
- {
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('flashInput')->once()->with(['name' => 'Taylor']);
- $response->onlyInput('name');
- }
-
-
- public function testExceptInputOnRedirect()
- {
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('flashInput')->once()->with(['name' => 'Taylor']);
- $response->exceptInput('age');
- }
-
-
- public function testFlashingErrorsOnRedirect()
- {
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('get')->with('errors', m::type(ViewErrorBag::class))->andReturn(new Illuminate\Support\ViewErrorBag);
- $session->shouldReceive('flash')->once()->with('errors', m::type(ViewErrorBag::class));
- $provider = m::mock(MessageProviderInterface::class);
- $provider->shouldReceive('getMessageBag')->once()->andReturn(new Illuminate\Support\MessageBag);
- $response->withErrors($provider);
- }
-
-
- public function testSettersGettersOnRequest()
- {
- $response = new RedirectResponse('foo.bar');
- $this->assertNull($response->getRequest());
- $this->assertNull($response->getSession());
-
- $request = Request::create('/', 'GET');
- $session = m::mock(Store::class);
- $response->setRequest($request);
- $response->setSession($session);
- $this->assertSame($request, $response->getRequest());
- $this->assertSame($session, $response->getSession());
- }
-
-
- public function testRedirectWithErrorsArrayConvertsToMessageBag()
- {
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('get')->with('errors', m::type(ViewErrorBag::class))->andReturn(new Illuminate\Support\ViewErrorBag);
- $session->shouldReceive('flash')->once()->with('errors', m::type(ViewErrorBag::class));
- $provider = ['foo' => 'bar'];
- $response->withErrors($provider);
- }
-
-
- public function testMagicCall()
- {
- $response = new RedirectResponse('foo.bar');
- $response->setRequest(Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 26]));
- $response->setSession($session = m::mock(Store::class));
- $session->shouldReceive('flash')->once()->with('foo', 'bar');
- $response->withFoo('bar');
- }
-
-
- public function testMagicCallException()
- {
- $this->expectException('BadMethodCallException');
- $response = new RedirectResponse('foo.bar');
- $response->doesNotExist('bar');
- }
-
-}
diff --git a/tests/Http/HttpRequestTest.php b/tests/Http/HttpRequestTest.php
deleted file mode 100755
index 656b83737..000000000
--- a/tests/Http/HttpRequestTest.php
+++ /dev/null
@@ -1,428 +0,0 @@
-assertSame($request, $request->instance());
- }
-
-
- public function testRootMethod()
- {
- $request = Request::create('http://example.com/foo/bar/script.php?test');
- $this->assertEquals('http://example.com', $request->root());
- }
-
-
- public function testPathMethod()
- {
- $request = Request::create('', 'GET');
- $this->assertEquals('/', $request->path());
-
- $request = Request::create('/foo/bar', 'GET');
- $this->assertEquals('foo/bar', $request->path());
- }
-
-
- public function testDecodedPathMethod()
- {
- $request = Request::create('/foo%20bar');
- $this->assertEquals('foo bar', $request->decodedPath());
- }
-
-
- /**
- * @dataProvider segmentProvider
- */
- public function testSegmentMethod($path, $segment, $expected)
- {
- $request = Request::create($path, 'GET');
- $this->assertEquals($expected, $request->segment($segment, 'default'));
- }
-
-
- public function segmentProvider()
- {
- return [
- ['', 1, 'default'],
- ['foo/bar//baz', '1', 'foo'],
- ['foo/bar//baz', '2', 'bar'],
- ['foo/bar//baz', '3', 'baz'],
- ];
- }
-
- /**
- * @dataProvider segmentsProvider
- */
- public function testSegmentsMethod($path, $expected)
- {
- $request = Request::create($path, 'GET');
- $this->assertEquals($expected, $request->segments());
-
- $request = Request::create('foo/bar', 'GET');
- $this->assertEquals(['foo', 'bar'], $request->segments());
- }
-
-
- public function segmentsProvider()
- {
- return [
- ['', []],
- ['foo/bar', ['foo', 'bar']],
- ['foo/bar//baz', ['foo', 'bar', 'baz']],
- ['foo/0/bar', ['foo', '0', 'bar']],
- ];
- }
-
-
- public function testUrlMethod()
- {
- $request = Request::create('http://foo.com/foo/bar?name=taylor', 'GET');
- $this->assertEquals('http://foo.com/foo/bar', $request->url());
-
- $request = Request::create('http://foo.com/foo/bar/?', 'GET');
- $this->assertEquals('http://foo.com/foo/bar', $request->url());
- }
-
-
- public function testFullUrlMethod()
- {
- $request = Request::create('http://foo.com/foo/bar?name=taylor', 'GET');
- $this->assertEquals('http://foo.com/foo/bar?name=taylor', $request->fullUrl());
-
- $request = Request::create('https://foo.com', 'GET');
- $this->assertEquals('https://foo.com', $request->fullUrl());
- }
-
-
- public function testIsMethod()
- {
- $request = Request::create('/foo/bar', 'GET');
-
- $this->assertTrue($request->is('foo*'));
- $this->assertFalse($request->is('bar*'));
- $this->assertTrue($request->is('*bar*'));
- $this->assertTrue($request->is('bar*', 'foo*', 'baz'));
-
- $request = Request::create('/', 'GET');
-
- $this->assertTrue($request->is('/'));
- }
-
-
- public function testAjaxMethod()
- {
- $request = Request::create('/', 'GET');
- $this->assertFalse($request->ajax());
- $request = Request::create('/', 'GET', [], [], [], ['HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'], '{}');
- $this->assertTrue($request->ajax());
- }
-
-
- public function testSecureMethod()
- {
- $request = Request::create('http://example.com', 'GET');
- $this->assertFalse($request->secure());
- $request = Request::create('https://example.com', 'GET');
- $this->assertTrue($request->secure());
- }
-
-
- public function testHasMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor']);
- $this->assertTrue($request->has('name'));
- $this->assertFalse($request->has('foo'));
- $this->assertFalse($request->has('name', 'email'));
-
- $request = Request::create('/', 'GET', ['name' => 'Taylor', 'email' => 'foo']);
- $this->assertTrue($request->has('name'));
- $this->assertTrue($request->has('name', 'email'));
-
- //test arrays within query string
- $request = Request::create('/', 'GET', ['foo' => ['bar', 'baz']]);
- $this->assertTrue($request->has('foo'));
- }
-
-
- public function testInputMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor']);
- $this->assertEquals('Taylor', $request->input('name'));
- $this->assertEquals('Bob', $request->input('foo', 'Bob'));
- }
-
-
- public function testOnlyMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 25]);
- $this->assertEquals(['age' => 25], $request->only('age'));
- $this->assertEquals(['name' => 'Taylor', 'age' => 25], $request->only('name', 'age'));
-
- $request = Request::create('/', 'GET', ['developer' => ['name' => 'Taylor', 'age' => 25]]);
- $this->assertEquals(['developer' => ['age' => 25]], $request->only('developer.age'));
- $this->assertEquals(['developer' => ['name' => 'Taylor'], 'test' => null], $request->only('developer.name', 'test'));
- }
-
-
- public function testExceptMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor', 'age' => 25]);
- $this->assertEquals(['name' => 'Taylor'], $request->except('age'));
- $this->assertEquals([], $request->except('age', 'name'));
- }
-
-
- public function testQueryMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor']);
- $this->assertEquals('Taylor', $request->query('name'));
- $this->assertEquals('Bob', $request->query('foo', 'Bob'));
- $all = $request->query(null);
- $this->assertEquals('Taylor', $all['name']);
-
- $request = Request::create('/', 'GET', ['hello' => 'world', 'user' => ['Taylor', 'Mohamed Said']]);
- $this->assertSame(['Taylor', 'Mohamed Said'], $request->query('user'));
- $this->assertSame(['hello' => 'world', 'user' => ['Taylor', 'Mohamed Said']], $request->query->all());
-
- $request = Request::create('/?hello=world&user[]=Taylor&user[]=Mohamed%20Said', 'GET', []);
- $this->assertSame(['Taylor', 'Mohamed Said'], $request->query('user'));
- $this->assertSame(['hello' => 'world', 'user' => ['Taylor', 'Mohamed Said']], $request->query->all());
- }
-
-
- public function testCookieMethod()
- {
- $request = Request::create('/', 'GET', [], ['name' => 'Taylor']);
- $this->assertEquals('Taylor', $request->cookie('name'));
- $this->assertEquals('Bob', $request->cookie('foo', 'Bob'));
- $all = $request->cookie(null);
- $this->assertEquals('Taylor', $all['name']);
- }
-
-
- public function testHasCookieMethod()
- {
- $request = Request::create('/', 'GET', [], ['foo' => 'bar']);
- $this->assertTrue($request->hasCookie('foo'));
- $this->assertFalse($request->hasCookie('qu'));
- }
-
-
- public function testFileMethod()
- {
- $files = [
- 'foo' => [
- 'size' => 500,
- 'name' => 'foo.jpg',
- 'tmp_name' => __FILE__,
- 'type' => 'blah',
- 'error' => null,
- ],
- ];
- $request = Request::create('/', 'GET', [], [], $files);
- $this->assertInstanceOf(UploadedFile::class, $request->file('foo'));
- }
-
-
- public function testHasFileMethod()
- {
- $request = Request::create('/', 'GET', [], [], []);
- $this->assertFalse($request->hasFile('foo'));
-
- $files = [
- 'foo' => [
- 'size' => 500,
- 'name' => 'foo.jpg',
- 'tmp_name' => __FILE__,
- 'type' => 'blah',
- 'error' => null,
- ],
- ];
- $request = Request::create('/', 'GET', [], [], $files);
- $this->assertTrue($request->hasFile('foo'));
- }
-
-
- public function testServerMethod()
- {
- $request = Request::create('/', 'GET', [], [], [], ['foo' => 'bar']);
- $this->assertEquals('bar', $request->server('foo'));
- $this->assertEquals('bar', $request->server('foo.doesnt.exist', 'bar'));
- $all = $request->server(null);
- $this->assertEquals('bar', $all['foo']);
- }
-
-
- public function testMergeMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor']);
- $merge = ['buddy' => 'Dayle'];
- $request->merge($merge);
- $this->assertEquals('Taylor', $request->input('name'));
- $this->assertEquals('Dayle', $request->input('buddy'));
- }
-
-
- public function testReplaceMethod()
- {
- $request = Request::create('/', 'GET', ['name' => 'Taylor']);
- $replace = ['buddy' => 'Dayle'];
- $request->replace($replace);
- $this->assertNull($request->input('name'));
- $this->assertEquals('Dayle', $request->input('buddy'));
- }
-
-
- public function testHeaderMethod()
- {
- $request = Request::create('/', 'GET', [], [], [], ['HTTP_DO_THIS' => 'foo']);
- $this->assertEquals('foo', $request->header('do-this'));
- $all = $request->header(null);
- $this->assertEquals('foo', $all['do-this'][0]);
- }
-
-
- public function testJSONMethod()
- {
- $payload = ['name' => 'taylor'];
- $request = Request::create('/', 'GET', [], [], [], ['CONTENT_TYPE' => 'application/json'], json_encode($payload));
- $this->assertEquals('taylor', $request->json('name'));
- $this->assertEquals('taylor', $request->input('name'));
- $data = $request->json()->all();
- $this->assertEquals($payload, $data);
- }
-
-
- public function testJSONEmulatingPHPBuiltInServer()
- {
- $payload = ['name' => 'taylor'];
- $content = json_encode($payload);
- // The built in PHP 5.4 webserver incorrectly provides HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH,
- // rather than CONTENT_TYPE and CONTENT_LENGTH
- $request = Request::create('/', 'GET', [], [], [], ['HTTP_CONTENT_TYPE' => 'application/json', 'HTTP_CONTENT_LENGTH' => strlen($content)], $content);
- $this->assertTrue($request->isJson());
- $data = $request->json()->all();
- $this->assertEquals($payload, $data);
-
- $data = $request->all();
- $this->assertEquals($payload, $data);
- }
-
-
- public function testAllInputReturnsInputAndFiles()
- {
- $file = $this->getMock(UploadedFile::class, null, [__FILE__, 'photo.jpg']);
- $request = Request::create('/?boom=breeze', 'GET', ['foo' => 'bar'], [], ['baz' => $file]);
- $this->assertEquals(['foo' => 'bar', 'baz' => $file, 'boom' => 'breeze'], $request->all());
- }
-
-
- public function testAllInputReturnsNestedInputAndFiles()
- {
- $file = $this->getMock(UploadedFile::class, null, [__FILE__, 'photo.jpg']);
- $request = Request::create('/?boom=breeze', 'GET', ['foo' => ['bar' => 'baz']], [], ['foo' => ['photo' => $file]]
- );
- $this->assertEquals(['foo' => ['bar' => 'baz', 'photo' => $file], 'boom' => 'breeze'], $request->all());
- }
-
-
- public function testAllInputReturnsInputAfterReplace()
- {
- $request = Request::create('/?boom=breeze', 'GET', ['foo' => ['bar' => 'baz']]);
- $request->replace(['foo' => ['bar' => 'baz'], 'boom' => 'breeze']);
- $this->assertEquals(['foo' => ['bar' => 'baz'], 'boom' => 'breeze'], $request->all());
- }
-
-
- public function testAllInputWithNumericKeysReturnsInputAfterReplace()
- {
- $request1 = Request::create('/', 'POST', [0 => 'A', 1 => 'B', 2 => 'C']);
- $request1->replace([0 => 'A', 1 => 'B', 2 => 'C']);
- $this->assertEquals([0 => 'A', 1 => 'B', 2 => 'C'], $request1->all());
-
- $request2 = Request::create('/', 'POST', [1 => 'A', 2 => 'B', 3 => 'C']);
- $request2->replace([1 => 'A', 2 => 'B', 3 => 'C']);
- $this->assertEquals([1 => 'A', 2 => 'B', 3 => 'C'], $request2->all());
- }
-
-
- public function testOldMethodCallsSession()
- {
- $request = Request::create('/', 'GET');
- $session = m::mock(Store::class);
- $session->shouldReceive('getOldInput')->once()->with('foo', 'bar')->andReturn('boom');
- $request->setLaravelSession($session);
- $this->assertEquals('boom', $request->old('foo', 'bar'));
- }
-
-
- public function testFlushMethodCallsSession()
- {
- $request = Request::create('/', 'GET');
- $session = m::mock(Store::class);
- $session->shouldReceive('flashInput')->once();
- $request->setLaravelSession($session);
- $request->flush();
- }
-
-
- public function testFormatReturnsAcceptableFormat()
- {
- $request = Request::create('/', 'GET', [], [], [], ['HTTP_ACCEPT' => 'application/json']);
- $this->assertEquals('json', $request->format());
- $this->assertTrue($request->wantsJson());
-
- $request = Request::create('/', 'GET', [], [], [], ['HTTP_ACCEPT' => 'application/atom+xml']);
- $this->assertEquals('atom', $request->format());
- $this->assertFalse($request->wantsJson());
-
- $request = Request::create('/', 'GET', [], [], [], ['HTTP_ACCEPT' => 'is/not/known']);
- $this->assertEquals('html', $request->format());
- $this->assertEquals('foo', $request->format('foo'));
- }
-
-
- public function testSessionMethod()
- {
- $this->expectException('RuntimeException');
- $request = Request::create('/', 'GET');
- $request->session();
- }
-
-
- public function testCreateFromBase()
- {
- $body = [
- 'foo' => 'bar',
- 'baz' => ['qux'],
- ];
-
- $server = [
- 'CONTENT_TYPE' => 'application/json',
- ];
-
- $base = SymfonyRequest::create('/', 'GET', [], [], [], $server, json_encode($body));
-
- $request = Request::createFromBase($base);
-
- $this->assertEquals($request->request->all(), $body);
- }
-
-}
diff --git a/tests/Http/HttpResponseTest.php b/tests/Http/HttpResponseTest.php
deleted file mode 100755
index d245e3118..000000000
--- a/tests/Http/HttpResponseTest.php
+++ /dev/null
@@ -1,143 +0,0 @@
-assertSame('{"foo":"bar"}', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
-
- $response = new Response(new JsonableStub);
- $this->assertSame('foo', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
-
- $response = new Response(new ArrayableAndJsonableStub);
- $this->assertSame('{"foo":"bar"}', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
-
- $response = new Response;
- $response->setContent(['foo' => 'bar']);
- $this->assertSame('{"foo":"bar"}', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
-
- $response = new Response(new JsonSerializableStub);
- $this->assertSame('{"foo":"bar"}', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
-
- $response = new Response(new ArrayableStub);
- $this->assertSame('{"foo":"bar"}', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
-
- $response->setContent('{"foo": "bar"}');
- $this->assertSame('{"foo": "bar"}', $response->getContent());
- $this->assertSame('application/json', $response->headers->get('Content-Type'));
- }
-
-
- public function testRenderablesAreRendered()
- {
- $mock = m::mock(Renderable::class);
- $mock->shouldReceive('render')->once()->andReturn('foo');
- $response = new Response($mock);
- $this->assertEquals('foo', $response->getContent());
- }
-
-
- public function testHeader()
- {
- $response = new Response();
- $this->assertNull($response->headers->get('foo'));
- $response->header('foo', 'bar');
- $this->assertEquals('bar', $response->headers->get('foo'));
- $response->header('foo', 'baz', false);
- $this->assertEquals('bar', $response->headers->get('foo'));
- $response->header('foo', 'baz');
- $this->assertEquals('baz', $response->headers->get('foo'));
- }
-
-
- public function testWithCookie()
- {
- $response = new Response();
- $this->assertCount(0, $response->headers->getCookies());
- $this->assertEquals($response, $response->withCookie(new Cookie('foo', 'bar')));
- $cookies = $response->headers->getCookies();
- $this->assertCount(1, $cookies);
- $this->assertEquals('foo', $cookies[0]->getName());
- $this->assertEquals('bar', $cookies[0]->getValue());
- }
-
-
- public function testGetOriginalContent()
- {
- $arr = ['foo' => 'bar'];
- $response = new Response();
- $response->setContent($arr);
- $this->assertSame($arr, $response->getOriginalContent());
- }
-
-
- public function testSetAndRetrieveStatusCode()
- {
- $response = new Response('foo', 404);
- $this->assertSame(404, $response->getStatusCode());
-
- $response = new Response('foo');
- $response->setStatusCode(404);
- $this->assertSame(404, $response->getStatusCode());
- }
-
-}
-
-class ArrayableStub implements ArrayableInterface
-{
- public function toArray()
- {
- return ['foo' => 'bar'];
- }
-}
-
-class ArrayableAndJsonableStub implements ArrayableInterface, JsonableInterface
-{
- public function toJson($options = 0)
- {
- return '{"foo":"bar"}';
- }
-
- public function toArray()
- {
- return [];
- }
-}
-
-class JsonableStub implements JsonableInterface
-{
- public function toJson($options = 0)
- {
- return 'foo';
- }
-}
-
-class JsonSerializableStub implements JsonSerializable
-{
- public function jsonSerialize(): array
- {
- return ['foo' => 'bar'];
- }
-}
\ No newline at end of file
diff --git a/tests/Session/SessionMiddlewareTest.php b/tests/Session/SessionMiddlewareTest.php
deleted file mode 100644
index 99f742216..000000000
--- a/tests/Session/SessionMiddlewareTest.php
+++ /dev/null
@@ -1,86 +0,0 @@
-shouldReceive('getSessionConfig')->andReturn([
- 'driver' => 'file',
- 'lottery' => [100, 100],
- 'path' => '/',
- 'domain' => null,
- 'lifetime' => 120,
- 'expire_on_close' => false,
- ]);
-
- $manager->shouldReceive('driver')->andReturn($driver = m::mock(Store::class)->makePartial());
- $driver->shouldReceive('setRequestOnHandler')->once()->with($request);
- $driver->shouldReceive('start')->once();
- $app->shouldReceive('handle')->once()->with($request, Symfony\Component\HttpKernel\HttpKernelInterface::MAIN_REQUEST, true)->andReturn($response);
- $driver->shouldReceive('save')->once();
- $driver->shouldReceive('getHandler')->andReturn($handler = m::mock('StdClass'));
- $handler->shouldReceive('gc')->once()->with(120 * 60);
- $driver->shouldReceive('getName')->andReturn('name');
- $driver->shouldReceive('getId')->andReturn(1);
- $driver->shouldReceive('setPreviousUrl')->with('http://www.foo.com/some')->once();
-
- $middleResponse = $middle->handle($request);
-
- $this->assertSame($response, $middleResponse);
- $this->assertEquals(1, head($response->headers->getCookies())->getValue());
- }
-
-
- public function testSessionIsNotUsedWhenNoDriver()
- {
- $request = Symfony\Component\HttpFoundation\Request::create('/', 'GET');
- $response = new Symfony\Component\HttpFoundation\Response;
- $middle = new Illuminate\Session\Middleware(
- $app = m::mock(HttpKernelInterface::class),
- $manager = m::mock(SessionManager::class)
- );
- $manager->shouldReceive('getSessionConfig')->andReturn([
- 'driver' => null,
- ]);
- $app->shouldReceive('handle')->once()->with($request, Symfony\Component\HttpKernel\HttpKernelInterface::MAIN_REQUEST, true)->andReturn($response);
- $middleResponse = $middle->handle($request);
-
- $this->assertSame($response, $middleResponse);
- }
-
-
- public function testCheckingForRequestUsingArraySessions()
- {
- $middleware = new Illuminate\Session\Middleware(
- m::mock(HttpKernelInterface::class),
- $manager = m::mock(SessionManager::class),
- function() { return true; }
- );
-
- $manager->shouldReceive('setDefaultDriver')->once()->with('array');
-
- $middleware->checkRequestForArraySessions(new Symfony\Component\HttpFoundation\Request);
- }
-
-}
diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php
deleted file mode 100644
index 85553fcdd..000000000
--- a/tests/Session/SessionStoreTest.php
+++ /dev/null
@@ -1,329 +0,0 @@
-getSession();
- $session->getHandler()->shouldReceive('read')->once()->with($this->getSessionId())->andReturn(
- serialize(['foo' => 'bar', 'bagged' => ['name' => 'taylor']])
- );
- $session->start();
-
- $this->assertEquals('bar', $session->get('foo'));
- $this->assertEquals('baz', $session->get('bar', 'baz'));
- $this->assertTrue($session->has('foo'));
- $this->assertFalse($session->has('bar'));
- $this->assertTrue($session->isStarted());
-
- $session->put('baz', 'boom');
- $this->assertTrue($session->has('baz'));
- }
-
-
- public function testExists()
- {
- $session = $this->getSession();
- $session->put('foo', 'bar');
- $session->put('baz', null);
-
- $this->assertTrue($session->exists('foo'));
- $this->assertTrue($session->exists('baz'));
- $this->assertTrue($session->exists(['foo', 'baz']));
- $this->assertFalse($session->exists(['foo', 'bar']));
- $this->assertFalse($session->exists('bar'));
-
- $this->assertTrue($session->has('foo'));
- $this->assertFalse($session->has('baz'));
- }
-
-
- public function testSessionMigration()
- {
- $session = $this->getSession();
- $oldId = $session->getId();
- $session->getHandler()->shouldReceive('destroy')->never();
- $this->assertTrue($session->migrate());
- $this->assertNotEquals($oldId, $session->getId());
-
-
- $session = $this->getSession();
- $oldId = $session->getId();
- $session->getHandler()->shouldReceive('destroy')->once()->with($oldId);
- $this->assertTrue($session->migrate(true));
- $this->assertNotEquals($oldId, $session->getId());
- }
-
-
- public function testSessionRegeneration()
- {
- $session = $this->getSession();
- $oldId = $session->getId();
- $session->getHandler()->shouldReceive('destroy')->never();
- $this->assertTrue($session->regenerate());
- $this->assertNotEquals($oldId, $session->getId());
- }
-
-
- public function testCantSetInvalidId()
- {
- $session = $this->getSession();
-
- $session->setId(null);
- $this->assertFalse(null == $session->getId());
-
- $session->setId(['a']);
- $this->assertFalse(['a'] == $session->getId());
-
- $session->setId('wrong');
- $this->assertFalse('wrong' == $session->getId());
- }
-
-
- public function testSessionInvalidate()
- {
- $session = $this->getSession();
- $oldId = $session->getId();
- $session->set('foo','bar');
- $this->assertGreaterThan(0, count($session->all()));
- $session->getHandler()->shouldReceive('destroy')->never();
- $this->assertTrue($session->invalidate());
- $this->assertNotEquals($oldId, $session->getId());
- $this->assertCount(0, $session->all());
- }
-
-
- public function testSessionIsProperlySaved()
- {
- $session = $this->getSession();
- $session->getHandler()->shouldReceive('read')->once()->andReturn(serialize([]));
- $session->start();
- $session->put('foo', 'bar');
- $session->flash('baz', 'boom');
- $session->getHandler()->shouldReceive('write')->once()->with(
- $this->getSessionId(),
- serialize([
- '_token' => $session->token(),
- 'foo' => 'bar',
- 'baz' => 'boom',
- 'flash' => [
- 'new' => [],
- 'old' => ['baz'],
- ],
- ])
- );
- $session->save();
-
- $this->assertFalse($session->isStarted());
- }
-
-
- public function testOldInputFlashing()
- {
- $session = $this->getSession();
- $session->put('boom', 'baz');
- $session->flashInput(['foo' => 'bar', 'bar' => 0]);
-
- $this->assertTrue($session->hasOldInput('foo'));
- $this->assertEquals('bar', $session->getOldInput('foo'));
- $this->assertEquals(0, $session->getOldInput('bar'));
- $this->assertFalse($session->hasOldInput('boom'));
-
- $session->ageFlashData();
-
- $this->assertTrue($session->hasOldInput('foo'));
- $this->assertEquals('bar', $session->getOldInput('foo'));
- $this->assertEquals(0, $session->getOldInput('bar'));
- $this->assertFalse($session->hasOldInput('boom'));
- }
-
-
- public function testDataFlashing()
- {
- $session = $this->getSession();
- $session->flash('foo', 'bar');
- $session->flash('bar', 0);
-
- $this->assertTrue($session->has('foo'));
- $this->assertEquals('bar', $session->get('foo'));
- $this->assertEquals(0, $session->get('bar'));
-
- $session->ageFlashData();
-
- $this->assertTrue($session->has('foo'));
- $this->assertEquals('bar', $session->get('foo'));
- $this->assertEquals(0, $session->get('bar'));
-
- $session->ageFlashData();
-
- $this->assertFalse($session->has('foo'));
- $this->assertNull($session->get('foo'));
- }
-
-
- public function testDataMergeNewFlashes()
- {
- $session = $this->getSession();
- $session->flash('foo', 'bar');
- $session->set('fu', 'baz');
- $session->set('flash.old', ['qu']);
- $this->assertNotFalse(array_search('foo', $session->get('flash.new')));
- $this->assertFalse(array_search('fu', $session->get('flash.new')));
- $session->keep(['fu','qu']);
- $this->assertNotFalse(array_search('foo', $session->get('flash.new')));
- $this->assertNotFalse(array_search('fu', $session->get('flash.new')));
- $this->assertNotFalse(array_search('qu', $session->get('flash.new')));
- $this->assertFalse(array_search('qu', $session->get('flash.old')));
- }
-
-
- public function testReflash()
- {
- $session = $this->getSession();
- $session->flash('foo', 'bar');
- $session->set('flash.old', ['foo']);
- $session->reflash();
- $this->assertNotFalse(array_search('foo', $session->get('flash.new')));
- $this->assertFalse(array_search('foo', $session->get('flash.old')));
- }
-
-
- public function testReplace()
- {
- $session = $this->getSession();
- $session->set('foo', 'bar');
- $session->set('qu', 'ux');
- $session->replace(['foo' => 'baz']);
- $this->assertEquals('baz', $session->get('foo'));
- $this->assertEquals('ux', $session->get('qu'));
- }
-
-
- public function testRemove()
- {
- $session = $this->getSession();
- $session->set('foo', 'bar');
- $pulled = $session->remove('foo');
- $this->assertFalse($session->has('foo'));
- $this->assertEquals('bar', $pulled);
- }
-
-
- public function testFlush()
- {
- $session = $this->getSession();
- $session->put('foo', 'bar');
-
- $session->flush();
-
- $this->assertFalse($session->has('foo'));
- $this->assertEmpty($session->all());
- }
-
-
- public function testHasOldInputWithoutKey()
- {
- $session = $this->getSession();
- $session->flash('boom', 'baz');
- $this->assertFalse($session->hasOldInput());
-
- $session->flashInput(['foo' => 'bar']);
- $this->assertTrue($session->hasOldInput());
- }
-
-
- public function testHandlerNeedsRequest()
- {
- $session = $this->getSession();
- $this->assertFalse($session->handlerNeedsRequest());
- $session->getHandler()->shouldReceive('setRequest')->never();
-
- $session = new Store('test', m::mock(new CookieSessionHandler(new CookieJar(), 60)));
- $this->assertTrue($session->handlerNeedsRequest());
- $session->getHandler()->shouldReceive('setRequest')->once();
- $request = new Request();
- $session->setRequestOnHandler($request);
- }
-
-
- public function testToken()
- {
- $session = $this->getSession();
- $this->assertEquals($session->token(), $session->getToken());
- }
-
-
- public function testRegenerateToken()
- {
- $session = $this->getSession();
- $token = $session->getToken();
- $session->regenerateToken();
- $this->assertNotEquals($token, $session->getToken());
- }
-
-
- public function testName()
- {
- $session = $this->getSession();
- $this->assertEquals($session->getName(), $this->getSessionName());
- $session->setName('foo');
- $this->assertEquals($session->getName(), 'foo');
- }
-
-
- public function testSetPreviousUrl()
- {
- $session = $this->getSession();
- $session->setPreviousUrl('https://example.com/foo/bar');
-
- $this->assertTrue($session->has('_previous.url'));
- $this->assertSame('https://example.com/foo/bar', $session->get('_previous.url'));
-
- $url = $session->previousUrl();
- $this->assertSame('https://example.com/foo/bar', $url);
- }
-
-
- public function getSession()
- {
- $reflection = new ReflectionClass(Store::class);
- return $reflection->newInstanceArgs($this->getMocks());
- }
-
-
- public function getMocks()
- {
- return [
- $this->getSessionName(),
- m::mock('SessionHandlerInterface'),
- $this->getSessionId(),
- ];
- }
-
-
- public function getSessionId()
- {
- return 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
- }
-
-
- public function getSessionName()
- {
- return 'name';
- }
-
-}
diff --git a/tests/Support/SupportFluentTest.php b/tests/Support/SupportFluentTest.php
deleted file mode 100755
index df0039fc5..000000000
--- a/tests/Support/SupportFluentTest.php
+++ /dev/null
@@ -1,122 +0,0 @@
- 'Taylor', 'age' => 25];
- $fluent = new Fluent($array);
-
- $refl = new \ReflectionObject($fluent);
- $attributes = $refl->getProperty('attributes');
- $attributes->setAccessible(true);
-
- $this->assertEquals($array, $attributes->getValue($fluent));
- $this->assertEquals($array, $fluent->getAttributes());
- }
-
-
- public function testAttributesAreSetByConstructorGivenStdClass(): void
- {
- $array = ['name' => 'Taylor', 'age' => 25];
- $fluent = new Fluent((object) $array);
-
- $refl = new \ReflectionObject($fluent);
- $attributes = $refl->getProperty('attributes');
- $attributes->setAccessible(true);
-
- $this->assertEquals($array, $attributes->getValue($fluent));
- $this->assertEquals($array, $fluent->getAttributes());
- }
-
-
- public function testAttributesAreSetByConstructorGivenArrayIterator(): void
- {
- $array = ['name' => 'Taylor', 'age' => 25];
- $fluent = new Fluent(new FluentArrayIteratorStub($array));
-
- $refl = new \ReflectionObject($fluent);
- $attributes = $refl->getProperty('attributes');
- $attributes->setAccessible(true);
-
- $this->assertEquals($array, $attributes->getValue($fluent));
- $this->assertEquals($array, $fluent->getAttributes());
- }
-
-
- public function testGetMethodReturnsAttribute(): void
- {
- $fluent = new Fluent(['name' => 'Taylor']);
-
- $this->assertEquals('Taylor', $fluent->get('name'));
- $this->assertEquals('Default', $fluent->get('foo', 'Default'));
- $this->assertEquals('Taylor', $fluent->name);
- $this->assertNull($fluent->foo);
- }
-
-
- public function testMagicMethodsCanBeUsedToSetAttributes(): void
- {
- $fluent = new Fluent;
-
- $fluent->name = 'Taylor';
- $fluent->developer();
- $fluent->age(25);
-
- $this->assertEquals('Taylor', $fluent->name);
- $this->assertTrue($fluent->developer);
- $this->assertEquals(25, $fluent->age);
- $this->assertInstanceOf(Fluent::class, $fluent->programmer());
- }
-
-
- public function testIssetMagicMethod(): void
- {
- $array = ['name' => 'Taylor', 'age' => 25];
- $fluent = new Fluent($array);
-
- $this->assertTrue(isset($fluent->name));
-
- unset($fluent->name);
-
- $this->assertFalse(isset($fluent->name));
- }
-
-
- public function testToArrayReturnsAttribute(): void
- {
- $array = ['name' => 'Taylor', 'age' => 25];
- $fluent = new Fluent($array);
-
- $this->assertEquals($array, $fluent->toArray());
- }
-
-
- public function testToJsonEncodesTheToArrayResult(): void
- {
- $fluent = $this->getMock(Fluent::class, ['toArray']);
- $fluent->expects($this->once())->method('toArray')->willReturn('foo');
- $results = $fluent->toJson();
-
- $this->assertEquals(json_encode('foo'), $results);
- }
-
-}
-
-
-class FluentArrayIteratorStub implements \IteratorAggregate {
- protected array $items = [];
-
- public function __construct(array $items = [])
- {
- $this->items = (array) $items;
- }
-
- public function getIterator(): Traversable
- {
- return new \ArrayIterator($this->items);
- }
-}
diff --git a/tests/Support/SupportPluralizerTest.php b/tests/Support/SupportPluralizerTest.php
deleted file mode 100755
index 8ef438f5a..000000000
--- a/tests/Support/SupportPluralizerTest.php
+++ /dev/null
@@ -1,53 +0,0 @@
-assertEquals('children', str_plural('child'));
- $this->assertEquals('tests', str_plural('test'));
- $this->assertEquals('deer', str_plural('deer'));
- $this->assertEquals('child', str_singular('children'));
- $this->assertEquals('test', str_singular('tests'));
- $this->assertEquals('deer', str_singular('deer'));
- $this->assertEquals('criterion', str_singular('criteria'));
- }
-
-
- public function testCaseSensitiveUsage()
- {
- $this->assertEquals('Children', str_plural('Child'));
- $this->assertEquals('CHILDREN', str_plural('CHILD'));
- $this->assertEquals('Tests', str_plural('Test'));
- $this->assertEquals('TESTS', str_plural('TEST'));
- $this->assertEquals('tests', str_plural('test'));
- $this->assertEquals('Deer', str_plural('Deer'));
- $this->assertEquals('DEER', str_plural('DEER'));
- $this->assertEquals('Child', str_singular('Children'));
- $this->assertEquals('CHILD', str_singular('CHILDREN'));
- $this->assertEquals('Test', str_singular('Tests'));
- $this->assertEquals('TEST', str_singular('TESTS'));
- $this->assertEquals('Deer', str_singular('Deer'));
- $this->assertEquals('DEER', str_singular('DEER'));
- $this->assertEquals('Criterion', str_singular('Criteria'));
- $this->assertEquals('CRITERION', str_singular('CRITERIA'));
- }
-
- public function testIfEndOfWord()
- {
- $this->assertEquals('VortexFields', str_plural('VortexField'));
- $this->assertEquals('MatrixFields', str_plural('MatrixField'));
- $this->assertEquals('IndexFields', str_plural('IndexField'));
- $this->assertEquals('VertexFields', str_plural('VertexField'));
- }
-
- public function testAlreadyPluralizedIrregularWords()
- {
- $this->assertEquals('children', str_plural('children'));
- $this->assertEquals('radii', str_plural('radii'));
- $this->assertEquals('teeth', str_plural('teeth'));
- }
-
-}
diff --git a/tests/Support/SupportServiceProviderTest.php b/tests/Support/SupportServiceProviderTest.php
deleted file mode 100755
index e14365992..000000000
--- a/tests/Support/SupportServiceProviderTest.php
+++ /dev/null
@@ -1,24 +0,0 @@
-assertEquals(realpath(__DIR__ . '/'), $superProvider->guessPackagePath());
-
- $superSuperProvider = new SuperSuperProvider(null);
- $this->assertEquals(realpath(__DIR__.'/'), $superSuperProvider->guessPackagePath());
- }
-
-}
diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php
deleted file mode 100755
index 5dcdef2fa..000000000
--- a/tests/Support/SupportStrTest.php
+++ /dev/null
@@ -1,199 +0,0 @@
-assertEquals('Taylor...', Str::words('Taylor Otwell', 1));
- $this->assertEquals('Taylor___', Str::words('Taylor Otwell', 1, '___'));
- $this->assertEquals('Taylor Otwell', Str::words('Taylor Otwell', 3));
- }
-
-
- public function testStringTrimmedOnlyWhereNecessary(): void
- {
- $this->assertEquals(' Taylor Otwell ', Str::words(' Taylor Otwell ', 3));
- $this->assertEquals(' Taylor...', Str::words(' Taylor Otwell ', 1));
- }
-
-
- public function testStringTitle(): void
- {
- $this->assertEquals('Jefferson Costella', Str::title('jefferson costella'));
- $this->assertEquals('Jefferson Costella', Str::title('jefFErson coSTella'));
- $this->assertEquals('Admin_Role', Str::title('admin_role'));
- $this->assertEquals('', Str::title(null));
- $this->assertEquals('', Str::title(''));
- }
-
-
- public function testStringWithoutWordsDoesntProduceError(): void
- {
- $nbsp = chr(0xC2).chr(0xA0);
- $this->assertEquals(' ', Str::words(' '));
- $this->assertEquals($nbsp, Str::words($nbsp));
- }
-
-
- public function testStartsWith(): void
- {
- $this->assertTrue(Str::startsWith('jason', 'jas'));
- $this->assertTrue(Str::startsWith('jason', 'jason'));
- $this->assertTrue(Str::startsWith('jason', ['jas']));
- $this->assertFalse(Str::startsWith('jason', 'day'));
- $this->assertFalse(Str::startsWith('jason', ['day']));
- $this->assertFalse(Str::startsWith('jason', ''));
- }
-
- public function testEquals(): void
- {
- self::assertTrue(Str::equals('1234', '1234'));
- self::assertTrue(Str::equals('Laravel', 'Laravel'));
- self::assertTrue(Str::equals('Laravel', 'laRaVeL'));
- self::assertFalse(Str::equals('Laravel', 'laRaVeL', true));
- self::assertTrue(Str::equals('', ''));
- self::assertTrue(Str::equals('', null));
- self::assertTrue(Str::equals());
- self::assertFalse(Str::equals(null, 'Laravel'));
- self::assertFalse(Str::equals('Laravel'));
- self::assertFalse(Str::equals('Laravel', null, true));
- }
-
-
- public function testEndsWith(): void
- {
- $this->assertTrue(Str::endsWith('jason', 'on'));
- $this->assertTrue(Str::endsWith('jason', 'jason'));
- $this->assertTrue(Str::endsWith('jason', ['on']));
- $this->assertFalse(Str::endsWith('jason', 'no'));
- $this->assertFalse(Str::endsWith('jason', ['no']));
- $this->assertFalse(Str::endsWith('jason', ''));
- $this->assertFalse(Str::endsWith('7', ' 7'));
- }
-
-
- public function testStrContains(): void
- {
- $this->assertTrue(Str::contains('taylor', 'ylo'));
- $this->assertTrue(Str::contains('taylor', ['ylo']));
- $this->assertFalse(Str::contains('taylor', 'xxx'));
- $this->assertFalse(Str::contains('taylor', ['xxx']));
- $this->assertFalse(Str::contains('taylor', ''));
- $this->assertFalse(Str::contains('taylor', null));
- $this->assertFalse(Str::contains('', 'y'));
- $this->assertFalse(Str::contains(null, 'y'));
- }
-
-
- public function testParseCallback(): void
- {
- $this->assertEquals(['Class', 'method'], Str::parseCallback('Class@method', 'foo'));
- $this->assertEquals(['Class', 'foo'], Str::parseCallback('Class', 'foo'));
- }
-
-
- public function testSlug(): void
- {
- $this->assertEquals('hello-world', Str::slug('hello world'));
- $this->assertEquals('hello-world', Str::slug('hello-world'));
- $this->assertEquals('hello-world', Str::slug('hello_world'));
- $this->assertEquals('hello_world', Str::slug('hello_world', '_'));
- }
-
-
- public function testFinish(): void
- {
- $this->assertEquals('abbc', Str::finish('ab', 'bc'));
- $this->assertEquals('abbc', Str::finish('abbcbc', 'bc'));
- $this->assertEquals('abcbbc', Str::finish('abcbbcbc', 'bc'));
- }
-
-
- public function testIs(): void
- {
- $this->assertTrue(Str::is('/', '/'));
- $this->assertFalse(Str::is('/', ' /'));
- $this->assertFalse(Str::is('/', '/a'));
- $this->assertTrue(Str::is('foo/*', 'foo/bar/baz'));
- $this->assertTrue(Str::is('*/foo', 'blah/baz/foo'));
- $this->assertFalse(Str::is('*/foo', ''));
- $this->assertFalse(Str::is('*/foo', null));
- }
-
-
- public function testLower(): void
- {
- $this->assertEquals('foo bar baz', Str::lower('FOO BAR BAZ'));
- $this->assertEquals('foo bar baz', Str::lower('fOo Bar bAz'));
- $this->assertEquals('', Str::lower(null));
- }
-
-
- public function testUpper(): void
- {
- $this->assertEquals('FOO BAR BAZ', Str::upper('foo bar baz'));
- $this->assertEquals('FOO BAR BAZ', Str::upper('foO bAr BaZ'));
- $this->assertEquals('', Str::upper(null));
- }
-
-
- public function testLimit(): void
- {
- $this->assertEquals('Laravel is...', Str::limit('Laravel is a free, open source PHP web application framework.', 10));
- $this->assertEquals('', Str::limit(null));
- $this->assertEquals('', Str::limit(''));
- }
-
-
- public function testLength(): void
- {
- $this->assertEquals(11, Str::length('foo bar baz'));
- $this->assertEquals(0, Str::length(''));
- $this->assertEquals(0, Str::length(null));
- }
-
-
- public function testQuickRandom(): void
- {
- $randomInteger = mt_rand(1, 100);
- $this->assertEquals($randomInteger, strlen(Str::quickRandom($randomInteger)));
- $this->assertIsString(Str::quickRandom());
- $this->assertEquals(16, strlen(Str::quickRandom()));
- }
-
-
- public function testRandom(): void
- {
- $this->assertEquals(16, strlen(Str::random()));
- $randomInteger = mt_rand(1, 100);
- $this->assertEquals($randomInteger, strlen(Str::random($randomInteger)));
- $this->assertIsString(Str::random());
- }
-
- public function testNumberFormat(): void
- {
- $this->assertEquals('1,000,000', Str::numberFormat(1000000));
- $this->assertEquals('150.000,00', Str::numberFormat(150000, 2, ',', '.'));
- $this->assertEquals('0', Str::numberFormat());
- $this->assertEquals('0', Str::numberFormat(null));
- }
-
- public function testReplace(): void
- {
- $this->assertSame('foo bar laravel', Str::replace('baz', 'laravel', 'foo bar baz'));
- $this->assertSame('foo bar baz 8.x', Str::replace('?', '8.x', 'foo bar baz ?'));
- $this->assertSame('foo/bar/baz', Str::replace(' ', '/', 'foo bar baz'));
- $this->assertSame('foo bar baz', Str::replace(['?1', '?2', '?3'], ['foo', 'bar', 'baz'], '?1 ?2 ?3'));
- $this->assertEquals('', Str::replace('Yo', 'Laravel', ''));
- $this->assertEquals('', Str::replace('Yo', 'Laravel', null));
- }
-}