id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
192255
|
#! /bin/bash
# Note: This is run as root
cd ~
export enable_auth="${enable_auth}"
export basic_auth_credentials="${basic_auth_credentials}"
export auth_type="${auth_type}"
export token_auth_credentials="${token_auth_credentials}"
apt-get update -y
apt-get install -y ca-certificates curl gnupg lsb-release
mkdir -m 0755 -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update -y
chmod a+r /etc/apt/keyrings/docker.gpg
apt-get update -y
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin git
usermod -aG docker ubuntu
git clone https://github.com/chroma-core/chroma.git && cd chroma
git fetch --tags
git checkout tags/${chroma_release}
if [ "$${enable_auth}" = "true" ] && [ "$${auth_type}" = "basic" ] && [ ! -z "$${basic_auth_credentials}" ]; then
username=$(echo $basic_auth_credentials | cut -d: -f1)
password=$(echo $basic_auth_credentials | cut -d: -f2)
docker run --rm --entrypoint htpasswd httpd:2 -Bbn $username $password > server.htpasswd
cat <<EOF > .env
CHROMA_SERVER_AUTHN_CREDENTIALS_FILE="/chroma/server.htpasswd"
CHROMA_SERVER_AUTHN_PROVIDER="chromadb.auth.basic_authn.BasicAuthenticationServerProvider"
EOF
fi
if [ "$${enable_auth}" = "true" ] && [ "$${auth_type}" = "token" ] && [ ! -z "$${token_auth_credentials}" ]; then
cat <<EOF > .env
CHROMA_SERVER_AUTHN_CREDENTIALS="$${token_auth_credentials}" \
CHROMA_SERVER_AUTHN_PROVIDER="chromadb.auth.token_authn.TokenAuthenticationServerProvider"
EOF
fi
cat <<EOF > docker-compose.override.yaml
version: '3.8'
services:
server:
volumes:
- /chroma-data:/chroma/chroma
EOF
COMPOSE_PROJECT_NAME=chroma docker compose up -d --build
| |
192259
|
#! /bin/bash
# Note: This is run as root
cd ~
export enable_auth="${enable_auth}"
export basic_auth_credentials="${basic_auth_credentials}"
export auth_type="${auth_type}"
export token_auth_credentials="${token_auth_credentials}"
apt-get update -y
apt-get install -y ca-certificates curl gnupg lsb-release
mkdir -m 0755 -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \
$(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update -y
chmod a+r /etc/apt/keyrings/docker.gpg
apt-get update -y
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin git
usermod -aG docker debian
git clone https://github.com/chroma-core/chroma.git && cd chroma
git fetch --tags
git checkout tags/${chroma_release}
if [ "$${enable_auth}" = "true" ] && [ "$${auth_type}" = "basic" ] && [ ! -z "$${basic_auth_credentials}" ]; then
username=$(echo $basic_auth_credentials | cut -d: -f1)
password=$(echo $basic_auth_credentials | cut -d: -f2)
docker run --rm --entrypoint htpasswd httpd:2 -Bbn $username $password > server.htpasswd
cat <<EOF > .env
CHROMA_SERVER_AUTHN_CREDENTIALS_FILE="/chroma/server.htpasswd"
CHROMA_SERVER_AUTHN_PROVIDER="chromadb.auth.basic_authn.BasicAuthenticationServerProvider"
EOF
fi
if [ "$${enable_auth}" = "true" ] && [ "$${auth_type}" = "token" ] && [ ! -z "$${token_auth_credentials}" ]; then
cat <<EOF > .env
CHROMA_SERVER_AUTHN_CREDENTIALS="$${token_auth_credentials}"
CHROMA_SERVER_AUTHN_PROVIDER="chromadb.auth.token_authn.TokenAuthenticationServerProvider"
EOF
fi
cat <<EOF > docker-compose.override.yaml
version: '3.8'
services:
server:
volumes:
- /chroma-data:/chroma/chroma
EOF
COMPOSE_PROJECT_NAME=chroma docker compose up -d --build
| |
192261
|
#! /bin/bash
# Note: This is run as root
cd ~
export enable_auth="${enable_auth}"
export basic_auth_credentials="${basic_auth_credentials}"
export auth_type="${auth_type}"
export token_auth_credentials="${token_auth_credentials}"
apt-get update -y
apt-get install -y ca-certificates curl gnupg lsb-release
mkdir -m 0755 -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
apt-get update -y
chmod a+r /etc/apt/keyrings/docker.gpg
apt-get update -y
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin git
usermod -aG docker ubuntu
git clone https://github.com/chroma-core/chroma.git && cd chroma
git fetch --tags
git checkout tags/${chroma_release}
if [ "$${enable_auth}" = "true" ] && [ "$${auth_type}" = "basic" ] && [ ! -z "$${basic_auth_credentials}" ]; then
username=$(echo $basic_auth_credentials | cut -d: -f1)
password=$(echo $basic_auth_credentials | cut -d: -f2)
docker run --rm --entrypoint htpasswd httpd:2 -Bbn $username $password > server.htpasswd
cat <<EOF > .env
CHROMA_SERVER_AUTHN_CREDENTIALS_FILE="/chroma/server.htpasswd"
CHROMA_SERVER_AUTHN_PROVIDER="chromadb.auth.basic_authn.BasicAuthenticationServerProvider"
EOF
fi
if [ "$${enable_auth}" = "true" ] && [ "$${auth_type}" = "token" ] && [ ! -z "$${token_auth_credentials}" ]; then
cat <<EOF > .env
CHROMA_SERVER_AUTHN_CREDENTIALS="$${token_auth_credentials}"
CHROMA_SERVER_AUTHN_PROVIDER="chromadb.auth.token_authn.TokenAuthenticationServerProvider"
EOF
fi
cat <<EOF > docker-compose.override.yaml
version: '3.8'
services:
server:
volumes:
- /chroma-data:/chroma/chroma
EOF
COMPOSE_PROJECT_NAME=chroma docker compose up -d --build
| |
192267
|
import argparse
import os
from typing import List
from openai.types.chat import ChatCompletionMessageParam
import openai
import chromadb
def build_prompt(query: str, context: List[str]) -> List[ChatCompletionMessageParam]:
"""
Builds a prompt for the LLM. #
This function builds a prompt for the LLM. It takes the original query,
and the returned context, and asks the model to answer the question based only
on what's in the context, not what's in its weights.
More information: https://platform.openai.com/docs/guides/chat/introduction
Args:
query (str): The original query.
context (List[str]): The context of the query, returned by embedding search.
Returns:
A prompt for the LLM (List[ChatCompletionMessageParam]).
"""
system: ChatCompletionMessageParam = {
"role": "system",
"content": "I am going to ask you a question, which I would like you to answer"
"based only on the provided context, and not any other information."
"If there is not enough information in the context to answer the question,"
'say "I am not sure", then try to make a guess.'
"Break your answer up into nicely readable paragraphs.",
}
user: ChatCompletionMessageParam = {
"role": "user",
"content": f"The question is {query}. Here is all the context you have:"
f'{(" ").join(context)}',
}
return [system, user]
def get_chatGPT_response(query: str, context: List[str], model_name: str) -> str:
"""
Queries the GPT API to get a response to the question.
Args:
query (str): The original query.
context (List[str]): The context of the query, returned by embedding search.
Returns:
A response to the question.
"""
response = openai.chat.completions.create(
model=model_name,
messages=build_prompt(query, context),
)
return response.choices[0].message.content # type: ignore
def main(
collection_name: str = "documents_collection", persist_directory: str = "."
) -> None:
# Check if the OPENAI_API_KEY environment variable is set. Prompt the user to set it if not.
if "OPENAI_API_KEY" not in os.environ:
openai.api_key = input(
"Please enter your OpenAI API Key. You can get it from https://platform.openai.com/account/api-keys\n"
)
# Ask what model to use
model_name = "gpt-3.5-turbo"
answer = input(f"Do you want to use GPT-4? (y/n) (default is {model_name}): ")
if answer == "y":
model_name = "gpt-4"
# Instantiate a persistent chroma client in the persist_directory.
# This will automatically load any previously saved collections.
# Learn more at docs.trychroma.com
client = chromadb.PersistentClient(path=persist_directory)
# Get the collection.
collection = client.get_collection(name=collection_name)
# We use a simple input loop.
while True:
# Get the user's query
query = input("Query: ")
if len(query) == 0:
print("Please enter a question. Ctrl+C to Quit.\n")
continue
print(f"\nThinking using {model_name}...\n")
# Query the collection to get the 5 most relevant results
results = collection.query(
query_texts=[query], n_results=5, include=["documents", "metadatas"]
)
sources = "\n".join(
[
f"{result['filename']}: line {result['line_number']}"
for result in results["metadatas"][0] # type: ignore
]
)
# Get the response from GPT
response = get_chatGPT_response(query, results["documents"][0], model_name) # type: ignore
# Output, with sources
print(response)
print("\n")
print(f"Source documents:\n{sources}")
print("\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Load documents from a directory into a Chroma collection"
)
parser.add_argument(
"--persist_directory",
type=str,
default="chroma_storage",
help="The directory where you want to store the Chroma collection",
)
parser.add_argument(
"--collection_name",
type=str,
default="documents_collection",
help="The name of the Chroma collection",
)
# Parse arguments
args = parser.parse_args()
main(
collection_name=args.collection_name,
persist_directory=args.persist_directory,
)
| |
192268
|
import os
import argparse
from tqdm import tqdm
import chromadb
def main(
documents_directory: str = "documents",
collection_name: str = "documents_collection",
persist_directory: str = ".",
) -> None:
# Read all files in the data directory
documents = []
metadatas = []
files = os.listdir(documents_directory)
for filename in files:
with open(f"{documents_directory}/{filename}", "r") as file:
for line_number, line in enumerate(
tqdm((file.readlines()), desc=f"Reading {filename}"), 1
):
# Strip whitespace and append the line to the documents list
line = line.strip()
# Skip empty lines
if len(line) == 0:
continue
documents.append(line)
metadatas.append({"filename": filename, "line_number": line_number})
# Instantiate a persistent chroma client in the persist_directory.
# Learn more at docs.trychroma.com
client = chromadb.PersistentClient(path=persist_directory)
# If the collection already exists, we just return it. This allows us to add more
# data to an existing collection.
collection = client.get_or_create_collection(name=collection_name)
# Create ids from the current count
count = collection.count()
print(f"Collection already contains {count} documents")
ids = [str(i) for i in range(count, count + len(documents))]
# Load the documents in batches of 100
for i in tqdm(
range(0, len(documents), 100), desc="Adding documents", unit_scale=100
):
collection.add(
ids=ids[i : i + 100],
documents=documents[i : i + 100],
metadatas=metadatas[i : i + 100], # type: ignore
)
new_count = collection.count()
print(f"Added {new_count - count} documents")
if __name__ == "__main__":
# Read the data directory, collection name, and persist directory
parser = argparse.ArgumentParser(
description="Load documents from a directory into a Chroma collection"
)
# Add arguments
parser.add_argument(
"--data_directory",
type=str,
default="documents",
help="The directory where your text files are stored",
)
parser.add_argument(
"--collection_name",
type=str,
default="documents_collection",
help="The name of the Chroma collection",
)
parser.add_argument(
"--persist_directory",
type=str,
default="chroma_storage",
help="The directory where you want to store the Chroma collection",
)
# Parse arguments
args = parser.parse_args()
main(
documents_directory=args.data_directory,
collection_name=args.collection_name,
persist_directory=args.persist_directory,
)
| |
192317
|
<?php
namespace Illuminate\Types\Relations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneThrough;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use function PHPStan\Testing\assertType;
| |
192335
|
<?php
use Illuminate\Config\Repository;
use function PHPStan\Testing\assertType;
assertType('Illuminate\Foundation\Application', app());
assertType('mixed', app('foo'));
assertType('Illuminate\Config\Repository', app(Repository::class));
assertType('Illuminate\Contracts\Auth\Factory', auth());
assertType('Illuminate\Contracts\Auth\StatefulGuard', auth('foo'));
assertType('Illuminate\Cache\CacheManager', cache());
assertType('bool', cache(['foo' => 'bar'], 42));
assertType('mixed', cache('foo', 42));
assertType('Illuminate\Config\Repository', config());
assertType('null', config(['foo' => 'bar']));
assertType('mixed', config('foo'));
assertType('Illuminate\Log\Context\Repository', context());
assertType('Illuminate\Log\Context\Repository', context(['foo' => 'bar']));
assertType('mixed', context('foo'));
assertType('Illuminate\Cookie\CookieJar', cookie());
assertType('Symfony\Component\HttpFoundation\Cookie', cookie('foo'));
assertType('Illuminate\Foundation\Bus\PendingDispatch', dispatch('foo'));
assertType('Illuminate\Foundation\Bus\PendingClosureDispatch', dispatch(fn () => 1));
assertType('Illuminate\Log\LogManager', logger());
assertType('null', logger('foo'));
assertType('Illuminate\Log\LogManager', logs());
assertType('Psr\Log\LoggerInterface', logs('foo'));
assertType('int|null', rescue(fn () => 123));
assertType('int', rescue(fn () => 123, 345));
assertType('int', rescue(fn () => 123, fn () => 345));
assertType('Illuminate\Routing\Redirector', redirect());
assertType('Illuminate\Http\RedirectResponse', redirect('foo'));
assertType('mixed', resolve('foo'));
assertType('Illuminate\Config\Repository', resolve(Repository::class));
assertType('Illuminate\Http\Request', request());
assertType('mixed', request('foo'));
assertType('array<string, mixed>', request(['foo', 'bar']));
assertType('Illuminate\Contracts\Routing\ResponseFactory', response());
assertType('Illuminate\Http\Response', response('foo'));
assertType('Illuminate\Session\SessionManager', session());
assertType('mixed', session('foo'));
assertType('null', session(['foo' => 'bar']));
assertType('Illuminate\Contracts\Translation\Translator', trans());
assertType('array|string', trans('foo'));
assertType('Illuminate\Contracts\Validation\Factory', validator());
assertType('Illuminate\Contracts\Validation\Validator', validator([]));
assertType('Illuminate\Contracts\View\Factory', view());
assertType('Illuminate\Contracts\View\View', view('foo'));
assertType('Illuminate\Contracts\Routing\UrlGenerator', url());
assertType('string', url('foo'));
| |
192338
|
<?php
use Illuminate\Container\Container;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Exceptions\Handler;
use Symfony\Component\HttpKernel\Exception\HttpException;
$exceptions = new Exceptions(
new Handler(
new Container,
),
);
$exceptions->stopIgnoring(HttpException::class);
$exceptions->stopIgnoring([ModelNotFoundException::class]);
| |
192366
|
<?php
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\ServiceProvider;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'frontend_url' => env('FRONTEND_URL', 'http://localhost:3000'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => env('APP_TIMEZONE', 'UTC'),
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the default one
| is not available. You may change the value to correspond to any of
| the languages which are currently supported by your application.
|
*/
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on any
| requests to your application. You may add your own services to the
| arrays below to provide additional features to this application.
|
*/
'providers' => ServiceProvider::defaultProviders()->merge([
// Package Service Providers...
])->merge([
// Application Service Providers...
// App\Providers\AppServiceProvider::class,
])->merge([
// Added Service Providers (Do not remove this line)...
])->toArray(),
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. You may add any additional class aliases which should
| be loaded to the array. For speed, all aliases are lazy loaded.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'Example' => App\Facades\Example::class,
])->toArray(),
];
| |
192371
|
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain and all subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
];
| |
192373
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];
| |
192376
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
| |
192377
|
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', 'Laravel Log'),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
| |
192378
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
| |
192382
|
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model as Eloquent;
use PHPUnit\Framework\TestCase;
class DatabaseEloquentBelongsToManyChunkByIdTest extends TestCase
{
protected function setUp(): void
{
$db = new DB;
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
]);
$db->bootEloquent();
$db->setAsGlobal();
$this->createSchema();
}
/**
* Setup the database schema.
*
* @return void
*/
public function createSchema()
{
$this->schema()->create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
});
$this->schema()->create('articles', function ($table) {
$table->increments('id');
$table->string('title');
});
$this->schema()->create('article_user', function ($table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function testBelongsToChunkById()
{
$this->seedData();
$user = BelongsToManyChunkByIdTestTestUser::query()->first();
$i = 0;
$user->articles()->chunkById(1, function (Collection $collection) use (&$i) {
$i++;
$this->assertEquals($i, $collection->first()->id);
});
$this->assertSame(3, $i);
}
public function testBelongsToChunkByIdDesc()
{
$this->seedData();
$user = BelongsToManyChunkByIdTestTestUser::query()->first();
$i = 0;
$user->articles()->chunkByIdDesc(1, function (Collection $collection) use (&$i) {
$this->assertEquals(3 - $i, $collection->first()->id);
$i++;
});
$this->assertSame(3, $i);
}
/**
* Tear down the database schema.
*
* @return void
*/
protected function tearDown(): void
{
$this->schema()->drop('users');
$this->schema()->drop('articles');
$this->schema()->drop('article_user');
}
/**
* Helpers...
*/
protected function seedData()
{
$user = BelongsToManyChunkByIdTestTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
BelongsToManyChunkByIdTestTestArticle::query()->insert([
['id' => 1, 'title' => 'Another title'],
['id' => 2, 'title' => 'Another title'],
['id' => 3, 'title' => 'Another title'],
]);
$user->articles()->sync([3, 1, 2]);
}
/**
* Get a database connection instance.
*
* @return \Illuminate\Database\ConnectionInterface
*/
protected function connection()
{
return Eloquent::getConnectionResolver()->connection();
}
/**
* Get a schema builder instance.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected function schema()
{
return $this->connection()->getSchemaBuilder();
}
}
class BelongsToManyChunkByIdTestTestUser extends Eloquent
{
protected $table = 'users';
protected $fillable = ['id', 'email'];
public $timestamps = false;
public function articles()
{
return $this->belongsToMany(BelongsToManyChunkByIdTestTestArticle::class, 'article_user', 'user_id', 'article_id');
}
}
class BelongsToManyChunkByIdTestTestArticle extends Eloquent
{
protected $table = 'articles';
protected $keyType = 'string';
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['id', 'title'];
}
| |
192438
|
public function test_for_method_recycles_models()
{
Factory::guessFactoryNamesUsing(function ($model) {
return $model.'Factory';
});
$user = FactoryTestUserFactory::new()->create();
$post = FactoryTestPostFactory::new()
->recycle($user)
->for(FactoryTestUserFactory::new())
->create();
$this->assertSame(1, FactoryTestUser::count());
}
public function test_has_method_does_not_reassign_the_parent()
{
Factory::guessFactoryNamesUsing(function ($model) {
return $model.'Factory';
});
$post = FactoryTestPostFactory::new()->create();
$user = FactoryTestUserFactory::new()
->recycle($post)
// The recycled post already belongs to a user, so it shouldn't be recycled here.
->has(FactoryTestPostFactory::new(), 'posts')
->create();
$this->assertSame(2, FactoryTestPost::count());
}
public function test_multiple_models_can_be_provided_to_recycle()
{
Factory::guessFactoryNamesUsing(function ($model) {
return $model.'Factory';
});
$users = FactoryTestUserFactory::new()->count(3)->create();
$posts = FactoryTestPostFactory::new()
->recycle($users)
->for(FactoryTestUserFactory::new())
->has(FactoryTestCommentFactory::new()->count(5), 'comments')
->count(2)
->create();
$this->assertSame(3, FactoryTestUser::count());
}
public function test_recycled_models_can_be_combined_with_multiple_calls()
{
Factory::guessFactoryNamesUsing(function ($model) {
return $model.'Factory';
});
$users = FactoryTestUserFactory::new()
->count(2)
->create();
$posts = FactoryTestPostFactory::new()
->recycle($users)
->count(2)
->create();
$additionalUser = FactoryTestUserFactory::new()
->create();
$additionalPost = FactoryTestPostFactory::new()
->recycle($additionalUser)
->create();
$this->assertSame(3, FactoryTestUser::count());
$this->assertSame(3, FactoryTestPost::count());
$comments = FactoryTestCommentFactory::new()
->recycle($users)
->recycle($posts)
->recycle([$additionalUser, $additionalPost])
->count(5)
->create();
$this->assertSame(3, FactoryTestUser::count());
$this->assertSame(3, FactoryTestPost::count());
}
public function test_no_models_can_be_provided_to_recycle()
{
Factory::guessFactoryNamesUsing(function ($model) {
return $model.'Factory';
});
$posts = FactoryTestPostFactory::new()
->recycle([])
->count(2)
->create();
$this->assertSame(2, FactoryTestPost::count());
$this->assertSame(2, FactoryTestUser::count());
}
/**
* Get a database connection instance.
*
* @return \Illuminate\Database\ConnectionInterface
*/
protected function connection()
{
return Eloquent::getConnectionResolver()->connection();
}
/**
* Get a schema builder instance.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected function schema()
{
return $this->connection()->getSchemaBuilder();
}
}
class FactoryTestUserFactory extends Factory
{
protected $model = FactoryTestUser::class;
public function definition()
{
return [
'name' => $this->faker->name(),
'options' => null,
];
}
}
class FactoryTestUser extends Eloquent
{
use HasFactory;
protected $table = 'users';
public function posts()
{
return $this->hasMany(FactoryTestPost::class, 'user_id');
}
public function roles()
{
return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin');
}
public function factoryTestRoles()
{
return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin');
}
}
class FactoryTestPostFactory extends Factory
{
protected $model = FactoryTestPost::class;
public function definition()
{
return [
'user_id' => FactoryTestUserFactory::new(),
'title' => $this->faker->name(),
];
}
}
class FactoryTestPost extends Eloquent
{
use SoftDeletes;
protected $table = 'posts';
public function user()
{
return $this->belongsTo(FactoryTestUser::class, 'user_id');
}
public function factoryTestUser()
{
return $this->belongsTo(FactoryTestUser::class, 'user_id');
}
public function author()
{
return $this->belongsTo(FactoryTestUser::class, 'user_id');
}
public function comments()
{
return $this->morphMany(FactoryTestComment::class, 'commentable');
}
}
class FactoryTestCommentFactory extends Factory
{
protected $model = FactoryTestComment::class;
public function definition()
{
return [
'commentable_id' => FactoryTestPostFactory::new(),
'commentable_type' => FactoryTestPost::class,
'user_id' => fn () => FactoryTestUserFactory::new(),
'body' => $this->faker->name(),
];
}
public function trashed()
{
return $this->state([
'deleted_at' => Carbon::now()->subWeek(),
]);
}
}
class FactoryTestComment extends Eloquent
{
use SoftDeletes;
protected $table = 'comments';
public function commentable()
{
return $this->morphTo();
}
}
class FactoryTestRoleFactory extends Factory
{
protected $model = FactoryTestRole::class;
public function definition()
{
return [
'name' => $this->faker->name(),
];
}
}
class FactoryTestRole extends Eloquent
{
protected $table = 'roles';
protected $touches = ['users'];
public function users()
{
return $this->belongsToMany(FactoryTestUser::class, 'role_user', 'role_id', 'user_id')->withPivot('admin');
}
}
| |
192440
|
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Eloquent\Relations\Relation;
use PHPUnit\Framework\TestCase;
class DatabaseEloquentIntegrationWithTablePrefixTest extends TestCase
{
/**
* Bootstrap Eloquent.
*
* @return void
*/
protected function setUp(): void
{
$db = new DB;
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
]);
$db->bootEloquent();
$db->setAsGlobal();
Eloquent::getConnectionResolver()->connection()->setTablePrefix('prefix_');
$this->createSchema();
}
protected function createSchema()
{
$this->schema('default')->create('users', function ($table) {
$table->increments('id');
$table->string('email');
$table->timestamps();
});
$this->schema('default')->create('friends', function ($table) {
$table->integer('user_id');
$table->integer('friend_id');
});
$this->schema('default')->create('posts', function ($table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('parent_id')->nullable();
$table->string('name');
$table->timestamps();
});
$this->schema('default')->create('photos', function ($table) {
$table->increments('id');
$table->morphs('imageable');
$table->string('name');
$table->timestamps();
});
}
/**
* Tear down the database schema.
*
* @return void
*/
protected function tearDown(): void
{
foreach (['default'] as $connection) {
$this->schema($connection)->drop('users');
$this->schema($connection)->drop('friends');
$this->schema($connection)->drop('posts');
$this->schema($connection)->drop('photos');
}
Relation::morphMap([], false);
}
public function testBasicModelHydration()
{
EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
EloquentTestUser::create(['email' => 'abigailotwell@gmail.com']);
$models = EloquentTestUser::fromQuery('SELECT * FROM prefix_users WHERE email = ?', ['abigailotwell@gmail.com']);
$this->assertInstanceOf(Collection::class, $models);
$this->assertInstanceOf(EloquentTestUser::class, $models[0]);
$this->assertSame('abigailotwell@gmail.com', $models[0]->email);
$this->assertCount(1, $models);
}
/**
* Helpers...
*/
/**
* Get a database connection instance.
*
* @return \Illuminate\Database\Connection
*/
protected function connection($connection = 'default')
{
return Eloquent::getConnectionResolver()->connection($connection);
}
/**
* Get a schema builder instance.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected function schema($connection = 'default')
{
return $this->connection($connection)->getSchemaBuilder();
}
}
| |
192450
|
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use PHPUnit\Framework\TestCase;
class DatabaseEloquentBelongsToManyEachByIdTest extends TestCase
{
protected function setUp(): void
{
$db = new DB;
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
]);
$db->bootEloquent();
$db->setAsGlobal();
$this->createSchema();
}
/**
* Setup the database schema.
*
* @return void
*/
public function createSchema()
{
$this->schema()->create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
});
$this->schema()->create('articles', function ($table) {
$table->increments('id');
$table->string('title');
});
$this->schema()->create('article_user', function ($table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function testBelongsToEachById()
{
$this->seedData();
$user = BelongsToManyEachByIdTestTestUser::query()->first();
$i = 0;
$user->articles()->eachById(function (BelongsToManyEachByIdTestTestArticle $model) use (&$i) {
$i++;
$this->assertEquals($i, $model->id);
});
$this->assertSame(3, $i);
}
/**
* Tear down the database schema.
*
* @return void
*/
protected function tearDown(): void
{
$this->schema()->drop('users');
$this->schema()->drop('articles');
$this->schema()->drop('article_user');
}
/**
* Helpers...
*/
protected function seedData()
{
$user = BelongsToManyEachByIdTestTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
BelongsToManyEachByIdTestTestArticle::query()->insert([
['id' => 1, 'title' => 'Another title'],
['id' => 2, 'title' => 'Another title'],
['id' => 3, 'title' => 'Another title'],
]);
$user->articles()->sync([3, 1, 2]);
}
/**
* Get a database connection instance.
*
* @return \Illuminate\Database\ConnectionInterface
*/
protected function connection()
{
return Eloquent::getConnectionResolver()->connection();
}
/**
* Get a schema builder instance.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected function schema()
{
return $this->connection()->getSchemaBuilder();
}
}
class BelongsToManyEachByIdTestTestUser extends Eloquent
{
protected $table = 'users';
protected $fillable = ['id', 'email'];
public $timestamps = false;
public function articles()
{
return $this->belongsToMany(BelongsToManyEachByIdTestTestArticle::class, 'article_user', 'user_id', 'article_id');
}
}
class BelongsToManyEachByIdTestTestArticle extends Eloquent
{
protected $table = 'articles';
protected $keyType = 'string';
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['id', 'title'];
}
| |
192457
|
public function testCheckAndCreateMethodsOnMultiConnections()
{
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::on('second_connection')->find(
EloquentTestUser::on('second_connection')->insert(['id' => 2, 'email' => 'themsaid@gmail.com'])
);
$user1 = EloquentTestUser::on('second_connection')->findOrNew(1);
$user2 = EloquentTestUser::on('second_connection')->findOrNew(2);
$this->assertFalse($user1->exists);
$this->assertTrue($user2->exists);
$this->assertSame('second_connection', $user1->getConnectionName());
$this->assertSame('second_connection', $user2->getConnectionName());
$user1 = EloquentTestUser::on('second_connection')->firstOrNew(['email' => 'taylorotwell@gmail.com']);
$user2 = EloquentTestUser::on('second_connection')->firstOrNew(['email' => 'themsaid@gmail.com']);
$this->assertFalse($user1->exists);
$this->assertTrue($user2->exists);
$this->assertSame('second_connection', $user1->getConnectionName());
$this->assertSame('second_connection', $user2->getConnectionName());
$this->assertEquals(1, EloquentTestUser::on('second_connection')->count());
$user1 = EloquentTestUser::on('second_connection')->firstOrCreate(['email' => 'taylorotwell@gmail.com']);
$user2 = EloquentTestUser::on('second_connection')->firstOrCreate(['email' => 'themsaid@gmail.com']);
$this->assertSame('second_connection', $user1->getConnectionName());
$this->assertSame('second_connection', $user2->getConnectionName());
$this->assertEquals(2, EloquentTestUser::on('second_connection')->count());
}
public function testCreatingModelWithEmptyAttributes()
{
$model = EloquentTestNonIncrementing::create([]);
$this->assertFalse($model->exists);
$this->assertFalse($model->wasRecentlyCreated);
}
public function testChunkByIdWithNonIncrementingKey()
{
EloquentTestNonIncrementingSecond::create(['name' => ' First']);
EloquentTestNonIncrementingSecond::create(['name' => ' Second']);
EloquentTestNonIncrementingSecond::create(['name' => ' Third']);
$i = 0;
EloquentTestNonIncrementingSecond::query()->chunkById(2, function (Collection $users) use (&$i) {
if (! $i) {
$this->assertSame(' First', $users[0]->name);
$this->assertSame(' Second', $users[1]->name);
} else {
$this->assertSame(' Third', $users[0]->name);
}
$i++;
}, 'name');
$this->assertEquals(2, $i);
}
public function testEachByIdWithNonIncrementingKey()
{
EloquentTestNonIncrementingSecond::create(['name' => ' First']);
EloquentTestNonIncrementingSecond::create(['name' => ' Second']);
EloquentTestNonIncrementingSecond::create(['name' => ' Third']);
$users = [];
EloquentTestNonIncrementingSecond::query()->eachById(
function (EloquentTestNonIncrementingSecond $user, $i) use (&$users) {
$users[] = [$user->name, $i];
}, 2, 'name');
$this->assertSame([[' First', 0], [' Second', 1], [' Third', 2]], $users);
}
public function testPluck()
{
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);
$simple = EloquentTestUser::oldest('id')->pluck('users.email')->all();
$keyed = EloquentTestUser::oldest('id')->pluck('users.email', 'users.id')->all();
$this->assertEquals(['taylorotwell@gmail.com', 'abigailotwell@gmail.com'], $simple);
$this->assertEquals([1 => 'taylorotwell@gmail.com', 2 => 'abigailotwell@gmail.com'], $keyed);
}
public function testPluckWithJoin()
{
$user1 = EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
$user2 = EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);
$user2->posts()->create(['id' => 1, 'name' => 'First post']);
$user1->posts()->create(['id' => 2, 'name' => 'Second post']);
$query = EloquentTestUser::join('posts', 'users.id', '=', 'posts.user_id');
$this->assertEquals([1 => 'First post', 2 => 'Second post'], $query->pluck('posts.name', 'posts.id')->all());
$this->assertEquals([2 => 'First post', 1 => 'Second post'], $query->pluck('posts.name', 'users.id')->all());
$this->assertEquals(['abigailotwell@gmail.com' => 'First post', 'taylorotwell@gmail.com' => 'Second post'], $query->pluck('posts.name', 'users.email AS user_email')->all());
}
public function testPluckWithColumnNameContainingASpace()
{
EloquentTestUserWithSpaceInColumnName::create(['id' => 1, 'email address' => 'taylorotwell@gmail.com']);
EloquentTestUserWithSpaceInColumnName::create(['id' => 2, 'email address' => 'abigailotwell@gmail.com']);
$simple = EloquentTestUserWithSpaceInColumnName::oldest('id')->pluck('users_with_space_in_column_name.email address')->all();
$keyed = EloquentTestUserWithSpaceInColumnName::oldest('id')->pluck('email address', 'id')->all();
$this->assertEquals(['taylorotwell@gmail.com', 'abigailotwell@gmail.com'], $simple);
$this->assertEquals([1 => 'taylorotwell@gmail.com', 2 => 'abigailotwell@gmail.com'], $keyed);
}
public function testFindOrFail()
{
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);
$single = EloquentTestUser::findOrFail(1);
$multiple = EloquentTestUser::findOrFail([1, 2]);
$this->assertInstanceOf(EloquentTestUser::class, $single);
$this->assertSame('taylorotwell@gmail.com', $single->email);
$this->assertInstanceOf(Collection::class, $multiple);
$this->assertInstanceOf(EloquentTestUser::class, $multiple[0]);
$this->assertInstanceOf(EloquentTestUser::class, $multiple[1]);
}
public function testFindOrFailWithSingleIdThrowsModelNotFoundException()
{
$this->expectException(ModelNotFoundException::class);
$this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\EloquentTestUser] 1');
$this->expectExceptionObject(
(new ModelNotFoundException())->setModel(EloquentTestUser::class, [1]),
);
EloquentTestUser::findOrFail(1);
}
public function testFindOrFailWithMultipleIdsThrowsModelNotFoundException()
{
$this->expectException(ModelNotFoundException::class);
$this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\EloquentTestUser] 2, 3');
$this->expectExceptionObject(
(new ModelNotFoundException())->setModel(EloquentTestUser::class, [2, 3]),
);
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::findOrFail([1, 2, 3]);
}
public function testFindOrFailWithMultipleIdsUsingCollectionThrowsModelNotFoundException()
{
$this->expectException(ModelNotFoundException::class);
$this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\EloquentTestUser] 2, 3');
$this->expectExceptionObject(
(new ModelNotFoundException())->setModel(EloquentTestUser::class, [2, 3]),
);
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::findOrFail(new Collection([1, 1, 2, 3]));
}
| |
192459
|
public function testHasOnSelfReferencingBelongsToManyRelationshipWithWherePivot()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$user->friends()->create(['email' => 'abigailotwell@gmail.com']);
$results = EloquentTestUser::has('friendsOne')->get();
$this->assertCount(1, $results);
$this->assertSame('taylorotwell@gmail.com', $results->first()->email);
}
public function testHasOnNestedSelfReferencingBelongsToManyRelationshipWithWherePivot()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
$friend->friends()->create(['email' => 'foo@gmail.com']);
$results = EloquentTestUser::has('friendsOne.friendsTwo')->get();
$this->assertCount(1, $results);
$this->assertSame('taylorotwell@gmail.com', $results->first()->email);
}
public function testHasOnSelfReferencingBelongsToRelationship()
{
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
$results = EloquentTestPost::has('parentPost')->get();
$this->assertCount(1, $results);
$this->assertSame('Child Post', $results->first()->name);
}
public function testAggregatedValuesOfDatetimeField()
{
EloquentTestUser::create(['id' => 1, 'email' => 'test1@test.test', 'created_at' => '2016-08-10 09:21:00', 'updated_at' => Carbon::now()]);
EloquentTestUser::create(['id' => 2, 'email' => 'test2@test.test', 'created_at' => '2016-08-01 12:00:00', 'updated_at' => Carbon::now()]);
$this->assertSame('2016-08-10 09:21:00', EloquentTestUser::max('created_at'));
$this->assertSame('2016-08-01 12:00:00', EloquentTestUser::min('created_at'));
}
public function testWhereHasOnSelfReferencingBelongsToRelationship()
{
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
$results = EloquentTestPost::whereHas('parentPost', function ($query) {
$query->where('name', 'Parent Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Child Post', $results->first()->name);
}
public function testWithWhereHasOnSelfReferencingBelongsToRelationship()
{
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
$results = EloquentTestPost::withWhereHas('parentPost', function ($query) {
$query->where('name', 'Parent Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Child Post', $results->first()->name);
$this->assertTrue($results->first()->relationLoaded('parentPost'));
$this->assertSame($results->first()->parentPost->name, 'Parent Post');
}
public function testHasOnNestedSelfReferencingBelongsToRelationship()
{
$grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
$results = EloquentTestPost::has('parentPost.parentPost')->get();
$this->assertCount(1, $results);
$this->assertSame('Child Post', $results->first()->name);
}
public function testWhereHasOnNestedSelfReferencingBelongsToRelationship()
{
$grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
$results = EloquentTestPost::whereHas('parentPost.parentPost', function ($query) {
$query->where('name', 'Grandparent Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Child Post', $results->first()->name);
}
public function testWithWhereHasOnNestedSelfReferencingBelongsToRelationship()
{
$grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
$results = EloquentTestPost::withWhereHas('parentPost.parentPost', function ($query) {
$query->where('name', 'Grandparent Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Child Post', $results->first()->name);
$this->assertTrue($results->first()->relationLoaded('parentPost'));
$this->assertSame($results->first()->parentPost->name, 'Parent Post');
$this->assertTrue($results->first()->parentPost->relationLoaded('parentPost'));
$this->assertSame($results->first()->parentPost->parentPost->name, 'Grandparent Post');
}
public function testHasOnSelfReferencingHasManyRelationship()
{
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
$results = EloquentTestPost::has('childPosts')->get();
$this->assertCount(1, $results);
$this->assertSame('Parent Post', $results->first()->name);
}
public function testWhereHasOnSelfReferencingHasManyRelationship()
{
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
$results = EloquentTestPost::whereHas('childPosts', function ($query) {
$query->where('name', 'Child Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Parent Post', $results->first()->name);
}
public function testWithWhereHasOnSelfReferencingHasManyRelationship()
{
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'user_id' => 1]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 2]);
$results = EloquentTestPost::withWhereHas('childPosts', function ($query) {
$query->where('name', 'Child Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Parent Post', $results->first()->name);
$this->assertTrue($results->first()->relationLoaded('childPosts'));
$this->assertSame($results->first()->childPosts->pluck('name')->unique()->toArray(), ['Child Post']);
}
| |
192460
|
public function testHasOnNestedSelfReferencingHasManyRelationship()
{
$grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
$results = EloquentTestPost::has('childPosts.childPosts')->get();
$this->assertCount(1, $results);
$this->assertSame('Grandparent Post', $results->first()->name);
}
public function testWhereHasOnNestedSelfReferencingHasManyRelationship()
{
$grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
$results = EloquentTestPost::whereHas('childPosts.childPosts', function ($query) {
$query->where('name', 'Child Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Grandparent Post', $results->first()->name);
}
public function testWithWhereHasOnNestedSelfReferencingHasManyRelationship()
{
$grandParentPost = EloquentTestPost::create(['name' => 'Grandparent Post', 'user_id' => 1]);
$parentPost = EloquentTestPost::create(['name' => 'Parent Post', 'parent_id' => $grandParentPost->id, 'user_id' => 2]);
EloquentTestPost::create(['name' => 'Child Post', 'parent_id' => $parentPost->id, 'user_id' => 3]);
$results = EloquentTestPost::withWhereHas('childPosts.childPosts', function ($query) {
$query->where('name', 'Child Post');
})->get();
$this->assertCount(1, $results);
$this->assertSame('Grandparent Post', $results->first()->name);
$this->assertTrue($results->first()->relationLoaded('childPosts'));
$this->assertSame($results->first()->childPosts->pluck('name')->unique()->toArray(), ['Parent Post']);
$this->assertSame($results->first()->childPosts->pluck('childPosts')->flatten()->pluck('name')->unique()->toArray(), ['Child Post']);
}
public function testHasWithNonWhereBindings()
{
$user = EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
$user->posts()->create(['name' => 'Post 2'])
->photos()->create(['name' => 'photo.jpg']);
$query = EloquentTestUser::has('postWithPhotos');
$bindingsCount = count($query->getBindings());
$questionMarksCount = substr_count($query->toSql(), '?');
$this->assertEquals($questionMarksCount, $bindingsCount);
}
public function testHasOnMorphToRelationship()
{
$post = EloquentTestPost::create(['name' => 'Morph Post', 'user_id' => 1]);
(new EloquentTestPhoto)->imageable()->associate($post)->fill(['name' => 'Morph Photo'])->save();
$photos = EloquentTestPhoto::has('imageable')->get();
$this->assertEquals(1, $photos->count());
}
public function testBelongsToManyRelationshipModelsAreProperlyHydratedWithSoleQuery()
{
$user = EloquentTestUserWithCustomFriendPivot::create(['email' => 'taylorotwell@gmail.com']);
$user->friends()->create(['email' => 'abigailotwell@gmail.com']);
$user->friends()->get()->each(function ($friend) {
$this->assertInstanceOf(EloquentTestFriendPivot::class, $friend->pivot);
});
$soleFriend = $user->friends()->where('email', 'abigailotwell@gmail.com')->sole();
$this->assertInstanceOf(EloquentTestFriendPivot::class, $soleFriend->pivot);
}
public function testBelongsToManyRelationshipMissingModelExceptionWithSoleQueryWorks()
{
$this->expectException(ModelNotFoundException::class);
$user = EloquentTestUserWithCustomFriendPivot::create(['email' => 'taylorotwell@gmail.com']);
$user->friends()->where('email', 'abigailotwell@gmail.com')->sole();
}
public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
EloquentTestUser::first()->friends()->chunk(2, function ($friends) use ($user, $friend) {
$this->assertCount(1, $friends);
$this->assertSame('abigailotwell@gmail.com', $friends->first()->email);
$this->assertEquals($user->id, $friends->first()->pivot->user_id);
$this->assertEquals($friend->id, $friends->first()->pivot->friend_id);
});
}
public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverEachRequest()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
EloquentTestUser::first()->friends()->each(function ($result) use ($user, $friend) {
$this->assertSame('abigailotwell@gmail.com', $result->email);
$this->assertEquals($user->id, $result->pivot->user_id);
$this->assertEquals($friend->id, $result->pivot->friend_id);
});
}
public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverCursorRequest()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']);
foreach (EloquentTestUser::first()->friends()->cursor() as $result) {
$this->assertSame('abigailotwell@gmail.com', $result->email);
$this->assertEquals($user->id, $result->pivot->user_id);
$this->assertEquals($friend->id, $result->pivot->friend_id);
}
}
public function testBasicHasManyEagerLoading()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$user->posts()->create(['name' => 'First Post']);
$user = EloquentTestUser::with('posts')->where('email', 'taylorotwell@gmail.com')->first();
$this->assertSame('First Post', $user->posts->first()->name);
$post = EloquentTestPost::with('user')->where('name', 'First Post')->get();
$this->assertSame('taylorotwell@gmail.com', $post->first()->user->email);
}
public function testBasicNestedSelfReferencingHasManyEagerLoading()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$post = $user->posts()->create(['name' => 'First Post']);
$post->childPosts()->create(['name' => 'Child Post', 'user_id' => $user->id]);
$user = EloquentTestUser::with('posts.childPosts')->where('email', 'taylorotwell@gmail.com')->first();
$this->assertNotNull($user->posts->first());
$this->assertSame('First Post', $user->posts->first()->name);
$this->assertNotNull($user->posts->first()->childPosts->first());
$this->assertSame('Child Post', $user->posts->first()->childPosts->first()->name);
$post = EloquentTestPost::with('parentPost.user')->where('name', 'Child Post')->get();
$this->assertNotNull($post->first()->parentPost);
$this->assertNotNull($post->first()->parentPost->user);
$this->assertSame('taylorotwell@gmail.com', $post->first()->parentPost->user->email);
}
| |
192461
|
public function testBasicMorphManyRelationship()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$user->photos()->create(['name' => 'Avatar 1']);
$user->photos()->create(['name' => 'Avatar 2']);
$post = $user->posts()->create(['name' => 'First Post']);
$post->photos()->create(['name' => 'Hero 1']);
$post->photos()->create(['name' => 'Hero 2']);
$this->assertInstanceOf(Collection::class, $user->photos);
$this->assertInstanceOf(EloquentTestPhoto::class, $user->photos[0]);
$this->assertInstanceOf(Collection::class, $post->photos);
$this->assertInstanceOf(EloquentTestPhoto::class, $post->photos[0]);
$this->assertCount(2, $user->photos);
$this->assertCount(2, $post->photos);
$this->assertSame('Avatar 1', $user->photos[0]->name);
$this->assertSame('Avatar 2', $user->photos[1]->name);
$this->assertSame('Hero 1', $post->photos[0]->name);
$this->assertSame('Hero 2', $post->photos[1]->name);
$photos = EloquentTestPhoto::orderBy('name')->get();
$this->assertInstanceOf(Collection::class, $photos);
$this->assertCount(4, $photos);
$this->assertInstanceOf(EloquentTestUser::class, $photos[0]->imageable);
$this->assertInstanceOf(EloquentTestPost::class, $photos[2]->imageable);
$this->assertSame('taylorotwell@gmail.com', $photos[1]->imageable->email);
$this->assertSame('First Post', $photos[3]->imageable->name);
}
public function testMorphMapIsUsedForCreatingAndFetchingThroughRelation()
{
Relation::morphMap([
'user' => EloquentTestUser::class,
'post' => EloquentTestPost::class,
]);
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$user->photos()->create(['name' => 'Avatar 1']);
$user->photos()->create(['name' => 'Avatar 2']);
$post = $user->posts()->create(['name' => 'First Post']);
$post->photos()->create(['name' => 'Hero 1']);
$post->photos()->create(['name' => 'Hero 2']);
$this->assertInstanceOf(Collection::class, $user->photos);
$this->assertInstanceOf(EloquentTestPhoto::class, $user->photos[0]);
$this->assertInstanceOf(Collection::class, $post->photos);
$this->assertInstanceOf(EloquentTestPhoto::class, $post->photos[0]);
$this->assertCount(2, $user->photos);
$this->assertCount(2, $post->photos);
$this->assertSame('Avatar 1', $user->photos[0]->name);
$this->assertSame('Avatar 2', $user->photos[1]->name);
$this->assertSame('Hero 1', $post->photos[0]->name);
$this->assertSame('Hero 2', $post->photos[1]->name);
$this->assertSame('user', $user->photos[0]->imageable_type);
$this->assertSame('user', $user->photos[1]->imageable_type);
$this->assertSame('post', $post->photos[0]->imageable_type);
$this->assertSame('post', $post->photos[1]->imageable_type);
}
public function testMorphMapIsUsedWhenFetchingParent()
{
Relation::morphMap([
'user' => EloquentTestUser::class,
'post' => EloquentTestPost::class,
]);
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$user->photos()->create(['name' => 'Avatar 1']);
$photo = EloquentTestPhoto::first();
$this->assertSame('user', $photo->imageable_type);
$this->assertInstanceOf(EloquentTestUser::class, $photo->imageable);
}
public function testMorphMapIsMergedByDefault()
{
$map1 = [
'user' => EloquentTestUser::class,
];
$map2 = [
'post' => EloquentTestPost::class,
];
Relation::morphMap($map1);
Relation::morphMap($map2);
$this->assertEquals(array_merge($map1, $map2), Relation::morphMap());
}
public function testMorphMapOverwritesCurrentMap()
{
$map1 = [
'user' => EloquentTestUser::class,
];
$map2 = [
'post' => EloquentTestPost::class,
];
Relation::morphMap($map1, false);
$this->assertEquals($map1, Relation::morphMap());
Relation::morphMap($map2, false);
$this->assertEquals($map2, Relation::morphMap());
}
public function testEmptyMorphToRelationship()
{
$photo = new EloquentTestPhoto;
$this->assertNull($photo->imageable);
}
public function testSaveOrFail()
{
$date = '1970-01-01';
$post = new EloquentTestPost([
'user_id' => 1, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date,
]);
$this->assertTrue($post->saveOrFail());
$this->assertEquals(1, EloquentTestPost::count());
}
public function testSavingJSONFields()
{
$model = EloquentTestWithJSON::create(['json' => ['x' => 0]]);
$this->assertEquals(['x' => 0], $model->json);
$model->fillable(['json->y', 'json->a->b']);
$model->update(['json->y' => '1']);
$this->assertArrayNotHasKey('json->y', $model->toArray());
$this->assertEquals(['x' => 0, 'y' => 1], $model->json);
$model->update(['json->a->b' => '3']);
$this->assertArrayNotHasKey('json->a->b', $model->toArray());
$this->assertEquals(['x' => 0, 'y' => 1, 'a' => ['b' => 3]], $model->json);
}
public function testSaveOrFailWithDuplicatedEntry()
{
$this->expectException(QueryException::class);
$this->expectExceptionMessage('SQLSTATE[23000]:');
$date = '1970-01-01';
EloquentTestPost::create([
'id' => 1, 'user_id' => 1, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date,
]);
$post = new EloquentTestPost([
'id' => 1, 'user_id' => 1, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date,
]);
$post->saveOrFail();
}
public function testMultiInsertsWithDifferentValues()
{
$date = '1970-01-01';
$result = EloquentTestPost::insert([
['user_id' => 1, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date],
['user_id' => 2, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date],
]);
$this->assertTrue($result);
$this->assertEquals(2, EloquentTestPost::count());
}
public function testMultiInsertsWithSameValues()
{
$date = '1970-01-01';
$result = EloquentTestPost::insert([
['user_id' => 1, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date],
['user_id' => 1, 'name' => 'Post', 'created_at' => $date, 'updated_at' => $date],
]);
$this->assertTrue($result);
$this->assertEquals(2, EloquentTestPost::count());
}
| |
192462
|
public function testNestedTransactions()
{
$user = EloquentTestUser::create(['email' => 'taylor@laravel.com']);
$this->connection()->transaction(function () use ($user) {
try {
$this->connection()->transaction(function () use ($user) {
$user->email = 'otwell@laravel.com';
$user->save();
throw new Exception;
});
} catch (Exception) {
// ignore the exception
}
$user = EloquentTestUser::first();
$this->assertSame('taylor@laravel.com', $user->email);
});
}
public function testNestedTransactionsUsingSaveOrFailWillSucceed()
{
$user = EloquentTestUser::create(['email' => 'taylor@laravel.com']);
$this->connection()->transaction(function () use ($user) {
try {
$user->email = 'otwell@laravel.com';
$user->saveOrFail();
} catch (Exception) {
// ignore the exception
}
$user = EloquentTestUser::first();
$this->assertSame('otwell@laravel.com', $user->email);
$this->assertEquals(1, $user->id);
});
}
public function testNestedTransactionsUsingSaveOrFailWillFails()
{
$user = EloquentTestUser::create(['email' => 'taylor@laravel.com']);
$this->connection()->transaction(function () use ($user) {
try {
$user->id = 'invalid';
$user->email = 'otwell@laravel.com';
$user->saveOrFail();
} catch (Exception) {
// ignore the exception
}
$user = EloquentTestUser::first();
$this->assertSame('taylor@laravel.com', $user->email);
$this->assertEquals(1, $user->id);
});
}
public function testToArrayIncludesDefaultFormattedTimestamps()
{
$model = new EloquentTestUser;
$model->setRawAttributes([
'created_at' => '2012-12-04',
'updated_at' => '2012-12-05',
]);
$array = $model->toArray();
$this->assertSame('2012-12-04T00:00:00.000000Z', $array['created_at']);
$this->assertSame('2012-12-05T00:00:00.000000Z', $array['updated_at']);
}
public function testToArrayIncludesCustomFormattedTimestamps()
{
$model = new EloquentTestUserWithCustomDateSerialization;
$model->setRawAttributes([
'created_at' => '2012-12-04',
'updated_at' => '2012-12-05',
]);
$array = $model->toArray();
$this->assertSame('04-12-12', $array['created_at']);
$this->assertSame('05-12-12', $array['updated_at']);
}
public function testIncrementingPrimaryKeysAreCastToIntegersByDefault()
{
EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
$user = EloquentTestUser::first();
$this->assertIsInt($user->id);
}
public function testDefaultIncrementingPrimaryKeyIntegerCastCanBeOverwritten()
{
EloquentTestUserWithStringCastId::create(['email' => 'taylorotwell@gmail.com']);
$user = EloquentTestUserWithStringCastId::first();
$this->assertIsString($user->id);
}
public function testRelationsArePreloadedInGlobalScope()
{
$user = EloquentTestUserWithGlobalScope::create(['email' => 'taylorotwell@gmail.com']);
$user->posts()->create(['name' => 'My Post']);
$result = EloquentTestUserWithGlobalScope::first();
$this->assertCount(1, $result->getRelations());
}
public function testModelIgnoredByGlobalScopeCanBeRefreshed()
{
$user = EloquentTestUserWithOmittingGlobalScope::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
$this->assertNotNull($user->fresh());
}
public function testGlobalScopeCanBeRemovedByOtherGlobalScope()
{
$user = EloquentTestUserWithGlobalScopeRemovingOtherScope::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
$user->delete();
$this->assertNotNull(EloquentTestUserWithGlobalScopeRemovingOtherScope::find($user->id));
}
public function testForPageBeforeIdCorrectlyPaginates()
{
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);
$results = EloquentTestUser::forPageBeforeId(15, 2);
$this->assertInstanceOf(Builder::class, $results);
$this->assertEquals(1, $results->first()->id);
$results = EloquentTestUser::orderBy('id', 'desc')->forPageBeforeId(15, 2);
$this->assertInstanceOf(Builder::class, $results);
$this->assertEquals(1, $results->first()->id);
}
public function testForPageAfterIdCorrectlyPaginates()
{
EloquentTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
EloquentTestUser::create(['id' => 2, 'email' => 'abigailotwell@gmail.com']);
$results = EloquentTestUser::forPageAfterId(15, 1);
$this->assertInstanceOf(Builder::class, $results);
$this->assertEquals(2, $results->first()->id);
$results = EloquentTestUser::orderBy('id', 'desc')->forPageAfterId(15, 1);
$this->assertInstanceOf(Builder::class, $results);
$this->assertEquals(2, $results->first()->id);
}
public function testMorphToRelationsAcrossDatabaseConnections()
{
$item = null;
EloquentTestItem::create(['id' => 1]);
EloquentTestOrder::create(['id' => 1, 'item_type' => EloquentTestItem::class, 'item_id' => 1]);
try {
$item = EloquentTestOrder::first()->item;
} catch (Exception) {
// ignore the exception
}
$this->assertInstanceOf(EloquentTestItem::class, $item);
}
public function testEagerLoadedMorphToRelationsOnAnotherDatabaseConnection()
{
EloquentTestPost::create(['id' => 1, 'name' => 'Default Connection Post', 'user_id' => 1]);
EloquentTestPhoto::create(['id' => 1, 'imageable_type' => EloquentTestPost::class, 'imageable_id' => 1, 'name' => 'Photo']);
EloquentTestPost::on('second_connection')
->create(['id' => 1, 'name' => 'Second Connection Post', 'user_id' => 1]);
EloquentTestPhoto::on('second_connection')
->create(['id' => 1, 'imageable_type' => EloquentTestPost::class, 'imageable_id' => 1, 'name' => 'Photo']);
$defaultConnectionPost = EloquentTestPhoto::with('imageable')->first()->imageable;
$secondConnectionPost = EloquentTestPhoto::on('second_connection')->with('imageable')->first()->imageable;
$this->assertSame('Default Connection Post', $defaultConnectionPost->name);
$this->assertSame('Second Connection Post', $secondConnectionPost->name);
}
| |
192470
|
{
/**
* Setup the database schema.
*
* @return void
*/
protected function setUp(): void
{
$db = new DB;
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
]);
$db->bootEloquent();
$db->setAsGlobal();
$this->createSchema();
}
protected function createSchema()
{
$this->schema()->create('test_posts', function ($table) {
$table->increments('id');
$table->timestamps();
});
$this->schema()->create('test_comments', function ($table) {
$table->increments('id');
$table->morphs('commentable');
$table->timestamps();
});
}
/**
* Tear down the database schema.
*
* @return void
*/
protected function tearDown(): void
{
$this->schema()->drop('test_posts');
$this->schema()->drop('test_comments');
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenLazyLoaded()
{
MorphManyInversePostModel::factory()->withComments()->count(3)->create();
$posts = MorphManyInversePostModel::all();
foreach ($posts as $post) {
$this->assertFalse($post->relationLoaded('comments'));
$comments = $post->comments;
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenEagerLoaded()
{
MorphManyInversePostModel::factory()->withComments()->count(3)->create();
$posts = MorphManyInversePostModel::with('comments')->get();
foreach ($posts as $post) {
$comments = $post->getRelation('comments');
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
}
public function testMorphManyGuessedInverseRelationIsProperlySetToParentWhenLazyLoaded()
{
MorphManyInversePostModel::factory()->withComments()->count(3)->create();
$posts = MorphManyInversePostModel::all();
foreach ($posts as $post) {
$this->assertFalse($post->relationLoaded('guessedComments'));
$comments = $post->guessedComments;
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
}
public function testMorphManyGuessedInverseRelationIsProperlySetToParentWhenEagerLoaded()
{
MorphManyInversePostModel::factory()->withComments()->count(3)->create();
$posts = MorphManyInversePostModel::with('guessedComments')->get();
foreach ($posts as $post) {
$comments = $post->getRelation('guessedComments');
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
}
public function testMorphLatestOfManyInverseRelationIsProperlySetToParentWhenLazyLoaded()
{
MorphManyInversePostModel::factory()->count(3)->withComments()->create();
$posts = MorphManyInversePostModel::all();
foreach ($posts as $post) {
$this->assertFalse($post->relationLoaded('lastComment'));
$comment = $post->lastComment;
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphLatestOfManyInverseRelationIsProperlySetToParentWhenEagerLoaded()
{
MorphManyInversePostModel::factory()->count(3)->withComments()->create();
$posts = MorphManyInversePostModel::with('lastComment')->get();
foreach ($posts as $post) {
$comment = $post->getRelation('lastComment');
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphLatestOfManyGuessedInverseRelationIsProperlySetToParentWhenLazyLoaded()
{
MorphManyInversePostModel::factory()->count(3)->withComments()->create();
$posts = MorphManyInversePostModel::all();
foreach ($posts as $post) {
$this->assertFalse($post->relationLoaded('guessedLastComment'));
$comment = $post->guessedLastComment;
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphLatestOfManyGuessedInverseRelationIsProperlySetToParentWhenEagerLoaded()
{
MorphManyInversePostModel::factory()->count(3)->withComments()->create();
$posts = MorphManyInversePostModel::with('guessedLastComment')->get();
foreach ($posts as $post) {
$comment = $post->getRelation('guessedLastComment');
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphOneOfManyInverseRelationIsProperlySetToParentWhenLazyLoaded()
{
MorphManyInversePostModel::factory()->count(3)->withComments()->create();
$posts = MorphManyInversePostModel::all();
foreach ($posts as $post) {
$this->assertFalse($post->relationLoaded('firstComment'));
$comment = $post->firstComment;
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphOneOfManyInverseRelationIsProperlySetToParentWhenEagerLoaded()
{
MorphManyInversePostModel::factory()->count(3)->withComments()->create();
$posts = MorphManyInversePostModel::with('firstComment')->get();
foreach ($posts as $post) {
$comment = $post->getRelation('firstComment');
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenMakingMany()
{
$post = MorphManyInversePostModel::create();
$comments = $post->comments()->makeMany(array_fill(0, 3, []));
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenCreatingMany()
{
$post = MorphManyInversePostModel::create();
$comments = $post->comments()->createMany(array_fill(0, 3, []));
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenCreatingManyQuietly()
{
$post = MorphManyInversePostModel::create();
$comments = $post->comments()->createManyQuietly(array_fill(0, 3, []));
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenSavingMany()
{
$post = MorphManyInversePostModel::create();
$comments = array_fill(0, 3, new MorphManyInverseCommentModel);
$post->comments()->saveMany($comments);
foreach ($comments as $comment) {
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertSame($post, $comment->commentable);
}
}
public function testMorphManyInverseRelationIsProperlySetToParentWhenUpdatingMany()
{
$post = MorphManyInversePostModel::create();
$comments = MorphManyInverseCommentModel::factory()->count(3)->create();
foreach ($comments as $comment) {
$this->assertTrue($post->isNot($comment->commentable));
}
$post->comments()->saveMany($comments);
foreach ($comments as $comment) {
$this->assertSame($post, $comment->commentable);
}
}
/**
* Helpers...
*/
| |
192478
|
public function testDropTimestampsTz()
{
$blueprint = new Blueprint('users');
$blueprint->dropTimestampsTz();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" drop column "created_at", drop column "updated_at"', $statements[0]);
}
public function testDropMorphs()
{
$blueprint = new Blueprint('photos');
$blueprint->dropMorphs('imageable');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(2, $statements);
$this->assertSame('drop index "photos_imageable_type_imageable_id_index"', $statements[0]);
$this->assertSame('alter table "photos" drop column "imageable_type", drop column "imageable_id"', $statements[1]);
}
public function testRenameTable()
{
$blueprint = new Blueprint('users');
$blueprint->rename('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" rename to "foo"', $statements[0]);
}
public function testRenameIndex()
{
$blueprint = new Blueprint('users');
$blueprint->renameIndex('foo', 'bar');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter index "foo" rename to "bar"', $statements[0]);
}
public function testAddingPrimaryKey()
{
$blueprint = new Blueprint('users');
$blueprint->primary('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('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->assertSame('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->assertSame('create index "baz" on "users" ("foo", "bar")', $statements[0]);
}
public function testAddingIndexWithAlgorithm()
{
$blueprint = new Blueprint('users');
$blueprint->index(['foo', 'bar'], 'baz', 'hash');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "baz" on "users" using hash ("foo", "bar")', $statements[0]);
}
public function testAddingFulltextIndex()
{
$blueprint = new Blueprint('users');
$blueprint->fulltext('body');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "users_body_fulltext" on "users" using gin ((to_tsvector(\'english\', "body")))', $statements[0]);
}
public function testAddingFulltextIndexMultipleColumns()
{
$blueprint = new Blueprint('users');
$blueprint->fulltext(['body', 'title']);
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "users_body_title_fulltext" on "users" using gin ((to_tsvector(\'english\', "body") || to_tsvector(\'english\', "title")))', $statements[0]);
}
public function testAddingFulltextIndexWithLanguage()
{
$blueprint = new Blueprint('users');
$blueprint->fulltext('body')->language('spanish');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "users_body_fulltext" on "users" using gin ((to_tsvector(\'spanish\', "body")))', $statements[0]);
}
public function testAddingFulltextIndexWithFluency()
{
$blueprint = new Blueprint('users');
$blueprint->string('body')->fulltext();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(2, $statements);
$this->assertSame('create index "users_body_fulltext" on "users" using gin ((to_tsvector(\'english\', "body")))', $statements[1]);
}
public function testAddingSpatialIndex()
{
$blueprint = new Blueprint('geo');
$blueprint->spatialIndex('coordinates');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "geo_coordinates_spatialindex" on "geo" using gist ("coordinates")', $statements[0]);
}
public function testAddingFluentSpatialIndex()
{
$blueprint = new Blueprint('geo');
$blueprint->geometry('coordinates', 'point')->spatialIndex();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(2, $statements);
$this->assertSame('create index "geo_coordinates_spatialindex" on "geo" using gist ("coordinates")', $statements[1]);
}
public function testAddingRawIndex()
{
$blueprint = new Blueprint('users');
$blueprint->rawIndex('(function(column))', 'raw_index');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "raw_index" on "users" ((function(column)))', $statements[0]);
}
public function testAddingIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->increments('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "id" serial not null primary key', $statements[0]);
}
public function testAddingSmallIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->smallIncrements('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "id" smallserial not null primary key', $statements[0]);
}
public function testAddingMediumIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->mediumIncrements('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "id" serial not null primary key', $statements[0]);
}
public function testAddingID()
{
$blueprint = new Blueprint('users');
$blueprint->id();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "id" bigserial not null primary key', $statements[0]);
$blueprint = new Blueprint('users');
$blueprint->id('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "foo" bigserial not null primary key', $statements[0]);
}
| |
192479
|
public function testAddingForeignID()
{
$blueprint = new Blueprint('users');
$foreignId = $blueprint->foreignId('foo');
$blueprint->foreignId('company_id')->constrained();
$blueprint->foreignId('laravel_idea_id')->constrained();
$blueprint->foreignId('team_id')->references('id')->on('teams');
$blueprint->foreignId('team_column_id')->constrained('teams');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertInstanceOf(ForeignIdColumnDefinition::class, $foreignId);
$this->assertSame([
'alter table "users" add column "foo" bigint not null',
'alter table "users" add column "company_id" bigint not null',
'alter table "users" add constraint "users_company_id_foreign" foreign key ("company_id") references "companies" ("id")',
'alter table "users" add column "laravel_idea_id" bigint not null',
'alter table "users" add constraint "users_laravel_idea_id_foreign" foreign key ("laravel_idea_id") references "laravel_ideas" ("id")',
'alter table "users" add column "team_id" bigint not null',
'alter table "users" add constraint "users_team_id_foreign" foreign key ("team_id") references "teams" ("id")',
'alter table "users" add column "team_column_id" bigint not null',
'alter table "users" add constraint "users_team_column_id_foreign" foreign key ("team_column_id") references "teams" ("id")',
], $statements);
}
public function testAddingForeignIdSpecifyingIndexNameInConstraint()
{
$blueprint = new Blueprint('users');
$blueprint->foreignId('company_id')->constrained(indexName: 'my_index');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertSame([
'alter table "users" add column "company_id" bigint not null',
'alter table "users" add constraint "my_index" foreign key ("company_id") references "companies" ("id")',
], $statements);
}
public function testAddingBigIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->bigIncrements('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "id" bigserial not null primary key', $statements[0]);
}
public function testAddingString()
{
$blueprint = new Blueprint('users');
$blueprint->string('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('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->assertSame('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->assertSame('alter table "users" add column "foo" varchar(100) null default \'bar\'', $statements[0]);
}
public function testAddingStringWithoutLengthLimit()
{
$blueprint = new Blueprint('users');
$blueprint->string('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "foo" varchar(255) not null', $statements[0]);
Builder::$defaultStringLength = null;
$blueprint = new Blueprint('users');
$blueprint->string('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
try {
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "foo" varchar not null', $statements[0]);
} finally {
Builder::$defaultStringLength = 255;
}
}
public function testAddingCharWithoutLengthLimit()
{
$blueprint = new Blueprint('users');
$blueprint->char('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "foo" char(255) not null', $statements[0]);
Builder::$defaultStringLength = null;
$blueprint = new Blueprint('users');
$blueprint->char('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
try {
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "foo" char not null', $statements[0]);
} finally {
Builder::$defaultStringLength = 255;
}
}
public function testAddingText()
{
$blueprint = new Blueprint('users');
$blueprint->text('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('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->assertSame('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->assertSame('alter table "users" add column "foo" bigserial not null 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->assertSame('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->assertSame('alter table "users" add column "foo" serial not null 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->assertSame('alter table "users" add column "foo" integer not null', $statements[0]);
$blueprint = new Blueprint('users');
$blueprint->mediumInteger('foo', true);
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add column "foo" serial not null primary key', $statements[0]);
}
| |
192488
|
public function testLazyByIdWithLastChunkComplete()
{
$builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
$builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
$chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
$chunk2 = new Collection([(object) ['someIdField' => 10], (object) ['someIdField' => 11]]);
$chunk3 = new Collection([]);
$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);
$this->assertEquals(
[
(object) ['someIdField' => 1],
(object) ['someIdField' => 2],
(object) ['someIdField' => 10],
(object) ['someIdField' => 11],
],
$builder->lazyById(2, 'someIdField')->all()
);
}
public function testLazyByIdWithLastChunkPartial()
{
$builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
$builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
$chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
$chunk2 = new Collection([(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);
$this->assertEquals(
[
(object) ['someIdField' => 1],
(object) ['someIdField' => 2],
(object) ['someIdField' => 10],
],
$builder->lazyById(2, 'someIdField')->all()
);
}
public function testLazyByIdIsLazy()
{
$builder = m::mock(Builder::class.'[forPageAfterId,get]', [$this->getMockQueryBuilder()]);
$builder->getQuery()->orders[] = ['column' => 'foobar', 'direction' => 'asc'];
$chunk1 = new Collection([(object) ['someIdField' => 1], (object) ['someIdField' => 2]]);
$builder->shouldReceive('forPageAfterId')->once()->with(2, 0, 'someIdField')->andReturnSelf();
$builder->shouldReceive('get')->once()->andReturn($chunk1);
$this->assertEquals(
[
(object) ['someIdField' => 1],
(object) ['someIdField' => 2],
],
$builder->lazyById(2, 'someIdField')->take(2)->all()
);
}
public function testPluckReturnsTheMutatedAttributesOfAModel()
{
$builder = $this->getBuilder();
$builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz']));
$builder->setModel($this->getMockModel());
$builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(true);
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'bar']));
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'baz']));
$this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name')->all());
}
public function testPluckReturnsTheCastedAttributesOfAModel()
{
$builder = $this->getBuilder();
$builder->getQuery()->shouldReceive('pluck')->with('name', '')->andReturn(new BaseCollection(['bar', 'baz']));
$builder->setModel($this->getMockModel());
$builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(false);
$builder->getModel()->shouldReceive('hasCast')->with('name')->andReturn(true);
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'bar']));
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'baz']));
$this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck('name')->all());
}
public function testPluckReturnsTheDateAttributesOfAModel()
{
$builder = $this->getBuilder();
$builder->getQuery()->shouldReceive('pluck')->with('created_at', '')->andReturn(new BaseCollection(['2010-01-01 00:00:00', '2011-01-01 00:00:00']));
$builder->setModel($this->getMockModel());
$builder->getModel()->shouldReceive('hasGetMutator')->with('created_at')->andReturn(false);
$builder->getModel()->shouldReceive('hasCast')->with('created_at')->andReturn(false);
$builder->getModel()->shouldReceive('getDates')->andReturn(['created_at']);
$builder->getModel()->shouldReceive('newFromBuilder')->with(['created_at' => '2010-01-01 00:00:00'])->andReturn(new EloquentBuilderTestPluckDatesStub(['created_at' => '2010-01-01 00:00:00']));
$builder->getModel()->shouldReceive('newFromBuilder')->with(['created_at' => '2011-01-01 00:00:00'])->andReturn(new EloquentBuilderTestPluckDatesStub(['created_at' => '2011-01-01 00:00:00']));
$this->assertEquals(['date_2010-01-01 00:00:00', 'date_2011-01-01 00:00:00'], $builder->pluck('created_at')->all());
}
public function testQualifiedPluckReturnsTheMutatedAttributesOfAModel()
{
$model = $this->getMockModel();
$model->shouldReceive('qualifyColumn')->with('name')->andReturn('foo_table.name');
$builder = $this->getBuilder();
$builder->getQuery()->shouldReceive('pluck')->with($model->qualifyColumn('name'), '')->andReturn(new BaseCollection(['bar', 'baz']));
$builder->setModel($model);
$builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(true);
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'bar']));
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'baz']));
$this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck($model->qualifyColumn('name'))->all());
}
public function testQualifiedPluckReturnsTheCastedAttributesOfAModel()
{
$model = $this->getMockModel();
$model->shouldReceive('qualifyColumn')->with('name')->andReturn('foo_table.name');
$builder = $this->getBuilder();
$builder->getQuery()->shouldReceive('pluck')->with($model->qualifyColumn('name'), '')->andReturn(new BaseCollection(['bar', 'baz']));
$builder->setModel($model);
$builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(false);
$builder->getModel()->shouldReceive('hasCast')->with('name')->andReturn(true);
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'bar'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'bar']));
$builder->getModel()->shouldReceive('newFromBuilder')->with(['name' => 'baz'])->andReturn(new EloquentBuilderTestPluckStub(['name' => 'baz']));
$this->assertEquals(['foo_bar', 'foo_baz'], $builder->pluck($model->qualifyColumn('name'))->all());
}
| |
192494
|
public function testWithExistsAndGlobalScope()
{
$model = new EloquentBuilderTestModelParentStub;
EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withExists', function ($query) {
return $query->addSelect('id');
});
$builder = $model->select('id')->withExists(['foo']);
// Remove the global scope so it doesn't interfere with any other tests
EloquentBuilderTestModelCloseRelatedStub::addGlobalScope('withExists', function ($query) {
//
});
$this->assertSame('select "id", exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}
public function testWithExistsOnBelongsToMany()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->withExists('roles');
$this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_far_related_stubs" inner join "user_role" on "eloquent_builder_test_model_far_related_stubs"."id" = "user_role"."related_id" where "eloquent_builder_test_model_parent_stubs"."id" = "user_role"."self_id") as "roles_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}
public function testWithExistsOnSelfRelated()
{
$model = new EloquentBuilderTestModelSelfRelatedStub;
$sql = $model->withExists('childFoos')->toSql();
// alias has a dynamic hash, so replace with a static string for comparison
$alias = 'self_alias_hash';
$aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
$sql = preg_replace($aliasRegex, $alias, $sql);
$this->assertSame('select "self_related_stubs".*, exists(select * from "self_related_stubs" as "self_alias_hash" where "self_related_stubs"."id" = "self_alias_hash"."parent_id") as "child_foos_exists" from "self_related_stubs"', $sql);
}
public function testWithExistsAndRename()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->withExists('foo as foo_bar');
$this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}
public function testWithExistsMultipleAndPartialRename()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->withExists(['foo as foo_bar', 'foo']);
$this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_bar", exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
}
public function testHasWithConstraintsAndHavingInSubquery()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('bar', 'baz');
$builder->whereHas('foo', function ($q) {
$q->having('bam', '>', 'qux');
})->where('quux', 'quuux');
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" having "bam" > ?) and "quux" = ?', $builder->toSql());
$this->assertEquals(['baz', 'qux', 'quuux'], $builder->getBindings());
}
public function testHasWithConstraintsWithOrWhereAndHavingInSubquery()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('name', 'larry');
$builder->whereHas('address', function ($q) {
$q->where('zipcode', '90210');
$q->orWhere('zipcode', '90220');
$q->having('street', '=', 'fooside dr');
})->where('age', 29);
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "name" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and ("zipcode" = ? or "zipcode" = ?) having "street" = ?) and "age" = ?', $builder->toSql());
$this->assertEquals(['larry', '90210', '90220', 'fooside dr', 29], $builder->getBindings());
}
public function testHasWithConstraintsWithOrWhereAndSubqueryInRelationFromClause()
{
EloquentBuilderTestModelParentStub::resolveRelationUsing('addressAsExpression', function ($model) {
return $model->address()->fromSub(EloquentBuilderTestModelCloseRelatedStub::query(), 'eloquent_builder_test_model_close_related_stubs');
});
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('name', 'larry');
$builder->whereHas('addressAsExpression', function ($q) {
$q->where('zipcode', '90210');
$q->orWhere('zipcode', '90220');
$q->having('street', '=', 'fooside dr');
})->where('age', 29);
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "name" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and ("zipcode" = ? or "zipcode" = ?) having "street" = ?) and "age" = ?', $builder->toSql());
$this->assertEquals(['larry', '90210', '90220', 'fooside dr', 29], $builder->getBindings());
}
public function testHasWithConstraintsAndJoinAndHavingInSubquery()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('bar', 'baz');
$builder->whereHas('foo', function ($q) {
$q->join('quuuux', function ($j) {
$j->where('quuuuux', '=', 'quuuuuux');
});
$q->having('bam', '>', 'qux');
})->where('quux', 'quuux');
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? and exists (select * from "eloquent_builder_test_model_close_related_stubs" inner join "quuuux" on "quuuuux" = ? where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" having "bam" > ?) and "quux" = ?', $builder->toSql());
$this->assertEquals(['baz', 'quuuuuux', 'qux', 'quuux'], $builder->getBindings());
}
| |
192495
|
public function testHasWithConstraintsAndHavingInSubqueryWithCount()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('bar', 'baz');
$builder->whereHas('foo', function ($q) {
$q->having('bam', '>', 'qux');
}, '>=', 2)->where('quux', 'quuux');
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? and (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" having "bam" > ?) >= 2 and "quux" = ?', $builder->toSql());
$this->assertEquals(['baz', 'qux', 'quuux'], $builder->getBindings());
}
public function testWithCountAndConstraintsWithBindingInSelectSub()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->newQuery();
$builder->withCount(['foo' => function ($q) use ($model) {
$q->selectSub($model->newQuery()->where('bam', '=', 3)->selectRaw('count(0)'), 'bam_3_count');
}]);
$this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, (select count(*) from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_count" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertSame([], $builder->getBindings());
}
public function testWithExistsAndConstraintsWithBindingInSelectSub()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->newQuery();
$builder->withExists(['foo' => function ($q) use ($model) {
$q->selectSub($model->newQuery()->where('bam', '=', 3)->selectRaw('count(0)'), 'bam_3_count');
}]);
$this->assertSame('select "eloquent_builder_test_model_parent_stubs".*, exists(select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id") as "foo_exists" from "eloquent_builder_test_model_parent_stubs"', $builder->toSql());
$this->assertSame([], $builder->getBindings());
}
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);
}
public function testOrHasNested()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->whereHas('foo', function ($q) {
$q->has('bar');
})->orWhereHas('foo', function ($q) {
$q->has('baz');
});
$result = $model->has('foo.bar')->orHas('foo.baz')->toSql();
$this->assertEquals($builder->toSql(), $result);
}
public function testSelfHasNested()
{
$model = new EloquentBuilderTestModelSelfRelatedStub;
$nestedSql = $model->whereHas('parentFoo', function ($q) {
$q->has('childFoo');
})->toSql();
$dotSql = $model->has('parentFoo.childFoo')->toSql();
// alias has a dynamic hash, so replace with a static string for comparison
$alias = 'self_alias_hash';
$aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
$nestedSql = preg_replace($aliasRegex, $alias, $nestedSql);
$dotSql = preg_replace($aliasRegex, $alias, $dotSql);
$this->assertEquals($nestedSql, $dotSql);
}
public function testSelfHasNestedUsesAlias()
{
$model = new EloquentBuilderTestModelSelfRelatedStub;
$sql = $model->has('parentFoo.childFoo')->toSql();
// alias has a dynamic hash, so replace with a static string for comparison
$alias = 'self_alias_hash';
$aliasRegex = '/\b(laravel_reserved_\d)(\b|$)/i';
$sql = preg_replace($aliasRegex, $alias, $sql);
$this->assertStringContainsString('"self_alias_hash"."id" = "self_related_stubs"."parent_id"', $sql);
}
public function testDoesntHave()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->doesntHave('foo');
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id")', $builder->toSql());
}
public function testDoesntHaveNested()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->doesntHave('foo.bar');
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and exists (select * from "eloquent_builder_test_model_far_related_stubs" where "eloquent_builder_test_model_close_related_stubs"."id" = "eloquent_builder_test_model_far_related_stubs"."eloquent_builder_test_model_close_related_stub_id"))', $builder->toSql());
}
public function testOrDoesntHave()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('bar', 'baz')->orDoesntHave('foo');
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? or not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id")', $builder->toSql());
$this->assertEquals(['baz'], $builder->getBindings());
}
public function testWhereDoesntHave()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->whereDoesntHave('foo', function ($query) {
$query->where('bar', 'baz');
});
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "bar" = ?)', $builder->toSql());
$this->assertEquals(['baz'], $builder->getBindings());
}
public function testOrWhereDoesntHave()
{
$model = new EloquentBuilderTestModelParentStub;
$builder = $model->where('bar', 'baz')->orWhereDoesntHave('foo', function ($query) {
$query->where('qux', 'quux');
});
$this->assertSame('select * from "eloquent_builder_test_model_parent_stubs" where "bar" = ? or not exists (select * from "eloquent_builder_test_model_close_related_stubs" where "eloquent_builder_test_model_parent_stubs"."foo_id" = "eloquent_builder_test_model_close_related_stubs"."id" and "qux" = ?)', $builder->toSql());
$this->assertEquals(['baz', 'quux'], $builder->getBindings());
}
| |
192526
|
public function testDropTableIfExists()
{
$blueprint = new Blueprint('users');
$blueprint->dropIfExists();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('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->assertSame('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->assertSame('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->assertSame('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->assertSame('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->assertSame('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->assertSame('alter table `users` drop index `foo`', $statements[0]);
}
public function testDropSpatialIndex()
{
$blueprint = new Blueprint('geo');
$blueprint->dropSpatialIndex(['coordinates']);
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `geo` drop index `geo_coordinates_spatialindex`', $statements[0]);
}
public function testDropForeign()
{
$blueprint = new Blueprint('users');
$blueprint->dropForeign('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('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->assertSame('alter table `users` drop `created_at`, drop `updated_at`', $statements[0]);
}
public function testDropTimestampsTz()
{
$blueprint = new Blueprint('users');
$blueprint->dropTimestampsTz();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `users` drop `created_at`, drop `updated_at`', $statements[0]);
}
public function testDropMorphs()
{
$blueprint = new Blueprint('photos');
$blueprint->dropMorphs('imageable');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(2, $statements);
$this->assertSame('alter table `photos` drop index `photos_imageable_type_imageable_id_index`', $statements[0]);
$this->assertSame('alter table `photos` drop `imageable_type`, drop `imageable_id`', $statements[1]);
}
public function testRenameTable()
{
$blueprint = new Blueprint('users');
$blueprint->rename('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('rename table `users` to `foo`', $statements[0]);
}
public function testRenameIndex()
{
$blueprint = new Blueprint('users');
$blueprint->renameIndex('foo', 'bar');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `users` rename index `foo` to `bar`', $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->assertSame('alter table `users` add primary key (`foo`)', $statements[0]);
}
public function testAddingPrimaryKeyWithAlgorithm()
{
$blueprint = new Blueprint('users');
$blueprint->primary('foo', 'bar', 'hash');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `users` add primary key using hash(`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->assertSame('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->assertSame('alter table `users` add index `baz`(`foo`, `bar`)', $statements[0]);
}
public function testAddingIndexWithAlgorithm()
{
$blueprint = new Blueprint('users');
$blueprint->index(['foo', 'bar'], 'baz', 'hash');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `users` add index `baz` using hash(`foo`, `bar`)', $statements[0]);
}
public function testAddingFulltextIndex()
{
$blueprint = new Blueprint('users');
$blueprint->fulltext('body');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `users` add fulltext `users_body_fulltext`(`body`)', $statements[0]);
}
public function testAddingSpatialIndex()
{
$blueprint = new Blueprint('geo');
$blueprint->spatialIndex('coordinates');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table `geo` add spatial index `geo_coordinates_spatialindex`(`coordinates`)', $statements[0]);
}
| |
192537
|
public function testDropTimestampsTz()
{
$blueprint = new Blueprint('users');
$blueprint->dropTimestampsTz();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertStringContainsString('alter table "users" drop column "created_at", "updated_at"', $statements[0]);
}
public function testDropMorphs()
{
$blueprint = new Blueprint('photos');
$blueprint->dropMorphs('imageable');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(2, $statements);
$this->assertSame('drop index "photos_imageable_type_imageable_id_index" on "photos"', $statements[0]);
$this->assertStringContainsString('alter table "photos" drop column "imageable_type", "imageable_id"', $statements[1]);
}
public function testRenameTable()
{
$blueprint = new Blueprint('users');
$blueprint->rename('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('sp_rename N\'"users"\', "foo"', $statements[0]);
}
public function testRenameIndex()
{
$blueprint = new Blueprint('users');
$blueprint->renameIndex('foo', 'bar');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('sp_rename N\'"users"."foo"\', "bar", N\'INDEX\'', $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->assertSame('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->assertSame('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->assertSame('create index "baz" on "users" ("foo", "bar")', $statements[0]);
}
public function testAddingSpatialIndex()
{
$blueprint = new Blueprint('geo');
$blueprint->spatialIndex('coordinates');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create spatial index "geo_coordinates_spatialindex" on "geo" ("coordinates")', $statements[0]);
}
public function testAddingFluentSpatialIndex()
{
$blueprint = new Blueprint('geo');
$blueprint->geometry('coordinates', 'point')->spatialIndex();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(2, $statements);
$this->assertSame('create spatial index "geo_coordinates_spatialindex" on "geo" ("coordinates")', $statements[1]);
}
public function testAddingRawIndex()
{
$blueprint = new Blueprint('users');
$blueprint->rawIndex('(function(column))', 'raw_index');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('create index "raw_index" on "users" ((function(column)))', $statements[0]);
}
public function testAddingIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->increments('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add "id" int not null identity primary key', $statements[0]);
}
public function testAddingSmallIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->smallIncrements('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add "id" smallint not null identity primary key', $statements[0]);
}
public function testAddingMediumIncrementingID()
{
$blueprint = new Blueprint('users');
$blueprint->mediumIncrements('id');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add "id" int not null identity primary key', $statements[0]);
}
public function testAddingID()
{
$blueprint = new Blueprint('users');
$blueprint->id();
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add "id" bigint not null identity primary key', $statements[0]);
$blueprint = new Blueprint('users');
$blueprint->id('foo');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertCount(1, $statements);
$this->assertSame('alter table "users" add "foo" bigint not null identity primary key', $statements[0]);
}
public function testAddingForeignID()
{
$blueprint = new Blueprint('users');
$foreignId = $blueprint->foreignId('foo');
$blueprint->foreignId('company_id')->constrained();
$blueprint->foreignId('laravel_idea_id')->constrained();
$blueprint->foreignId('team_id')->references('id')->on('teams');
$blueprint->foreignId('team_column_id')->constrained('teams');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertInstanceOf(ForeignIdColumnDefinition::class, $foreignId);
$this->assertSame([
'alter table "users" add "foo" bigint not null',
'alter table "users" add "company_id" bigint not null',
'alter table "users" add constraint "users_company_id_foreign" foreign key ("company_id") references "companies" ("id")',
'alter table "users" add "laravel_idea_id" bigint not null',
'alter table "users" add constraint "users_laravel_idea_id_foreign" foreign key ("laravel_idea_id") references "laravel_ideas" ("id")',
'alter table "users" add "team_id" bigint not null',
'alter table "users" add constraint "users_team_id_foreign" foreign key ("team_id") references "teams" ("id")',
'alter table "users" add "team_column_id" bigint not null',
'alter table "users" add constraint "users_team_column_id_foreign" foreign key ("team_column_id") references "teams" ("id")',
], $statements);
}
public function testAddingForeignIdSpecifyingIndexNameInConstraint()
{
$blueprint = new Blueprint('users');
$blueprint->foreignId('company_id')->constrained(indexName: 'my_index');
$statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
$this->assertSame([
'alter table "users" add "company_id" bigint not null',
'alter table "users" add constraint "my_index" foreign key ("company_id") references "companies" ("id")',
], $statements);
}
| |
192554
|
public function testNewQueryReturnsEloquentQueryBuilder()
{
$conn = m::mock(Connection::class);
$grammar = m::mock(Grammar::class);
$processor = m::mock(Processor::class);
EloquentModelStub::setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class));
$conn->shouldReceive('query')->andReturnUsing(function () use ($conn, $grammar, $processor) {
return new BaseBuilder($conn, $grammar, $processor);
});
$resolver->shouldReceive('connection')->andReturn($conn);
$model = new EloquentModelStub;
$builder = $model->newQuery();
$this->assertInstanceOf(Builder::class, $builder);
}
public function testGetAndSetTableOperations()
{
$model = new EloquentModelStub;
$this->assertSame('stub', $model->getTable());
$model->setTable('foo');
$this->assertSame('foo', $model->getTable());
}
public function testGetKeyReturnsValueOfPrimaryKey()
{
$model = new EloquentModelStub;
$model->id = 1;
$this->assertEquals(1, $model->getKey());
$this->assertSame('id', $model->getKeyName());
}
public function testConnectionManagement()
{
EloquentModelStub::setConnectionResolver($resolver = m::mock(ConnectionResolverInterface::class));
$model = m::mock(EloquentModelStub::class.'[getConnectionName,connection]');
$retval = $model->setConnection('foo');
$this->assertEquals($retval, $model);
$this->assertSame('foo', $model->connection);
$model->shouldReceive('getConnectionName')->once()->andReturn('somethingElse');
$resolver->shouldReceive('connection')->once()->with('somethingElse')->andReturn('bar');
$this->assertSame('bar', $model->getConnection());
}
public function testToArray()
{
$model = new EloquentModelStub;
$model->name = 'foo';
$model->age = null;
$model->password = 'password1';
$model->setHidden(['password']);
$model->setRelation('names', new BaseCollection([
new EloquentModelStub(['bar' => 'baz']), new EloquentModelStub(['bam' => 'boom']),
]));
$model->setRelation('partner', new EloquentModelStub(['name' => 'abby']));
$model->setRelation('group', null);
$model->setRelation('multi', new BaseCollection);
$array = $model->toArray();
$this->assertIsArray($array);
$this->assertSame('foo', $array['name']);
$this->assertSame('baz', $array['names'][0]['bar']);
$this->assertSame('boom', $array['names'][1]['bam']);
$this->assertSame('abby', $array['partner']['name']);
$this->assertNull($array['group']);
$this->assertEquals([], $array['multi']);
$this->assertFalse(isset($array['password']));
$model->setAppends(['appendable']);
$array = $model->toArray();
$this->assertSame('appended', $array['appendable']);
}
public function testToArrayWithCircularRelations()
{
$parent = new EloquentModelWithRecursiveRelationshipsStub(['id' => 1, 'parent_id' => null]);
$lastId = $parent->id;
$parent->setRelation('self', $parent);
$children = new Collection();
for ($count = 0; $count < 2; $count++) {
$child = new EloquentModelWithRecursiveRelationshipsStub(['id' => ++$lastId, 'parent_id' => $parent->id]);
$child->setRelation('parent', $parent);
$child->setRelation('self', $child);
$children->push($child);
}
$parent->setRelation('children', $children);
try {
$this->assertSame(
[
'id' => 1,
'parent_id' => null,
'self' => ['id' => 1, 'parent_id' => null],
'children' => [
[
'id' => 2,
'parent_id' => 1,
'parent' => ['id' => 1, 'parent_id' => null],
'self' => ['id' => 2, 'parent_id' => 1],
],
[
'id' => 3,
'parent_id' => 1,
'parent' => ['id' => 1, 'parent_id' => null],
'self' => ['id' => 3, 'parent_id' => 1],
],
],
],
$parent->toArray()
);
} catch (\RuntimeException $e) {
$this->fail($e->getMessage());
}
}
public function testGetQueueableRelationsWithCircularRelations()
{
$parent = new EloquentModelWithRecursiveRelationshipsStub(['id' => 1, 'parent_id' => null]);
$lastId = $parent->id;
$parent->setRelation('self', $parent);
$children = new Collection();
for ($count = 0; $count < 2; $count++) {
$child = new EloquentModelWithRecursiveRelationshipsStub(['id' => ++$lastId, 'parent_id' => $parent->id]);
$child->setRelation('parent', $parent);
$child->setRelation('self', $child);
$children->push($child);
}
$parent->setRelation('children', $children);
try {
$this->assertSame(
[
'self',
'children',
'children.parent',
'children.self',
],
$parent->getQueueableRelations()
);
} catch (\RuntimeException $e) {
$this->fail($e->getMessage());
}
}
public function testVisibleCreatesArrayWhitelist()
{
$model = new EloquentModelStub;
$model->setVisible(['name']);
$model->name = 'Taylor';
$model->age = 26;
$array = $model->toArray();
$this->assertEquals(['name' => 'Taylor'], $array);
}
public function testHiddenCanAlsoExcludeRelationships()
{
$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 testGetArrayableRelationsFunctionExcludeHiddenRelationships()
{
$model = new EloquentModelStub;
$class = new ReflectionClass($model);
$method = $class->getMethod('getArrayableRelations');
$model->setRelation('foo', ['bar']);
$model->setRelation('bam', ['boom']);
$model->setHidden(['foo']);
$array = $method->invokeArgs($model, []);
$this->assertSame(['bam' => ['boom']], $array);
}
public function testToArraySnakeAttributes()
{
$model = new EloquentModelStub;
$model->setRelation('namesList', new BaseCollection([
new EloquentModelStub(['bar' => 'baz']), new EloquentModelStub(['bam' => 'boom']),
]));
$array = $model->toArray();
$this->assertSame('baz', $array['names_list'][0]['bar']);
$this->assertSame('boom', $array['names_list'][1]['bam']);
$model = new EloquentModelCamelStub;
$model->setRelation('namesList', new BaseCollection([
new EloquentModelStub(['bar' => 'baz']), new EloquentModelStub(['bam' => 'boom']),
]));
$array = $model->toArray();
$this->assertSame('baz', $array['namesList'][0]['bar']);
$this->assertSame('boom', $array['namesList'][1]['bam']);
}
public function testToArrayUsesMutators()
{
$model = new EloquentModelStub;
$model->list_items = [1, 2, 3];
$array = $model->toArray();
$this->assertEquals([1, 2, 3], $array['list_items']);
}
public function testHidden()
{
$model = new EloquentModelStub(['name' => 'foo', 'age' => 'bar', 'id' => 'baz']);
$model->setHidden(['age', 'id']);
$array = $model->toArray();
$this->assertArrayHasKey('name', $array);
$this->assertArrayNotHasKey('age', $array);
}
| |
192565
|
class EloquentModelDestroyStub extends Model
{
protected $fillable = [
'id',
];
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::class)]);
$model->shouldReceive('delete')->once();
return $mock;
}
}
class EloquentModelEmptyDestroyStub extends Model
{
public function newQuery()
{
$mock = m::mock(Builder::class);
$mock->shouldReceive('whereIn')->never();
return $mock;
}
}
class EloquentModelWithStub extends Model
{
public function newQuery()
{
$mock = m::mock(Builder::class);
$mock->shouldReceive('with')->once()->with(['foo', 'bar'])->andReturn('foo');
return $mock;
}
}
class EloquentModelWithWhereHasStub extends Model
{
public function foo()
{
return $this->hasMany(EloquentModelStub::class);
}
}
class EloquentModelWithoutRelationStub extends Model
{
public $with = ['foo'];
protected $guarded = [];
public function getEagerLoads()
{
return $this->eagerLoads;
}
}
class EloquentModelWithoutTableStub extends Model
{
//
}
class EloquentModelBootingTestStub extends Model
{
public static function unboot()
{
unset(static::$booted[static::class]);
}
public static function isBooted()
{
return array_key_exists(static::class, static::$booted);
}
}
class EloquentModelAppendsStub extends Model
{
protected $appends = ['is_admin', 'camelCased', 'StudlyCased'];
public function getIsAdminAttribute()
{
return 'admin';
}
public function getCamelCasedAttribute()
{
return 'camelCased';
}
public function getStudlyCasedAttribute()
{
return 'StudlyCased';
}
}
class EloquentModelGetMutatorsStub extends Model
{
public static function resetMutatorCache()
{
static::$mutatorCache = [];
}
public function getFirstNameAttribute()
{
//
}
public function getMiddleNameAttribute()
{
//
}
public function getLastNameAttribute()
{
//
}
public function doNotgetFirstInvalidAttribute()
{
//
}
public function doNotGetSecondInvalidAttribute()
{
//
}
public function doNotgetThirdInvalidAttributeEither()
{
//
}
public function doNotGetFourthInvalidAttributeEither()
{
//
}
}
class EloquentModelCastingStub extends Model
{
protected $casts = [
'floatAttribute' => 'float',
'boolAttribute' => 'bool',
'objectAttribute' => 'object',
'jsonAttribute' => 'json',
'dateAttribute' => 'date',
'timestampAttribute' => 'timestamp',
'ascollectionAttribute' => AsCollection::class,
'asCustomCollectionAsArrayAttribute' => [AsCollection::class, CustomCollection::class],
'asEncryptedCollectionAttribute' => AsEncryptedCollection::class,
'asEnumCollectionAttribute' => AsEnumCollection::class.':'.StringStatus::class,
'asEnumArrayObjectAttribute' => AsEnumArrayObject::class.':'.StringStatus::class,
'duplicatedAttribute' => 'string',
];
protected function casts(): array
{
return [
'intAttribute' => 'int',
'stringAttribute' => 'string',
'booleanAttribute' => 'boolean',
'arrayAttribute' => 'array',
'collectionAttribute' => 'collection',
'datetimeAttribute' => 'datetime',
'asarrayobjectAttribute' => AsArrayObject::class,
'asStringableAttribute' => AsStringable::class,
'asCustomCollectionAttribute' => AsCollection::using(CustomCollection::class),
'asEncryptedArrayObjectAttribute' => AsEncryptedArrayObject::class,
'asEncryptedCustomCollectionAttribute' => AsEncryptedCollection::using(CustomCollection::class),
'asEncryptedCustomCollectionAsArrayAttribute' => [AsEncryptedCollection::class, CustomCollection::class],
'asCustomEnumCollectionAttribute' => AsEnumCollection::of(StringStatus::class),
'asCustomEnumArrayObjectAttribute' => AsEnumArrayObject::of(StringStatus::class),
'singleElementInArrayAttribute' => [AsCollection::class],
'duplicatedAttribute' => 'int',
];
}
public function jsonAttributeValue()
{
return $this->attributes['jsonAttribute'];
}
protected function serializeDate(DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
}
class EloquentModelEnumCastingStub extends Model
{
protected $casts = ['enumAttribute' => StringStatus::class];
}
class EloquentModelDynamicHiddenStub extends Model
{
protected $table = 'stub';
protected $guarded = [];
public function getHidden()
{
return ['age', 'id'];
}
}
class EloquentModelDynamicVisibleStub extends Model
{
protected $table = 'stub';
protected $guarded = [];
public function getVisible()
{
return ['name', 'id'];
}
}
class EloquentModelNonIncrementingStub extends Model
{
protected $table = 'stub';
protected $guarded = [];
public $incrementing = false;
}
class EloquentNoConnectionModelStub extends EloquentModelStub
{
//
}
class EloquentDifferentConnectionModelStub extends EloquentModelStub
{
public $connection = 'different_connection';
}
class EloquentPrimaryUuidModelStub extends EloquentModelStub
{
use HasUuids;
public $incrementing = false;
protected $keyType = 'string';
public function getKeyName()
{
return 'uuid';
}
}
class EloquentNonPrimaryUuidModelStub extends EloquentModelStub
{
use HasUuids;
public function getKeyName()
{
return 'id';
}
public function uniqueIds()
{
return ['uuid'];
}
}
class EloquentPrimaryUlidModelStub extends EloquentModelStub
{
use HasUlids;
public $incrementing = false;
protected $keyType = 'string';
public function getKeyName()
{
return 'ulid';
}
}
class EloquentNonPrimaryUlidModelStub extends EloquentModelStub
{
use HasUlids;
public function getKeyName()
{
return 'id';
}
public function uniqueIds()
{
return ['ulid'];
}
}
#[ObservedBy(EloquentTestObserverStub::class)]
class EloquentModelWithObserveAttributeStub extends EloquentModelStub
{
//
}
#[ObservedBy([EloquentTestObserverStub::class])]
class EloquentModelWithObserveAttributeUsingArrayStub extends EloquentModelStub
{
//
}
class EloquentModelSavingEventStub
{
//
}
class EloquentModelEventObjectStub extends Model
{
protected $dispatchesEvents = [
'saving' => EloquentModelSavingEventStub::class,
];
}
class EloquentModelWithoutTimestamps extends Model
{
protected $table = 'stub';
public $timestamps = false;
}
class EloquentModelWithUpdatedAtNull extends Model
{
protected $table = 'stub';
const UPDATED_AT = null;
}
class UnsavedModel extends Model
{
protected $casts = ['name' => Uppercase::class];
}
class Uppercase implements CastsInboundAttributes
{
public function set($model, string $key, $value, array $attributes)
{
return is_string($value) ? strtoupper($value) : $value;
}
}
class CustomCollection extends BaseCollection
{
//
}
class EloquentModelWithPrimitiveCasts extends Model
{
public $fillable = ['id'];
public $casts = [
'backed_enum' => CastableBackedEnum::class,
'address' => Address::class,
];
public $attributes = [
'address_line_one' => null,
'address_line_two' => null,
];
public static function makePrimitiveCastsArray(): array
{
$toReturn = [];
foreach (static::$primitiveCastTypes as $index => $primitiveCastType) {
$toReturn['primitive_cast_'.$index] = $primitiveCastType;
}
return $toReturn;
}
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->mergeCasts(self::makePrimitiveCastsArray());
}
public function getThisIsFineAttribute($value)
{
return 'ok';
}
public function thisIsAlsoFine(): Attribute
{
return Attribute::get(fn () => 'ok');
}
}
| |
192576
|
public function testWhereIntegerInRaw()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereIntegerInRaw('id', [
'1a', 2, Bar::FOO,
]);
$this->assertSame('select * from "users" where "id" in (1, 2, 5)', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereIntegerInRaw('id', [
['id' => '1a'],
['id' => 2],
['any' => '3'],
['id' => Bar::FOO],
]);
$this->assertSame('select * from "users" where "id" in (1, 2, 3, 5)', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
}
public function testOrWhereIntegerInRaw()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('id', '=', 1)->orWhereIntegerInRaw('id', ['1a', 2]);
$this->assertSame('select * from "users" where "id" = ? or "id" in (1, 2)', $builder->toSql());
$this->assertEquals([0 => 1], $builder->getBindings());
}
public function testWhereIntegerNotInRaw()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereIntegerNotInRaw('id', ['1a', 2]);
$this->assertSame('select * from "users" where "id" not in (1, 2)', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
}
public function testOrWhereIntegerNotInRaw()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('id', '=', 1)->orWhereIntegerNotInRaw('id', ['1a', 2]);
$this->assertSame('select * from "users" where "id" = ? or "id" not in (1, 2)', $builder->toSql());
$this->assertEquals([0 => 1], $builder->getBindings());
}
public function testEmptyWhereIntegerInRaw()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereIntegerInRaw('id', []);
$this->assertSame('select * from "users" where 0 = 1', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
}
public function testEmptyWhereIntegerNotInRaw()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereIntegerNotInRaw('id', []);
$this->assertSame('select * from "users" where 1 = 1', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
}
public function testBasicWhereColumn()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn('first_name', 'last_name')->orWhereColumn('first_name', 'middle_name');
$this->assertSame('select * from "users" where "first_name" = "last_name" or "first_name" = "middle_name"', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn('updated_at', '>', 'created_at');
$this->assertSame('select * from "users" where "updated_at" > "created_at"', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
}
public function testArrayWhereColumn()
{
$conditions = [
['first_name', 'last_name'],
['updated_at', '>', 'created_at'],
];
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn($conditions);
$this->assertSame('select * from "users" where ("first_name" = "last_name" and "updated_at" > "created_at")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
}
public function testWhereFulltextMySql()
{
$builder = $this->getMySqlBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World');
$this->assertSame('select * from `users` where match (`body`) against (? in natural language mode)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getMySqlBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World', ['expanded' => true]);
$this->assertSame('select * from `users` where match (`body`) against (? in natural language mode with query expansion)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getMySqlBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', '+Hello -World', ['mode' => 'boolean']);
$this->assertSame('select * from `users` where match (`body`) against (? in boolean mode)', $builder->toSql());
$this->assertEquals(['+Hello -World'], $builder->getBindings());
$builder = $this->getMySqlBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', '+Hello -World', ['mode' => 'boolean', 'expanded' => true]);
$this->assertSame('select * from `users` where match (`body`) against (? in boolean mode)', $builder->toSql());
$this->assertEquals(['+Hello -World'], $builder->getBindings());
$builder = $this->getMySqlBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext(['body', 'title'], 'Car,Plane');
$this->assertSame('select * from `users` where match (`body`, `title`) against (? in natural language mode)', $builder->toSql());
$this->assertEquals(['Car,Plane'], $builder->getBindings());
}
| |
192577
|
public function testWhereFulltextPostgres()
{
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World');
$this->assertSame('select * from "users" where (to_tsvector(\'english\', "body")) @@ plainto_tsquery(\'english\', ?)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World', ['language' => 'simple']);
$this->assertSame('select * from "users" where (to_tsvector(\'simple\', "body")) @@ plainto_tsquery(\'simple\', ?)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World', ['mode' => 'plain']);
$this->assertSame('select * from "users" where (to_tsvector(\'english\', "body")) @@ plainto_tsquery(\'english\', ?)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World', ['mode' => 'phrase']);
$this->assertSame('select * from "users" where (to_tsvector(\'english\', "body")) @@ phraseto_tsquery(\'english\', ?)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', '+Hello -World', ['mode' => 'websearch']);
$this->assertSame('select * from "users" where (to_tsvector(\'english\', "body")) @@ websearch_to_tsquery(\'english\', ?)', $builder->toSql());
$this->assertEquals(['+Hello -World'], $builder->getBindings());
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext('body', 'Hello World', ['language' => 'simple', 'mode' => 'plain']);
$this->assertSame('select * from "users" where (to_tsvector(\'simple\', "body")) @@ plainto_tsquery(\'simple\', ?)', $builder->toSql());
$this->assertEquals(['Hello World'], $builder->getBindings());
$builder = $this->getPostgresBuilderWithProcessor();
$builder->select('*')->from('users')->whereFulltext(['body', 'title'], 'Car Plane');
$this->assertSame('select * from "users" where (to_tsvector(\'english\', "body") || to_tsvector(\'english\', "title")) @@ plainto_tsquery(\'english\', ?)', $builder->toSql());
$this->assertEquals(['Car Plane'], $builder->getBindings());
}
public function testWhereAll()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAll(['last_name', 'email'], '%Otwell%');
$this->assertSame('select * from "users" where ("last_name" = ? and "email" = ?)', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAll(['last_name', 'email'], 'not like', '%Otwell%');
$this->assertSame('select * from "users" where ("last_name" not like ? and "email" not like ?)', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAll([
fn (Builder $query) => $query->where('last_name', 'like', '%Otwell%'),
fn (Builder $query) => $query->where('email', 'like', '%Otwell%'),
]);
$this->assertSame('select * from "users" where (("last_name" like ?) and ("email" like ?))', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
}
public function testOrWhereAll()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereAll(['last_name', 'email'], 'like', '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? or ("last_name" like ? and "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->whereAll(['last_name', 'email'], 'like', '%Otwell%', 'or');
$this->assertSame('select * from "users" where "first_name" like ? or ("last_name" like ? and "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereAll(['last_name', 'email'], '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? or ("last_name" = ? and "email" = ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereAll([
fn (Builder $query) => $query->where('last_name', 'like', '%Otwell%'),
fn (Builder $query) => $query->where('email', 'like', '%Otwell%'),
]);
$this->assertSame('select * from "users" where "first_name" like ? or (("last_name" like ?) and ("email" like ?))', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
}
public function testWhereAny()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAny(['last_name', 'email'], 'like', '%Otwell%');
$this->assertSame('select * from "users" where ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAny(['last_name', 'email'], '%Otwell%');
$this->assertSame('select * from "users" where ("last_name" = ? or "email" = ?)', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAny([
fn (Builder $query) => $query->where('last_name', 'like', '%Otwell%'),
fn (Builder $query) => $query->where('email', 'like', '%Otwell%'),
]);
$this->assertSame('select * from "users" where (("last_name" like ?) or ("email" like ?))', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
}
| |
192578
|
public function testOrWhereAny()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereAny(['last_name', 'email'], 'like', '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? or ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->whereAny(['last_name', 'email'], 'like', '%Otwell%', 'or');
$this->assertSame('select * from "users" where "first_name" like ? or ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereAny(['last_name', 'email'], '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? or ("last_name" = ? or "email" = ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereAny([
fn (Builder $query) => $query->where('last_name', 'like', '%Otwell%'),
fn (Builder $query) => $query->where('email', 'like', '%Otwell%'),
]);
$this->assertSame('select * from "users" where "first_name" like ? or (("last_name" like ?) or ("email" like ?))', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
}
public function testWhereNone()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNone(['last_name', 'email'], 'like', '%Otwell%');
$this->assertSame('select * from "users" where not ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNone(['last_name', 'email'], 'Otwell');
$this->assertSame('select * from "users" where not ("last_name" = ? or "email" = ?)', $builder->toSql());
$this->assertEquals(['Otwell', 'Otwell'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->whereNone(['last_name', 'email'], 'like', '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? and not ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNone([
fn (Builder $query) => $query->where('last_name', 'like', '%Otwell%'),
fn (Builder $query) => $query->where('email', 'like', '%Otwell%'),
]);
$this->assertSame('select * from "users" where not (("last_name" like ?) or ("email" like ?))', $builder->toSql());
$this->assertEquals(['%Otwell%', '%Otwell%'], $builder->getBindings());
}
public function testOrWhereNone()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereNone(['last_name', 'email'], 'like', '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? or not ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->whereNone(['last_name', 'email'], 'like', '%Otwell%', 'or');
$this->assertSame('select * from "users" where "first_name" like ? or not ("last_name" like ? or "email" like ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereNone(['last_name', 'email'], '%Otwell%');
$this->assertSame('select * from "users" where "first_name" like ? or not ("last_name" = ? or "email" = ?)', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('first_name', 'like', '%Taylor%')->orWhereNone([
fn (Builder $query) => $query->where('last_name', 'like', '%Otwell%'),
fn (Builder $query) => $query->where('email', 'like', '%Otwell%'),
]);
$this->assertSame('select * from "users" where "first_name" like ? or not (("last_name" like ?) or ("email" like ?))', $builder->toSql());
$this->assertEquals(['%Taylor%', '%Otwell%', '%Otwell%'], $builder->getBindings());
}
| |
192582
|
public function testLatest()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->latest();
$this->assertSame('select * from "users" order by "created_at" desc', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->latest()->limit(1);
$this->assertSame('select * from "users" order by "created_at" desc limit 1', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->latest('updated_at');
$this->assertSame('select * from "users" order by "updated_at" desc', $builder->toSql());
}
public function testOldest()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->oldest();
$this->assertSame('select * from "users" order by "created_at" asc', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->oldest()->limit(1);
$this->assertSame('select * from "users" order by "created_at" asc limit 1', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->oldest('updated_at');
$this->assertSame('select * from "users" order by "updated_at" asc', $builder->toSql());
}
public function testInRandomOrderMySql()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->inRandomOrder();
$this->assertSame('select * from "users" order by RANDOM()', $builder->toSql());
}
public function testInRandomOrderPostgres()
{
$builder = $this->getPostgresBuilder();
$builder->select('*')->from('users')->inRandomOrder();
$this->assertSame('select * from "users" order by RANDOM()', $builder->toSql());
}
public function testInRandomOrderSqlServer()
{
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->inRandomOrder();
$this->assertSame('select * from [users] order by NEWID()', $builder->toSql());
}
public function testOrderBysSqlServer()
{
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->orderBy('email')->orderBy('age', 'desc');
$this->assertSame('select * from [users] order by [email] asc, [age] desc', $builder->toSql());
$builder->orders = null;
$this->assertSame('select * from [users]', $builder->toSql());
$builder->orders = [];
$this->assertSame('select * from [users]', $builder->toSql());
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->orderBy('email');
$this->assertSame('select * from [users] order by [email] asc', $builder->toSql());
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->orderByDesc('name');
$this->assertSame('select * from [users] order by [name] desc', $builder->toSql());
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->orderByRaw('[age] asc');
$this->assertSame('select * from [users] order by [age] asc', $builder->toSql());
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->orderBy('email')->orderByRaw('[age] ? desc', ['foo']);
$this->assertSame('select * from [users] order by [email] asc, [age] ? desc', $builder->toSql());
$this->assertEquals(['foo'], $builder->getBindings());
$builder = $this->getSqlServerBuilder();
$builder->select('*')->from('users')->skip(25)->take(10)->orderByRaw('[email] desc');
$this->assertSame('select * from [users] order by [email] desc offset 25 rows fetch next 10 rows only', $builder->toSql());
}
public function testReorder()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->orderBy('name');
$this->assertSame('select * from "users" order by "name" asc', $builder->toSql());
$builder->reorder();
$this->assertSame('select * from "users"', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->orderBy('name');
$this->assertSame('select * from "users" order by "name" asc', $builder->toSql());
$builder->reorder('email', 'desc');
$this->assertSame('select * from "users" order by "email" desc', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('first');
$builder->union($this->getBuilder()->select('*')->from('second'));
$builder->orderBy('name');
$this->assertSame('(select * from "first") union (select * from "second") order by "name" asc', $builder->toSql());
$builder->reorder();
$this->assertSame('(select * from "first") union (select * from "second")', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->orderByRaw('?', [true]);
$this->assertEquals([true], $builder->getBindings());
$builder->reorder();
$this->assertEquals([], $builder->getBindings());
}
public function testOrderBySubQueries()
{
$expected = 'select * from "users" order by (select "created_at" from "logins" where "user_id" = "users"."id" limit 1)';
$subQuery = function ($query) {
return $query->select('created_at')->from('logins')->whereColumn('user_id', 'users.id')->limit(1);
};
$builder = $this->getBuilder()->select('*')->from('users')->orderBy($subQuery);
$this->assertSame("$expected asc", $builder->toSql());
$builder = $this->getBuilder()->select('*')->from('users')->orderBy($subQuery, 'desc');
$this->assertSame("$expected desc", $builder->toSql());
$builder = $this->getBuilder()->select('*')->from('users')->orderByDesc($subQuery);
$this->assertSame("$expected desc", $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('posts')->where('public', 1)
->unionAll($this->getBuilder()->select('*')->from('videos')->where('public', 1))
->orderBy($this->getBuilder()->selectRaw('field(category, ?, ?)', ['news', 'opinion']));
$this->assertSame('(select * from "posts" where "public" = ?) union all (select * from "videos" where "public" = ?) order by (select field(category, ?, ?)) asc', $builder->toSql());
$this->assertEquals([1, 1, 'news', 'opinion'], $builder->getBindings());
}
public function testOrderByInvalidDirectionParam()
{
$this->expectException(InvalidArgumentException::class);
$builder = $this->getBuilder();
$builder->select('*')->from('users')->orderBy('age', 'asec');
}
| |
192583
|
public function testHavings()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->having('email', '>', 1);
$this->assertSame('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->assertSame('select * from "users" having "email" = ? or "email" = ?', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->groupBy('email')->having('email', '>', 1);
$this->assertSame('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->assertSame('select "email" as "foo_email" from "users" having "foo_email" > ?', $builder->toSql());
$builder = $this->getBuilder();
$builder->select(['category', new Raw('count(*) as "total"')])->from('item')->where('department', '=', 'popular')->groupBy('category')->having('total', '>', new Raw('3'));
$this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" > 3', $builder->toSql());
$builder = $this->getBuilder();
$builder->select(['category', new Raw('count(*) as "total"')])->from('item')->where('department', '=', 'popular')->groupBy('category')->having('total', '>', 3);
$this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" > ?', $builder->toSql());
}
public function testNestedHavings()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->having('email', '=', 'foo')->orHaving(function ($q) {
$q->having('name', '=', 'bar')->having('age', '=', 25);
});
$this->assertSame('select * from "users" having "email" = ? or ("name" = ? and "age" = ?)', $builder->toSql());
$this->assertEquals([0 => 'foo', 1 => 'bar', 2 => 25], $builder->getBindings());
}
public function testNestedHavingBindings()
{
$builder = $this->getBuilder();
$builder->having('email', '=', 'foo')->having(function ($q) {
$q->selectRaw('?', ['ignore'])->having('name', '=', 'bar');
});
$this->assertEquals([0 => 'foo', 1 => 'bar'], $builder->getBindings());
}
public function testHavingBetweens()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->havingBetween('id', [1, 2, 3]);
$this->assertSame('select * from "users" having "id" between ? and ?', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->havingBetween('id', [[1, 2], [3, 4]]);
$this->assertSame('select * from "users" having "id" between ? and ?', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
}
public function testHavingNull()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->havingNull('email');
$this->assertSame('select * from "users" having "email" is null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')
->havingNull('email')
->havingNull('phone');
$this->assertSame('select * from "users" having "email" is null and "phone" is null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')
->orHavingNull('email')
->orHavingNull('phone');
$this->assertSame('select * from "users" having "email" is null or "phone" is null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->groupBy('email')->havingNull('email');
$this->assertSame('select * from "users" group by "email" having "email" is null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('email as foo_email')->from('users')->havingNull('foo_email');
$this->assertSame('select "email" as "foo_email" from "users" having "foo_email" is null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select(['category', new Raw('count(*) as "total"')])->from('item')->where('department', '=', 'popular')->groupBy('category')->havingNull('total');
$this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" is null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select(['category', new Raw('count(*) as "total"')])->from('item')->where('department', '=', 'popular')->groupBy('category')->havingNull('total');
$this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" is null', $builder->toSql());
}
public function testHavingNotNull()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->havingNotNull('email');
$this->assertSame('select * from "users" having "email" is not null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')
->havingNotNull('email')
->havingNotNull('phone');
$this->assertSame('select * from "users" having "email" is not null and "phone" is not null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')
->orHavingNotNull('email')
->orHavingNotNull('phone');
$this->assertSame('select * from "users" having "email" is not null or "phone" is not null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->groupBy('email')->havingNotNull('email');
$this->assertSame('select * from "users" group by "email" having "email" is not null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('email as foo_email')->from('users')->havingNotNull('foo_email');
$this->assertSame('select "email" as "foo_email" from "users" having "foo_email" is not null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select(['category', new Raw('count(*) as "total"')])->from('item')->where('department', '=', 'popular')->groupBy('category')->havingNotNull('total');
$this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" is not null', $builder->toSql());
$builder = $this->getBuilder();
$builder->select(['category', new Raw('count(*) as "total"')])->from('item')->where('department', '=', 'popular')->groupBy('category')->havingNotNull('total');
$this->assertSame('select "category", count(*) as "total" from "item" where "department" = ? group by "category" having "total" is not null', $builder->toSql());
}
| |
192586
|
public function testWhereWithArrayConditions()
{
/*
* where(key, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where([['foo', 1], ['bar', 2]]);
$this->assertSame('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where([['foo', 1], ['bar', 2]], boolean: 'or');
$this->assertSame('select * from "users" where ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where([['foo', 1], ['bar', 2]], boolean: 'and');
$this->assertSame('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where(['foo' => 1, 'bar' => 2]);
$this->assertSame('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where(['foo' => 1, 'bar' => 2], boolean: 'or');
$this->assertSame('select * from "users" where ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where(['foo' => 1, 'bar' => 2], boolean: 'and');
$this->assertSame('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
/*
* where(key, <, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where([['foo', 1], ['bar', '<', 2]]);
$this->assertSame('select * from "users" where ("foo" = ? and "bar" < ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where([['foo', 1], ['bar', '<', 2]], boolean: 'or');
$this->assertSame('select * from "users" where ("foo" = ? or "bar" < ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where([['foo', 1], ['bar', '<', 2]], boolean: 'and');
$this->assertSame('select * from "users" where ("foo" = ? and "bar" < ?)', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
/*
* whereNot(key, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', 2]]);
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', 2]], boolean: 'or');
$this->assertSame('select * from "users" where not (("foo" = ? or "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', 2]], boolean: 'and');
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot(['foo' => 1, 'bar' => 2]);
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot(['foo' => 1, 'bar' => 2], boolean: 'or');
$this->assertSame('select * from "users" where not (("foo" = ? or "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot(['foo' => 1, 'bar' => 2], boolean: 'and');
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
/*
* whereNot(key, <, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', '<', 2]]);
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" < ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', '<', 2]], boolean: 'or');
$this->assertSame('select * from "users" where not (("foo" = ? or "bar" < ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', '<', 2]], boolean: 'and');
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" < ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
/*
* whereColumn(col1, col2)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn([['foo', '_foo'], ['bar', '_bar']]);
$this->assertSame('select * from "users" where ("foo" = "_foo" and "bar" = "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn([['foo', '_foo'], ['bar', '_bar']], boolean: 'or');
$this->assertSame('select * from "users" where ("foo" = "_foo" or "bar" = "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
| |
192587
|
$builder->select('*')->from('users')->whereColumn([['foo', '_foo'], ['bar', '_bar']], boolean: 'and');
$this->assertSame('select * from "users" where ("foo" = "_foo" and "bar" = "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn(['foo' => '_foo', 'bar' => '_bar']);
$this->assertSame('select * from "users" where ("foo" = "_foo" and "bar" = "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn(['foo' => '_foo', 'bar' => '_bar'], boolean: 'or');
$this->assertSame('select * from "users" where ("foo" = "_foo" or "bar" = "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn(['foo' => '_foo', 'bar' => '_bar'], boolean: 'and');
$this->assertSame('select * from "users" where ("foo" = "_foo" and "bar" = "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
/*
* whereColumn(col1, <, col2)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn([['foo', '_foo'], ['bar', '<', '_bar']]);
$this->assertSame('select * from "users" where ("foo" = "_foo" and "bar" < "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn([['foo', '_foo'], ['bar', '<', '_bar']], boolean: 'or');
$this->assertSame('select * from "users" where ("foo" = "_foo" or "bar" < "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereColumn([['foo', '_foo'], ['bar', '<', '_bar']], boolean: 'and');
$this->assertSame('select * from "users" where ("foo" = "_foo" and "bar" < "_bar")', $builder->toSql());
$this->assertEquals([], $builder->getBindings());
/*
* whereAll([...keys], value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAll(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAll(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 2], $builder->getBindings());
/*
* whereAny([...keys], value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAny(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereAny(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 2], $builder->getBindings());
/*
* whereNone([...keys], value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNone(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where not ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNone(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where not ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 2, 1 => 2], $builder->getBindings());
/*
* where()->orWhere(key, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhere([['foo', 1], ['bar', 2]]);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhere(['foo' => 1, 'bar' => 2]);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
/*
* where()->orWhere(key, <, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhere([['foo', 1], ['bar', '<', 2]]);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? or "bar" < ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
/*
* where()->orWhereColumn(col1, col2)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereColumn([['foo', '_foo'], ['bar', '_bar']]);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = "_foo" or "bar" = "_bar")', $builder->toSql());
$this->assertEquals([0 => 'xxxx'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereColumn(['foo' => '_foo', 'bar' => '_bar']);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = "_foo" or "bar" = "_bar")', $builder->toSql());
$this->assertEquals([0 => 'xxxx'], $builder->getBindings());
/*
* where()->orWhere(key, <, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhere([['foo', 1], ['bar', '<', 2]]);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? or "bar" < ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
/*
* where()->orWhereNot(key, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereNot([['foo', 1], ['bar', 2]]);
$this->assertSame('select * from "users" where "xxxx" = ? or not (("foo" = ? or "bar" = ?))', $builder->toSql());
| |
192588
|
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereNot(['foo' => 1, 'bar' => 2]);
$this->assertSame('select * from "users" where "xxxx" = ? or not (("foo" = ? or "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
/*
* where()->orWhereNot(key, <, value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereNot([['foo', 1], ['bar', '<', 2]]);
$this->assertSame('select * from "users" where "xxxx" = ? or not (("foo" = ? or "bar" < ?))', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 1, 2 => 2], $builder->getBindings());
/*
* where()->orWhereAll([...keys], value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereAll(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 2, 2 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereAll(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? and "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 2, 2 => 2], $builder->getBindings());
/*
* where()->orWhereAny([...keys], value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereAny(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 2, 2 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereAny(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where "xxxx" = ? or ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 2, 2 => 2], $builder->getBindings());
/*
* where()->orWhereNone([...keys], value)
*/
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereNone(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where "xxxx" = ? or not ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 2, 2 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('xxxx', 'xxxx')->orWhereNone(['foo', 'bar'], 2);
$this->assertSame('select * from "users" where "xxxx" = ? or not ("foo" = ? or "bar" = ?)', $builder->toSql());
$this->assertEquals([0 => 'xxxx', 1 => 2, 2 => 2], $builder->getBindings());
}
public function testNestedWheres()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('email', '=', 'foo')->orWhere(function ($q) {
$q->where('name', '=', 'bar')->where('age', '=', 25);
});
$this->assertSame('select * from "users" where "email" = ? or ("name" = ? and "age" = ?)', $builder->toSql());
$this->assertEquals([0 => 'foo', 1 => 'bar', 2 => 25], $builder->getBindings());
}
public function testNestedWhereBindings()
{
$builder = $this->getBuilder();
$builder->where('email', '=', 'foo')->where(function ($q) {
$q->selectRaw('?', ['ignore'])->where('name', '=', 'bar');
});
$this->assertEquals([0 => 'foo', 1 => 'bar'], $builder->getBindings());
}
public function testWhereNot()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot(function ($q) {
$q->where('email', '=', 'foo');
});
$this->assertSame('select * from "users" where not ("email" = ?)', $builder->toSql());
$this->assertEquals([0 => 'foo'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('name', '=', 'bar')->whereNot(function ($q) {
$q->where('email', '=', 'foo');
});
$this->assertSame('select * from "users" where "name" = ? and not ("email" = ?)', $builder->toSql());
$this->assertEquals([0 => 'bar', 1 => 'foo'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->where('name', '=', 'bar')->orWhereNot(function ($q) {
$q->where('email', '=', 'foo');
});
$this->assertSame('select * from "users" where "name" = ? or not ("email" = ?)', $builder->toSql());
$this->assertEquals([0 => 'bar', 1 => 'foo'], $builder->getBindings());
}
public function testIncrementManyArgumentValidation1()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Non-numeric value passed as increment amount for column: \'col\'.');
$builder = $this->getBuilder();
$builder->from('users')->incrementEach(['col' => 'a']);
}
public function testIncrementManyArgumentValidation2()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Non-associative array passed to incrementEach method.');
$builder = $this->getBuilder();
$builder->from('users')->incrementEach([11 => 11]);
}
public function testWhereNotWithArrayConditions()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', 2]]);
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot(['foo' => 1, 'bar' => 2]);
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" = ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->whereNot([['foo', 1], ['bar', '<', 2]]);
$this->assertSame('select * from "users" where not (("foo" = ? and "bar" < ?))', $builder->toSql());
$this->assertEquals([0 => 1, 1 => 2], $builder->getBindings());
}
| |
192589
|
public function testFullSubSelects()
{
$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->assertSame('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()
{
$builder = $this->getBuilder();
$builder->select('*')->from('orders')->whereExists(function ($q) {
$q->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'));
});
$this->assertSame('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->assertSame('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->assertSame('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->assertSame('select * from "orders" where "id" = ? or not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('orders')->whereExists(
$this->getBuilder()->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'))
);
$this->assertSame('select * from "orders" where exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('orders')->whereNotExists(
$this->getBuilder()->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'))
);
$this->assertSame('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(
$this->getBuilder()->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'))
);
$this->assertSame('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(
$this->getBuilder()->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'))
);
$this->assertSame('select * from "orders" where "id" = ? or not exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('orders')->whereExists(
(new EloquentBuilder($this->getBuilder()))->select('*')->from('products')->where('products.id', '=', new Raw('"orders"."id"'))
);
$this->assertSame('select * from "orders" where exists (select * from "products" where "products"."id" = "orders"."id")', $builder->toSql());
}
public function testBasicJoins()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->join('contacts', 'users.id', 'contacts.id');
$this->assertSame('select * from "users" inner join "contacts" on "users"."id" = "contacts"."id"', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->join('contacts', 'users.id', '=', 'contacts.id')->leftJoin('photos', 'users.id', '=', 'photos.id');
$this->assertSame('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->assertSame('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 testCrossJoins()
{
$builder = $this->getBuilder();
$builder->select('*')->from('sizes')->crossJoin('colors');
$this->assertSame('select * from "sizes" cross join "colors"', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('tableB')->join('tableA', 'tableA.column1', '=', 'tableB.column2', 'cross');
$this->assertSame('select * from "tableB" cross join "tableA" on "tableA"."column1" = "tableB"."column2"', $builder->toSql());
$builder = $this->getBuilder();
$builder->select('*')->from('tableB')->crossJoin('tableA', 'tableA.column1', '=', 'tableB.column2');
$this->assertSame('select * from "tableB" cross join "tableA" on "tableA"."column1" = "tableB"."column2"', $builder->toSql());
}
public function testCrossJoinSubs()
{
$builder = $this->getBuilder();
$builder->selectRaw('(sale / overall.sales) * 100 AS percent_of_total')->from('sales')->crossJoinSub($this->getBuilder()->selectRaw('SUM(sale) AS sales')->from('sales'), 'overall');
$this->assertSame('select (sale / overall.sales) * 100 AS percent_of_total from "sales" cross join (select SUM(sale) AS sales from "sales") as "overall"', $builder->toSql());
}
| |
192591
|
public function testJoinsWithAdvancedConditions()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')->where(function ($j) {
$j->whereRole('admin')
->orWhereNull('contacts.disabled')
->orWhereRaw('year(contacts.created_at) = 2016');
});
});
$this->assertSame('select * from "users" left join "contacts" on "users"."id" = "contacts"."id" and ("role" = ? or "contacts"."disabled" is null or year(contacts.created_at) = 2016)', $builder->toSql());
$this->assertEquals(['admin'], $builder->getBindings());
}
public function testJoinsWithSubqueryCondition()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')->whereIn('contact_type_id', function ($q) {
$q->select('id')->from('contact_types')
->where('category_id', '1')
->whereNull('deleted_at');
});
});
$this->assertSame('select * from "users" left join "contacts" on "users"."id" = "contacts"."id" and "contact_type_id" in (select "id" from "contact_types" where "category_id" = ? and "deleted_at" is null)', $builder->toSql());
$this->assertEquals(['1'], $builder->getBindings());
$builder = $this->getBuilder();
$builder->select('*')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')->whereExists(function ($q) {
$q->selectRaw('1')->from('contact_types')
->whereRaw('contact_types.id = contacts.contact_type_id')
->where('category_id', '1')
->whereNull('deleted_at');
});
});
$this->assertSame('select * from "users" left join "contacts" on "users"."id" = "contacts"."id" and exists (select 1 from "contact_types" where contact_types.id = contacts.contact_type_id and "category_id" = ? and "deleted_at" is null)', $builder->toSql());
$this->assertEquals(['1'], $builder->getBindings());
}
public function testJoinsWithAdvancedSubqueryCondition()
{
$builder = $this->getBuilder();
$builder->select('*')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')->whereExists(function ($q) {
$q->selectRaw('1')->from('contact_types')
->whereRaw('contact_types.id = contacts.contact_type_id')
->where('category_id', '1')
->whereNull('deleted_at')
->whereIn('level_id', function ($q) {
$q->select('id')->from('levels')
->where('is_active', true);
});
});
});
$this->assertSame('select * from "users" left join "contacts" on "users"."id" = "contacts"."id" and exists (select 1 from "contact_types" where contact_types.id = contacts.contact_type_id and "category_id" = ? and "deleted_at" is null and "level_id" in (select "id" from "levels" where "is_active" = ?))', $builder->toSql());
$this->assertEquals(['1', true], $builder->getBindings());
}
public function testJoinsWithNestedJoins()
{
$builder = $this->getBuilder();
$builder->select('users.id', 'contacts.id', 'contact_types.id')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')->join('contact_types', 'contacts.contact_type_id', '=', 'contact_types.id');
});
$this->assertSame('select "users"."id", "contacts"."id", "contact_types"."id" from "users" left join ("contacts" inner join "contact_types" on "contacts"."contact_type_id" = "contact_types"."id") on "users"."id" = "contacts"."id"', $builder->toSql());
}
public function testJoinsWithMultipleNestedJoins()
{
$builder = $this->getBuilder();
$builder->select('users.id', 'contacts.id', 'contact_types.id', 'countries.id', 'planets.id')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')
->join('contact_types', 'contacts.contact_type_id', '=', 'contact_types.id')
->leftJoin('countries', function ($q) {
$q->on('contacts.country', '=', 'countries.country')
->join('planets', function ($q) {
$q->on('countries.planet_id', '=', 'planet.id')
->where('planet.is_settled', '=', 1)
->where('planet.population', '>=', 10000);
});
});
});
$this->assertSame('select "users"."id", "contacts"."id", "contact_types"."id", "countries"."id", "planets"."id" from "users" left join ("contacts" inner join "contact_types" on "contacts"."contact_type_id" = "contact_types"."id" left join ("countries" inner join "planets" on "countries"."planet_id" = "planet"."id" and "planet"."is_settled" = ? and "planet"."population" >= ?) on "contacts"."country" = "countries"."country") on "users"."id" = "contacts"."id"', $builder->toSql());
$this->assertEquals(['1', 10000], $builder->getBindings());
}
public function testJoinsWithNestedJoinWithAdvancedSubqueryCondition()
{
$builder = $this->getBuilder();
$builder->select('users.id', 'contacts.id', 'contact_types.id')->from('users')->leftJoin('contacts', function ($j) {
$j->on('users.id', 'contacts.id')
->join('contact_types', 'contacts.contact_type_id', '=', 'contact_types.id')
->whereExists(function ($q) {
$q->select('*')->from('countries')
->whereColumn('contacts.country', '=', 'countries.country')
->join('planets', function ($q) {
$q->on('countries.planet_id', '=', 'planet.id')
->where('planet.is_settled', '=', 1);
})
->where('planet.population', '>=', 10000);
});
});
$this->assertSame('select "users"."id", "contacts"."id", "contact_types"."id" from "users" left join ("contacts" inner join "contact_types" on "contacts"."contact_type_id" = "contact_types"."id") on "users"."id" = "contacts"."id" and exists (select * from "countries" inner join "planets" on "countries"."planet_id" = "planet"."id" and "planet"."is_settled" = ? where "contacts"."country" = "countries"."country" and "planet"."population" >= ?)', $builder->toSql());
$this->assertEquals(['1', 10000], $builder->getBindings());
}
public function testJoinWithNestedOnCondition()
{
$builder = $this->getBuilder();
$builder->select('users.id')->from('users')->join('contacts', function (JoinClause $j) {
return $j
->on('users.id', 'contacts.id')
->addNestedWhereQuery($this->getBuilder()->where('contacts.id', 1));
});
$this->assertSame('select "users"."id" from "users" inner join "contacts" on "users"."id" = "contacts"."id" and ("contacts"."id" = ?)', $builder->toSql());
$this->assertEquals([1], $builder->getBindings());
}
| |
192593
|
public function testJoinLateralPostgres()
{
$builder = $this->getPostgresBuilder();
$builder->getConnection()->shouldReceive('getDatabaseName');
$builder->from('users')->joinLateral(function ($q) {
$q->from('contacts')->whereColumn('contracts.user_id', 'users.id');
}, 'sub');
$this->assertSame('select * from "users" inner join lateral (select * from "contacts" where "contracts"."user_id" = "users"."id") as "sub" on true', $builder->toSql());
}
public function testJoinLateralSqlServer()
{
$builder = $this->getSqlServerBuilder();
$builder->getConnection()->shouldReceive('getDatabaseName');
$builder->from('users')->joinLateral(function ($q) {
$q->from('contacts')->whereColumn('contracts.user_id', 'users.id');
}, 'sub');
$this->assertSame('select * from [users] cross apply (select * from [contacts] where [contracts].[user_id] = [users].[id]) as [sub]', $builder->toSql());
}
public function testJoinLateralWithPrefix()
{
$builder = $this->getMySqlBuilder();
$builder->getConnection()->shouldReceive('getDatabaseName');
$builder->getGrammar()->setTablePrefix('prefix_');
$builder->from('users')->joinLateral('select * from `contacts` where `contracts`.`user_id` = `users`.`id`', 'sub');
$this->assertSame('select * from `prefix_users` inner join lateral (select * from `contacts` where `contracts`.`user_id` = `users`.`id`) as `prefix_sub` on true', $builder->toSql());
}
public function testLeftJoinLateral()
{
$builder = $this->getMySqlBuilder();
$builder->getConnection()->shouldReceive('getDatabaseName');
$sub = $this->getMySqlBuilder();
$sub->getConnection()->shouldReceive('getDatabaseName');
$builder->from('users')->leftJoinLateral($sub->from('contacts')->whereColumn('contracts.user_id', 'users.id'), 'sub');
$this->assertSame('select * from `users` left join lateral (select * from `contacts` where `contracts`.`user_id` = `users`.`id`) as `sub` on true', $builder->toSql());
$this->expectException(InvalidArgumentException::class);
$builder = $this->getBuilder();
$builder->from('users')->leftJoinLateral(['foo'], 'sub');
}
public function testLeftJoinLateralSqlServer()
{
$builder = $this->getSqlServerBuilder();
$builder->getConnection()->shouldReceive('getDatabaseName');
$builder->from('users')->leftJoinLateral(function ($q) {
$q->from('contacts')->whereColumn('contracts.user_id', 'users.id');
}, 'sub');
$this->assertSame('select * from [users] outer apply (select * from [contacts] where [contracts].[user_id] = [users].[id]) as [sub]', $builder->toSql());
}
public function testRawExpressionsInSelect()
{
$builder = $this->getBuilder();
$builder->select(new Raw('substr(foo, 6)'))->from('users');
$this->assertSame('select substr(foo, 6) from "users"', $builder->toSql());
}
public function testFindReturnsFirstResultByID()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1], true)->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 testFindOrReturnsFirstResultByID()
{
$builder = $this->getMockQueryBuilder();
$data = m::mock(stdClass::class);
$builder->shouldReceive('first')->andReturn($data)->once();
$builder->shouldReceive('first')->with(['column'])->andReturn($data)->once();
$builder->shouldReceive('first')->andReturn(null)->once();
$this->assertSame($data, $builder->findOr(1, fn () => 'callback result'));
$this->assertSame($data, $builder->findOr(1, ['column'], fn () => 'callback result'));
$this->assertSame('callback result', $builder->findOr(1, fn () => 'callback result'));
}
public function testFirstMethodReturnsFirstResult()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1], true)->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 testFirstOrFailMethodReturnsFirstResult()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1], true)->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)->firstOrFail();
$this->assertEquals(['foo' => 'bar'], $results);
}
public function testFirstOrFailMethodThrowsRecordNotFoundException()
{
$builder = $this->getBuilder();
$builder->getConnection()->shouldReceive('select')->once()->with('select * from "users" where "id" = ? limit 1', [1], true)->andReturn([]);
$builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [])->andReturn([]);
$this->expectException(RecordNotFoundException::class);
$this->expectExceptionMessage('No record found for the given query.');
$builder->from('users')->where('id', '=', 1)->firstOrFail();
}
public function testPluckMethodGetsCollectionOfColumnValues()
{
$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->all());
$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->all());
}
| |
192620
|
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Model as Eloquent;
use PHPUnit\Framework\TestCase;
class DatabaseEloquentBelongsToManyLazyByIdTest extends TestCase
{
protected function setUp(): void
{
$db = new DB;
$db->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
]);
$db->bootEloquent();
$db->setAsGlobal();
$this->createSchema();
}
/**
* Setup the database schema.
*
* @return void
*/
public function createSchema()
{
$this->schema()->create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
});
$this->schema()->create('articles', function ($table) {
$table->increments('aid');
$table->string('title');
});
$this->schema()->create('article_user', function ($table) {
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('aid')->on('articles');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function testBelongsToLazyById()
{
$this->seedData();
$user = BelongsToManyLazyByIdTestTestUser::query()->first();
$i = 0;
$user->articles()->lazyById(1)->each(function ($model) use (&$i) {
$i++;
$this->assertEquals($i, $model->aid);
});
$this->assertSame(3, $i);
}
/**
* Tear down the database schema.
*
* @return void
*/
protected function tearDown(): void
{
$this->schema()->drop('users');
$this->schema()->drop('articles');
$this->schema()->drop('article_user');
}
/**
* Helpers...
*/
protected function seedData()
{
$user = BelongsToManyLazyByIdTestTestUser::create(['id' => 1, 'email' => 'taylorotwell@gmail.com']);
BelongsToManyLazyByIdTestTestArticle::query()->insert([
['aid' => 1, 'title' => 'Another title'],
['aid' => 2, 'title' => 'Another title'],
['aid' => 3, 'title' => 'Another title'],
]);
$user->articles()->sync([3, 1, 2]);
}
/**
* Get a database connection instance.
*
* @return \Illuminate\Database\ConnectionInterface
*/
protected function connection()
{
return Eloquent::getConnectionResolver()->connection();
}
/**
* Get a schema builder instance.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected function schema()
{
return $this->connection()->getSchemaBuilder();
}
}
class BelongsToManyLazyByIdTestTestUser extends Eloquent
{
protected $table = 'users';
protected $fillable = ['id', 'email'];
public $timestamps = false;
public function articles()
{
return $this->belongsToMany(BelongsToManyLazyByIdTestTestArticle::class, 'article_user', 'user_id', 'article_id');
}
}
class BelongsToManyLazyByIdTestTestArticle extends Eloquent
{
protected $primaryKey = 'aid';
protected $table = 'articles';
protected $keyType = 'string';
public $incrementing = false;
public $timestamps = false;
protected $fillable = ['aid', 'title'];
}
| |
192635
|
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Eloquent\Attributes\ScopedBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use PHPUnit\Framework\TestCase;
class DatabaseEloquentGlobalScopesTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
tap(new DB)->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
])->bootEloquent();
}
protected function tearDown(): void
{
parent::tearDown();
Model::unsetConnectionResolver();
}
public function testGlobalScopeIsApplied()
{
$model = new EloquentGlobalScopesTestModel;
$query = $model->newQuery();
$this->assertSame('select * from "table" where "active" = ?', $query->toSql());
$this->assertEquals([1], $query->getBindings());
}
public function testGlobalScopeCanBeRemoved()
{
$model = new EloquentGlobalScopesTestModel;
$query = $model->newQuery()->withoutGlobalScope(ActiveScope::class);
$this->assertSame('select * from "table"', $query->toSql());
$this->assertEquals([], $query->getBindings());
}
public function testClassNameGlobalScopeIsApplied()
{
$model = new EloquentClassNameGlobalScopesTestModel;
$query = $model->newQuery();
$this->assertSame('select * from "table" where "active" = ?', $query->toSql());
$this->assertEquals([1], $query->getBindings());
}
public function testGlobalScopeInAttributeIsApplied()
{
$model = new EloquentGlobalScopeInAttributeTestModel;
$query = $model->newQuery();
$this->assertSame('select * from "table" where "active" = ?', $query->toSql());
$this->assertEquals([1], $query->getBindings());
}
public function testClosureGlobalScopeIsApplied()
{
$model = new EloquentClosureGlobalScopesTestModel;
$query = $model->newQuery();
$this->assertSame('select * from "table" where "active" = ? order by "name" asc', $query->toSql());
$this->assertEquals([1], $query->getBindings());
}
public function testGlobalScopesCanBeRegisteredViaArray()
{
$model = new EloquentGlobalScopesArrayTestModel;
$query = $model->newQuery();
$this->assertSame('select * from "table" where "active" = ? order by "name" asc', $query->toSql());
$this->assertEquals([1], $query->getBindings());
}
public function testClosureGlobalScopeCanBeRemoved()
{
$model = new EloquentClosureGlobalScopesTestModel;
$query = $model->newQuery()->withoutGlobalScope('active_scope');
$this->assertSame('select * from "table" order by "name" asc', $query->toSql());
$this->assertEquals([], $query->getBindings());
}
public function testGlobalScopeCanBeRemovedAfterTheQueryIsExecuted()
{
$model = new EloquentClosureGlobalScopesTestModel;
$query = $model->newQuery();
$this->assertSame('select * from "table" where "active" = ? order by "name" asc', $query->toSql());
$this->assertEquals([1], $query->getBindings());
$query->withoutGlobalScope('active_scope');
$this->assertSame('select * from "table" order by "name" asc', $query->toSql());
$this->assertEquals([], $query->getBindings());
}
public function testAllGlobalScopesCanBeRemoved()
{
$model = new EloquentClosureGlobalScopesTestModel;
$query = $model->newQuery()->withoutGlobalScopes();
$this->assertSame('select * from "table"', $query->toSql());
$this->assertEquals([], $query->getBindings());
$query = EloquentClosureGlobalScopesTestModel::withoutGlobalScopes();
$this->assertSame('select * from "table"', $query->toSql());
$this->assertEquals([], $query->getBindings());
}
public function testGlobalScopesWithOrWhereConditionsAreNested()
{
$model = new EloquentClosureGlobalScopesWithOrTestModel;
$query = $model->newQuery();
$this->assertSame('select "email", "password" from "table" where ("email" = ? or "email" = ?) and "active" = ? order by "name" asc', $query->toSql());
$this->assertEquals(['taylor@gmail.com', 'someone@else.com', 1], $query->getBindings());
$query = $model->newQuery()->where('col1', 'val1')->orWhere('col2', 'val2');
$this->assertSame('select "email", "password" from "table" where ("col1" = ? or "col2" = ?) and ("email" = ? or "email" = ?) and "active" = ? order by "name" asc', $query->toSql());
$this->assertEquals(['val1', 'val2', 'taylor@gmail.com', 'someone@else.com', 1], $query->getBindings());
}
public function testRegularScopesWithOrWhereConditionsAreNested()
{
$query = EloquentClosureGlobalScopesTestModel::withoutGlobalScopes()->where('foo', 'foo')->orWhere('bar', 'bar')->approved();
$this->assertSame('select * from "table" where ("foo" = ? or "bar" = ?) and ("approved" = ? or "should_approve" = ?)', $query->toSql());
$this->assertEquals(['foo', 'bar', 1, 0], $query->getBindings());
}
public function testScopesStartingWithOrBooleanArePreserved()
{
$query = EloquentClosureGlobalScopesTestModel::withoutGlobalScopes()->where('foo', 'foo')->orWhere('bar', 'bar')->orApproved();
$this->assertSame('select * from "table" where ("foo" = ? or "bar" = ?) or ("approved" = ? or "should_approve" = ?)', $query->toSql());
$this->assertEquals(['foo', 'bar', 1, 0], $query->getBindings());
}
public function testHasQueryWhereBothModelsHaveGlobalScopes()
{
$query = EloquentGlobalScopesWithRelationModel::has('related')->where('bar', 'baz');
$subQuery = 'select * from "table" where "table2"."id" = "table"."related_id" and "foo" = ? and "active" = ?';
$mainQuery = 'select * from "table2" where exists ('.$subQuery.') and "bar" = ? and "active" = ? order by "name" asc';
$this->assertEquals($mainQuery, $query->toSql());
$this->assertEquals(['bar', 1, 'baz', 1], $query->getBindings());
}
}
class EloquentClosureGlobalScopesTestModel extends Model
{
protected $table = 'table';
public static function boot()
{
static::addGlobalScope(function ($query) {
$query->orderBy('name');
});
static::addGlobalScope('active_scope', function ($query) {
$query->where('active', 1);
});
parent::boot();
}
public function scopeApproved($query)
{
return $query->where('approved', 1)->orWhere('should_approve', 0);
}
public function scopeOrApproved($query)
{
return $query->orWhere('approved', 1)->orWhere('should_approve', 0);
}
}
class EloquentGlobalScopesWithRelationModel extends EloquentClosureGlobalScopesTestModel
{
protected $table = 'table2';
public function related()
{
return $this->hasMany(EloquentGlobalScopesTestModel::class, 'related_id')->where('foo', 'bar');
}
}
class EloquentClosureGlobalScopesWithOrTestModel extends EloquentClosureGlobalScopesTestModel
{
public static function boot()
{
static::addGlobalScope('or_scope', function ($query) {
$query->where('email', 'taylor@gmail.com')->orWhere('email', 'someone@else.com');
});
static::addGlobalScope(function ($query) {
$query->select('email', 'password');
});
parent::boot();
}
}
class EloquentGlobalScopesTestModel extends Model
{
protected $table = 'table';
public static function boot()
{
static::addGlobalScope(new ActiveScope);
parent::boot();
}
}
| |
192648
|
public function testWithExists()
{
$user = HasOneOfManyTestUser::create();
$user = HasOneOfManyTestUser::withExists('latest_login')->first();
$this->assertFalse($user->latest_login_exists);
$user->logins()->create();
$user = HasOneOfManyTestUser::withExists('latest_login')->first();
$this->assertTrue($user->latest_login_exists);
}
public function testWithExistsWithConstraintsInJoinSubSelect()
{
$user = HasOneOfManyTestUser::create();
$user = HasOneOfManyTestUser::withExists('foo_state')->first();
$this->assertFalse($user->foo_state_exists);
$user->states()->create([
'type' => 'foo',
'state' => 'bar',
]);
$user = HasOneOfManyTestUser::withExists('foo_state')->first();
$this->assertTrue($user->foo_state_exists);
}
public function testWithSoftDeletes()
{
$user = HasOneOfManyTestUser::create();
$user->logins()->create();
$user->latest_login_with_soft_deletes;
$this->assertNotNull($user->latest_login_with_soft_deletes);
}
public function testWithConstraintNotInAggregate()
{
$user = HasOneOfManyTestUser::create();
$previousFoo = $user->states()->create([
'type' => 'foo',
'state' => 'bar',
'updated_at' => '2020-01-01 00:00:00',
]);
$newFoo = $user->states()->create([
'type' => 'foo',
'state' => 'active',
'updated_at' => '2021-01-01 12:00:00',
]);
$newBar = $user->states()->create([
'type' => 'bar',
'state' => 'active',
'updated_at' => '2021-01-01 12:00:00',
]);
$this->assertSame($newFoo->id, $user->last_updated_foo_state->id);
}
public function testItGetsCorrectResultUsingAtLeastTwoAggregatesDistinctFromId()
{
$user = HasOneOfManyTestUser::create();
$expectedState = $user->states()->create([
'state' => 'state',
'type' => 'type',
'created_at' => '2023-01-01',
'updated_at' => '2023-01-03',
]);
$user->states()->create([
'state' => 'state',
'type' => 'type',
'created_at' => '2023-01-01',
'updated_at' => '2023-01-02',
]);
$this->assertSame($user->latest_updated_latest_created_state->id, $expectedState->id);
}
/**
* Get a database connection instance.
*
* @return \Illuminate\Database\Connection
*/
protected function connection()
{
return Eloquent::getConnectionResolver()->connection();
}
/**
* Get a schema builder instance.
*
* @return \Illuminate\Database\Schema\Builder
*/
protected function schema()
{
return $this->connection()->getSchemaBuilder();
}
}
/**
* Eloquent Models...
*/
class HasOneOfManyTestUser extends Eloquent
{
protected $table = 'users';
protected $guarded = [];
public $timestamps = false;
public function logins()
{
return $this->hasMany(HasOneOfManyTestLogin::class, 'user_id');
}
public function latest_login()
{
return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany();
}
public function latest_login_with_soft_deletes()
{
return $this->hasOne(HasOneOfManyTestLoginWithSoftDeletes::class, 'user_id')->ofMany();
}
public function latest_login_with_shortcut()
{
return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->latestOfMany();
}
public function latest_login_with_invalid_aggregate()
{
return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany('id', 'count');
}
public function latest_login_without_global_scope()
{
return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->withoutGlobalScopes()->latestOfMany();
}
public function first_login()
{
return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany('id', 'min');
}
public function latest_login_with_foo_state()
{
return $this->hasOne(HasOneOfManyTestLogin::class, 'user_id')->ofMany(
['id' => 'max'],
function ($query) {
$query->join('states', 'states.user_id', 'logins.user_id')
->where('states.type', 'foo');
}
);
}
public function states()
{
return $this->hasMany(HasOneOfManyTestState::class, 'user_id');
}
public function foo_state()
{
return $this->hasOne(HasOneOfManyTestState::class, 'user_id')->ofMany(
['id' => 'max'],
function ($q) {
$q->where('type', 'foo');
}
);
}
public function last_updated_foo_state()
{
return $this->hasOne(HasOneOfManyTestState::class, 'user_id')->ofMany([
'updated_at' => 'max',
'id' => 'max',
], function ($q) {
$q->where('type', 'foo');
});
}
public function prices()
{
return $this->hasMany(HasOneOfManyTestPrice::class, 'user_id');
}
public function price()
{
return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->ofMany([
'published_at' => 'max',
'id' => 'max',
], function ($q) {
$q->where('published_at', '<', now());
});
}
public function price_without_key_in_aggregates()
{
return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->ofMany(['published_at' => 'MAX']);
}
public function price_with_shortcut()
{
return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->latestOfMany(['published_at', 'id']);
}
public function price_without_global_scope()
{
return $this->hasOne(HasOneOfManyTestPrice::class, 'user_id')->withoutGlobalScopes()->ofMany([
'published_at' => 'max',
'id' => 'max',
], function ($q) {
$q->where('published_at', '<', now());
});
}
public function latest_updated_latest_created_state()
{
return $this->hasOne(HasOneOfManyTestState::class, 'user_id')->ofMany([
'updated_at' => 'max',
'created_at' => 'max',
]);
}
}
class HasOneOfManyTestModel extends Eloquent
{
public function logins()
{
return $this->hasOne(HasOneOfManyTestLogin::class)->ofMany();
}
}
class HasOneOfManyTestLogin extends Eloquent
{
protected $table = 'logins';
protected $guarded = [];
public $timestamps = false;
}
class HasOneOfManyTestLoginWithSoftDeletes extends Eloquent
{
use SoftDeletes;
protected $table = 'logins';
protected $guarded = [];
public $timestamps = false;
}
class HasOneOfManyTestState extends Eloquent
{
protected $table = 'states';
protected $guarded = [];
public $timestamps = true;
protected $fillable = ['type', 'state', 'updated_at'];
}
class HasOneOfManyTestPrice extends Eloquent
{
protected $table = 'prices';
protected $guarded = [];
public $timestamps = false;
protected $fillable = ['published_at'];
protected $casts = ['published_at' => 'datetime'];
}
| |
192659
|
<?php
namespace Illuminate\Tests\Database;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use PHPUnit\Framework\TestCase;
class DatabaseSoftDeletingTest extends TestCase
{
public function testDeletedAtIsAddedToCastsAsDefaultType()
{
$model = new SoftDeletingModel;
$this->assertArrayHasKey('deleted_at', $model->getCasts());
$this->assertSame('datetime', $model->getCasts()['deleted_at']);
}
public function testDeletedAtIsCastToCarbonInstance()
{
$expected = Carbon::createFromFormat('Y-m-d H:i:s', '2018-12-29 13:59:39');
$model = new SoftDeletingModel(['deleted_at' => $expected->format('Y-m-d H:i:s')]);
$this->assertInstanceOf(Carbon::class, $model->deleted_at);
$this->assertTrue($expected->eq($model->deleted_at));
}
public function testExistingCastOverridesAddedDateCast()
{
$model = new class(['deleted_at' => '2018-12-29 13:59:39']) extends SoftDeletingModel
{
protected $casts = ['deleted_at' => 'bool'];
};
$this->assertTrue($model->deleted_at);
}
public function testExistingMutatorOverridesAddedDateCast()
{
$model = new class(['deleted_at' => '2018-12-29 13:59:39']) extends SoftDeletingModel
{
protected function getDeletedAtAttribute()
{
return 'expected';
}
};
$this->assertSame('expected', $model->deleted_at);
}
public function testCastingToStringOverridesAutomaticDateCastingToRetainPreviousBehaviour()
{
$model = new class(['deleted_at' => '2018-12-29 13:59:39']) extends SoftDeletingModel
{
protected $casts = ['deleted_at' => 'string'];
};
$this->assertSame('2018-12-29 13:59:39', $model->deleted_at);
}
}
class SoftDeletingModel extends Model
{
use SoftDeletes;
protected $guarded = [];
protected $dateFormat = 'Y-m-d H:i:s';
}
| |
192686
|
<?php
use Illuminate\Database\Eloquent\Model;
class EloquentModelUuidStub extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'model';
/**
* The "type" of the primary key ID.
*
* @var string
*/
protected $keyType = 'string';
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
}
| |
192693
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
| |
192775
|
public function testAfterCallbacksDoNotOverrideEachOther()
{
$gate = $this->getBasicGate();
$gate->after(function ($user, $ability, $result) {
return $ability === 'allow';
});
$gate->after(function ($user, $ability, $result) {
return ! $result;
});
$this->assertTrue($gate->allows('allow'));
$this->assertTrue($gate->denies('deny'));
}
public function testCanDefineGatesUsingBackedEnum()
{
$gate = $this->getBasicGate();
$gate->define(AbilitiesEnum::VIEW_DASHBOARD, function ($user) {
return true;
});
$this->assertTrue($gate->allows('view-dashboard'));
}
public function testBackedEnumInAllows()
{
$gate = $this->getBasicGate();
$gate->define(AbilitiesEnum::VIEW_DASHBOARD, function ($user) {
return true;
});
$this->assertTrue($gate->allows(AbilitiesEnum::VIEW_DASHBOARD));
}
public function testBackedEnumInDenies()
{
$gate = $this->getBasicGate();
$gate->define(AbilitiesEnum::VIEW_DASHBOARD, function ($user) {
return false;
});
$this->assertTrue($gate->denies(AbilitiesEnum::VIEW_DASHBOARD));
}
public function testArrayAbilitiesInAllows()
{
$gate = $this->getBasicGate();
$gate->define('allow_1', function ($user) {
return true;
});
$gate->define('allow_2', function ($user) {
return true;
});
$gate->define(AbilitiesEnum::VIEW_DASHBOARD, function ($user) {
return true;
});
$gate->define('deny', function ($user) {
return false;
});
$this->assertTrue($gate->allows(['allow_1']));
$this->assertTrue($gate->allows(['allow_1', 'allow_2', AbilitiesEnum::VIEW_DASHBOARD]));
$this->assertFalse($gate->allows(['allow_1', 'allow_2', 'deny']));
$this->assertFalse($gate->allows(['deny', 'allow_1', 'allow_2']));
}
public function testArrayAbilitiesInDenies()
{
$gate = $this->getBasicGate();
$gate->define('deny_1', function ($user) {
return false;
});
$gate->define('deny_2', function ($user) {
return false;
});
$gate->define(AbilitiesEnum::VIEW_DASHBOARD, function ($user) {
return false;
});
$gate->define('allow', function ($user) {
return true;
});
$this->assertTrue($gate->denies(['deny_1']));
$this->assertTrue($gate->denies(['deny_1', 'deny_2', AbilitiesEnum::VIEW_DASHBOARD]));
$this->assertTrue($gate->denies(['deny_1', 'allow']));
$this->assertTrue($gate->denies(['allow', 'deny_1']));
$this->assertFalse($gate->denies(['allow']));
}
public function testCurrentUserThatIsOnGateAlwaysInjectedIntoClosureCallbacks()
{
$gate = $this->getBasicGate();
$gate->define('foo', function ($user) {
$this->assertSame(1, $user->id);
return true;
});
$this->assertTrue($gate->check('foo'));
}
public function testASingleArgumentCanBePassedWhenCheckingAbilities()
{
$gate = $this->getBasicGate();
$dummy = new AccessGateTestDummy;
$gate->before(function ($user, $ability, array $arguments) use ($dummy) {
$this->assertCount(1, $arguments);
$this->assertSame($dummy, $arguments[0]);
});
$gate->define('foo', function ($user, $x) use ($dummy) {
$this->assertSame($dummy, $x);
return true;
});
$gate->after(function ($user, $ability, $result, array $arguments) use ($dummy) {
$this->assertCount(1, $arguments);
$this->assertSame($dummy, $arguments[0]);
});
$this->assertTrue($gate->check('foo', $dummy));
}
public function testMultipleArgumentsCanBePassedWhenCheckingAbilities()
{
$gate = $this->getBasicGate();
$dummy1 = new AccessGateTestDummy;
$dummy2 = new AccessGateTestDummy;
$gate->before(function ($user, $ability, array $arguments) use ($dummy1, $dummy2) {
$this->assertCount(2, $arguments);
$this->assertSame([$dummy1, $dummy2], $arguments);
});
$gate->define('foo', function ($user, $x, $y) use ($dummy1, $dummy2) {
$this->assertSame($dummy1, $x);
$this->assertSame($dummy2, $y);
return true;
});
$gate->after(function ($user, $ability, $result, array $arguments) use ($dummy1, $dummy2) {
$this->assertCount(2, $arguments);
$this->assertSame([$dummy1, $dummy2], $arguments);
});
$this->assertTrue($gate->check('foo', [$dummy1, $dummy2]));
}
public function testClassesCanBeDefinedAsCallbacksUsingAtNotation()
{
$gate = $this->getBasicGate();
$gate->define('foo', AccessGateTestClass::class.'@foo');
$this->assertTrue($gate->check('foo'));
}
public function testInvokableClassesCanBeDefined()
{
$gate = $this->getBasicGate();
$gate->define('foo', AccessGateTestInvokableClass::class);
$this->assertTrue($gate->check('foo'));
}
public function testGatesCanBeDefinedUsingAnArrayCallback()
{
$gate = $this->getBasicGate();
$gate->define('foo', [new AccessGateTestStaticClass, 'foo']);
$this->assertTrue($gate->check('foo'));
}
public function testGatesCanBeDefinedUsingAnArrayCallbackWithStaticMethod()
{
$gate = $this->getBasicGate();
$gate->define('foo', [AccessGateTestStaticClass::class, 'foo']);
$this->assertTrue($gate->check('foo'));
}
public function testPolicyClassesCanBeDefinedToHandleChecksForGivenType()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
$this->assertTrue($gate->check('update', new AccessGateTestDummy));
}
public function testPolicyClassesHandleChecksForAllSubtypes()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
$this->assertTrue($gate->check('update', new AccessGateTestSubDummy));
}
public function testPolicyClassesHandleChecksForInterfaces()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummyInterface::class, AccessGateTestPolicy::class);
$this->assertTrue($gate->check('update', new AccessGateTestSubDummy));
}
public function testPolicyConvertsDashToCamel()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
$this->assertTrue($gate->check('update-dash', new AccessGateTestDummy));
}
public function testPolicyDefaultToFalseIfMethodDoesNotExistAndGateDoesNotExist()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
$this->assertFalse($gate->check('nonexistent_method', new AccessGateTestDummy));
}
public function testPolicyClassesCanBeDefinedToHandleChecksForGivenClassName()
{
$gate = $this->getBasicGate(true);
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicy::class);
$this->assertTrue($gate->check('create', [AccessGateTestDummy::class, true]));
}
public function testPoliciesMayHaveBeforeMethodsToOverrideChecks()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithBefore::class);
$this->assertTrue($gate->check('update', new AccessGateTestDummy));
}
| |
192778
|
public function testAnyAbilitiesCheckUsingBackedEnum()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithAllPermissions::class);
$this->assertTrue($gate->any(['edit', AbilitiesEnum::UPDATE], new AccessGateTestDummy));
}
public function testNoneAbilitiesCheckUsingBackedEnum()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithNoPermissions::class);
$this->assertTrue($gate->none(['edit', AbilitiesEnum::UPDATE], new AccessGateTestDummy));
}
public function testAbilitiesCheckUsingBackedEnum()
{
$gate = $this->getBasicGate();
$gate->policy(AccessGateTestDummy::class, AccessGateTestPolicyWithAllPermissions::class);
$this->assertTrue($gate->check(['edit', AbilitiesEnum::UPDATE], new AccessGateTestDummy));
}
/**
* @param array $abilitiesToSet
* @param array|string $abilitiesToCheck
* @param bool $expectedHasValue
*/
#[DataProvider('hasAbilitiesTestDataProvider')]
public function testHasAbilities($abilitiesToSet, $abilitiesToCheck, $expectedHasValue)
{
$gate = $this->getBasicGate();
$gate->resource('test', AccessGateTestResource::class, $abilitiesToSet);
$this->assertEquals($expectedHasValue, $gate->has($abilitiesToCheck));
}
public static function hasAbilitiesTestDataProvider()
{
$abilities = ['foo' => 'foo', 'bar' => 'bar'];
$noAbilities = [];
return [
[$abilities, ['test.foo', 'test.bar'], true],
[$abilities, ['test.bar', 'test.foo'], true],
[$abilities, ['test.bar', 'test.foo', 'test.baz'], false],
[$abilities, ['test.bar'], true],
[$abilities, ['baz'], false],
[$abilities, [''], false],
[$abilities, [], true],
[$abilities, 'test.bar', true],
[$abilities, 'test.foo', true],
[$abilities, '', false],
[$noAbilities, '', false],
[$noAbilities, [], true],
];
}
public function testClassesCanBeDefinedAsCallbacksUsingAtNotationForGuests()
{
$gate = new Gate(new Container, function () {
//
});
$gate->define('foo', AccessGateTestClassForGuest::class.'@foo');
$gate->define('obj_foo', [new AccessGateTestClassForGuest, 'foo']);
$gate->define('static_foo', [AccessGateTestClassForGuest::class, 'staticFoo']);
$gate->define('static_@foo', AccessGateTestClassForGuest::class.'@staticFoo');
$gate->define('bar', AccessGateTestClassForGuest::class.'@bar');
$gate->define('invokable', AccessGateTestGuestInvokableClass::class);
$gate->define('nullable_invokable', AccessGateTestGuestNullableInvokable::class);
$gate->define('absent_invokable', 'someAbsentClass');
AccessGateTestClassForGuest::$calledMethod = '';
$this->assertTrue($gate->check('foo'));
$this->assertSame('foo was called', AccessGateTestClassForGuest::$calledMethod);
$this->assertTrue($gate->check('static_foo'));
$this->assertSame('static foo was invoked', AccessGateTestClassForGuest::$calledMethod);
$this->assertTrue($gate->check('bar'));
$this->assertSame('bar got invoked', AccessGateTestClassForGuest::$calledMethod);
$this->assertTrue($gate->check('static_@foo'));
$this->assertSame('static foo was invoked', AccessGateTestClassForGuest::$calledMethod);
$this->assertTrue($gate->check('invokable'));
$this->assertSame('__invoke was called', AccessGateTestGuestInvokableClass::$calledMethod);
$this->assertTrue($gate->check('nullable_invokable'));
$this->assertSame('Nullable __invoke was called', AccessGateTestGuestNullableInvokable::$calledMethod);
$this->assertFalse($gate->check('absent_invokable'));
}
public function testCanSetDenialResponseInConstructor()
{
$gate = new Gate(container: new Container, userResolver: function () {
//
});
$gate->defaultDenialResponse(Response::denyWithStatus(999, 'my_message', 'abc'));
$gate->define('foo', function () {
return false;
});
$response = $gate->inspect('foo', new AccessGateTestDummy);
$this->assertTrue($response->denied());
$this->assertFalse($response->allowed());
$this->assertSame('my_message', $response->message());
$this->assertSame('abc', $response->code());
$this->assertSame(999, $response->status());
}
public function testCanSetDenialResponse()
{
$gate = new Gate(container: new Container, userResolver: function () {
//
});
$gate->define('foo', function () {
return false;
});
$gate->defaultDenialResponse(Response::denyWithStatus(404, 'not_found', 'xyz'));
$response = $gate->inspect('foo', new AccessGateTestDummy);
$this->assertTrue($response->denied());
$this->assertFalse($response->allowed());
$this->assertSame('not_found', $response->message());
$this->assertSame('xyz', $response->code());
$this->assertSame(404, $response->status());
}
}
class AccessGateTestClassForGuest
{
public static $calledMethod = null;
public function foo($user = null)
{
static::$calledMethod = 'foo was called';
return true;
}
public static function staticFoo($user = null)
{
static::$calledMethod = 'static foo was invoked';
return true;
}
public function bar(?stdClass $user)
{
static::$calledMethod = 'bar got invoked';
return true;
}
}
class AccessGateTestStaticClass
{
public static function foo($user)
{
return $user->id === 1;
}
}
class AccessGateTestClass
{
public function foo($user)
{
return $user->id === 1;
}
}
class AccessGateTestInvokableClass
{
public function __invoke($user)
{
return $user->id === 1;
}
}
class AccessGateTestGuestInvokableClass
{
public static $calledMethod = null;
public function __invoke($user = null)
{
static::$calledMethod = '__invoke was called';
return true;
}
}
class AccessGateTestGuestNullableInvokable
{
public static $calledMethod = null;
public function __invoke(?stdClass $user)
{
static::$calledMethod = 'Nullable __invoke was called';
return true;
}
}
interface AccessGateTestDummyInterface
{
//
}
class AccessGateTestDummy implements AccessGateTestDummyInterface
{
//
}
class AccessGateTestSubDummy extends AccessGateTestDummy
{
//
}
class AccessGateTestPolicy
{
use HandlesAuthorization;
public function createAny($user, $additional)
{
return $additional;
}
public function create($user)
{
return $user->isAdmin ? $this->allow() : $this->deny('You are not an admin.');
}
public function updateAny($user, AccessGateTestDummy $dummy)
{
return ! $user->isAdmin;
}
public function update($user, AccessGateTestDummy $dummy)
{
return ! $user->isAdmin;
}
public function updateDash($user, AccessGateTestDummy $dummy)
{
return $user instanceof stdClass;
}
}
class AccessGateTestPolicyWithBefore
{
public function before($user, $ability)
{
return true;
}
public function update($user, AccessGateTestDummy $dummy)
{
return false;
}
}
class AccessGateTestResource
{
public function view($user)
{
return true;
}
public function create($user)
{
return true;
}
public function update($user, AccessGateTestDummy $dummy)
{
return true;
}
public function delete($user, AccessGateTestDummy $dummy)
{
return true;
}
}
class AccessGateTestCustomResource
{
public function foo($user)
{
return true;
}
public function bar($user)
{
return true;
}
}
class AccessGateTestPolicyWithMixedPermissions
{
public function edit($user, AccessGateTestDummy $dummy)
{
return false;
}
public function update($user, AccessGateTestDummy $dummy)
{
return true;
}
}
| |
192787
|
public function testRegistersQueryHandler()
{
$callback = function ($builder) {
$builder->whereIn('group', ['one', 'two']);
};
$provider = $this->getProviderMock();
$mock = m::mock(stdClass::class);
$mock->shouldReceive('newQuery')->once()->andReturn($mock);
$mock->shouldReceive('where')->once()->with('username', 'dayle');
$mock->shouldReceive('whereIn')->once()->with('group', ['one', 'two']);
$mock->shouldReceive('first')->once()->andReturn('bar');
$provider->expects($this->once())->method('createModel')->willReturn($mock);
$provider->withQuery($callback);
$user = $provider->retrieveByCredentials([function ($builder) {
$builder->where('username', 'dayle');
}]);
$this->assertSame('bar', $user);
$this->assertSame($callback, $provider->getQueryCallback());
}
protected function getProviderMock()
{
$hasher = m::mock(Hasher::class);
return $this->getMockBuilder(EloquentUserProvider::class)->onlyMethods(['createModel'])->setConstructorArgs([$hasher, 'foo'])->getMock();
}
}
class EloquentProviderUserStub
{
//
}
| |
192819
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentWhereHasTest;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder as QueryBuilder;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
use PHPUnit\Framework\Attributes\DataProvider;
class EloquentWhereHasTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
});
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->boolean('public');
});
Schema::create('texts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('post_id');
$table->text('content');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('commentable_type');
$table->integer('commentable_id');
});
$user = User::create();
$post = tap((new Post(['public' => true]))->user()->associate($user))->save();
(new Comment)->commentable()->associate($post)->save();
(new Text(['content' => 'test']))->post()->associate($post)->save();
$user = User::create();
$post = tap((new Post(['public' => false]))->user()->associate($user))->save();
(new Comment)->commentable()->associate($post)->save();
(new Text(['content' => 'test2']))->post()->associate($post)->save();
}
/**
* Check that the 'whereRelation' callback function works.
*/
#[DataProvider('dataProviderWhereRelationCallback')]
public function testWhereRelationCallback($callbackEloquent, $callbackQuery)
{
$userWhereRelation = User::whereRelation('posts', $callbackEloquent);
$userWhereHas = User::whereHas('posts', $callbackEloquent);
$query = DB::table('users')->whereExists($callbackQuery);
$this->assertEquals($userWhereRelation->getQuery()->toSql(), $query->toSql());
$this->assertEquals($userWhereRelation->getQuery()->toSql(), $userWhereHas->toSql());
$this->assertEquals($userWhereHas->getQuery()->toSql(), $query->toSql());
$this->assertEquals($userWhereRelation->first()->id, $query->first()->id);
$this->assertEquals($userWhereRelation->first()->id, $userWhereHas->first()->id);
$this->assertEquals($userWhereHas->first()->id, $query->first()->id);
}
/**
* Check that the 'orWhereRelation' callback function works.
*/
#[DataProvider('dataProviderWhereRelationCallback')]
public function testOrWhereRelationCallback($callbackEloquent, $callbackQuery)
{
$userOrWhereRelation = User::orWhereRelation('posts', $callbackEloquent);
$userOrWhereHas = User::orWhereHas('posts', $callbackEloquent);
$query = DB::table('users')->orWhereExists($callbackQuery);
$this->assertEquals($userOrWhereRelation->getQuery()->toSql(), $query->toSql());
$this->assertEquals($userOrWhereRelation->getQuery()->toSql(), $userOrWhereHas->toSql());
$this->assertEquals($userOrWhereHas->getQuery()->toSql(), $query->toSql());
$this->assertEquals($userOrWhereRelation->first()->id, $query->first()->id);
$this->assertEquals($userOrWhereRelation->first()->id, $userOrWhereHas->first()->id);
$this->assertEquals($userOrWhereHas->first()->id, $query->first()->id);
}
public static function dataProviderWhereRelationCallback()
{
$callbackArray = function ($value) {
$callbackEloquent = function (EloquentBuilder $builder) use ($value) {
$builder->selectRaw('id')->where('public', $value);
};
$callbackQuery = function (QueryBuilder $builder) use ($value) {
$hasMany = app()->make(User::class)->posts();
$builder->from('posts')->addSelect(['*'])->whereColumn(
$hasMany->getQualifiedParentKeyName(),
'=',
$hasMany->getQualifiedForeignKeyName()
);
$builder->selectRaw('id')->where('public', $value);
};
return [$callbackEloquent, $callbackQuery];
};
return [
'Find user with post.public = true' => $callbackArray(true),
'Find user with post.public = false' => $callbackArray(false),
];
}
public function testWhereRelation()
{
$users = User::whereRelation('posts', 'public', true)->get();
$this->assertEquals([1], $users->pluck('id')->all());
}
public function testOrWhereRelation()
{
$users = User::whereRelation('posts', 'public', true)->orWhereRelation('posts', 'public', false)->get();
$this->assertEquals([1, 2], $users->pluck('id')->all());
}
public function testNestedWhereRelation()
{
$texts = User::whereRelation('posts.texts', 'content', 'test')->get();
$this->assertEquals([1], $texts->pluck('id')->all());
}
public function testNestedOrWhereRelation()
{
$texts = User::whereRelation('posts.texts', 'content', 'test')->orWhereRelation('posts.texts', 'content', 'test2')->get();
$this->assertEquals([1, 2], $texts->pluck('id')->all());
}
public function testWhereMorphRelation()
{
$comments = Comment::whereMorphRelation('commentable', '*', 'public', true)->get();
$this->assertEquals([1], $comments->pluck('id')->all());
}
public function testOrWhereMorphRelation()
{
$comments = Comment::whereMorphRelation('commentable', '*', 'public', true)
->orWhereMorphRelation('commentable', '*', 'public', false)
->get();
$this->assertEquals([1, 2], $comments->pluck('id')->all());
}
public function testWithCount()
{
$users = User::whereHas('posts', function ($query) {
$query->where('public', true);
})->get();
$this->assertEquals([1], $users->pluck('id')->all());
}
}
class Comment extends Model
{
public $timestamps = false;
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $withCount = ['comments'];
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function texts()
{
return $this->hasMany(Text::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
class Text extends Model
{
public $timestamps = false;
protected $guarded = [];
public function post()
{
return $this->belongsTo(Post::class);
}
}
class User extends Model
{
public $timestamps = false;
public function posts()
{
return $this->hasMany(Post::class);
}
}
| |
192822
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Casts\AsCollection;
use Illuminate\Database\Eloquent\Casts\AsStringable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class DatabaseCustomCastsTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('test_eloquent_model_with_custom_casts', function (Blueprint $table) {
$table->increments('id');
$table->text('array_object');
$table->json('array_object_json');
$table->text('collection');
$table->string('stringable');
$table->string('password');
$table->timestamps();
});
Schema::create('test_eloquent_model_with_custom_casts_nullables', function (Blueprint $table) {
$table->increments('id');
$table->text('array_object')->nullable();
$table->json('array_object_json')->nullable();
$table->text('collection')->nullable();
$table->string('stringable')->nullable();
$table->timestamps();
});
}
public function test_custom_casting()
{
$model = new TestEloquentModelWithCustomCasts;
$model->array_object = ['name' => 'Taylor'];
$model->array_object_json = ['name' => 'Taylor'];
$model->collection = collect(['name' => 'Taylor']);
$model->stringable = Str::of('Taylor');
$model->password = Hash::make('secret');
$model->save();
$model = $model->fresh();
$this->assertEquals(['name' => 'Taylor'], $model->array_object->toArray());
$this->assertEquals(['name' => 'Taylor'], $model->array_object_json->toArray());
$this->assertEquals(['name' => 'Taylor'], $model->collection->toArray());
$this->assertSame('Taylor', (string) $model->stringable);
$this->assertTrue(Hash::check('secret', $model->password));
$model->array_object['age'] = 34;
$model->array_object['meta']['title'] = 'Developer';
$model->array_object_json['age'] = 34;
$model->array_object_json['meta']['title'] = 'Developer';
$model->save();
$model = $model->fresh();
$this->assertEquals(
[
'name' => 'Taylor',
'age' => 34,
'meta' => ['title' => 'Developer'],
],
$model->array_object->toArray()
);
$this->assertEquals(
[
'name' => 'Taylor',
'age' => 34,
'meta' => ['title' => 'Developer'],
],
$model->array_object_json->toArray()
);
}
public function test_custom_casting_using_create()
{
$model = TestEloquentModelWithCustomCasts::create([
'array_object' => ['name' => 'Taylor'],
'array_object_json' => ['name' => 'Taylor'],
'collection' => collect(['name' => 'Taylor']),
'stringable' => Str::of('Taylor'),
'password' => Hash::make('secret'),
]);
$model->save();
$model = $model->fresh();
$this->assertEquals(['name' => 'Taylor'], $model->array_object->toArray());
$this->assertEquals(['name' => 'Taylor'], $model->array_object_json->toArray());
$this->assertEquals(['name' => 'Taylor'], $model->collection->toArray());
$this->assertSame('Taylor', (string) $model->stringable);
$this->assertTrue(Hash::check('secret', $model->password));
}
public function test_custom_casting_nullable_values()
{
$model = new TestEloquentModelWithCustomCastsNullable();
$model->array_object = null;
$model->array_object_json = null;
$model->collection = collect();
$model->stringable = null;
$model->save();
$model = $model->fresh();
$this->assertEmpty($model->array_object);
$this->assertEmpty($model->array_object_json);
$this->assertEmpty($model->collection);
$this->assertSame('', (string) $model->stringable);
$model->array_object = ['name' => 'John'];
$model->array_object['name'] = 'Taylor';
$model->array_object['meta']['title'] = 'Developer';
$model->array_object_json = ['name' => 'John'];
$model->array_object_json['name'] = 'Taylor';
$model->array_object_json['meta']['title'] = 'Developer';
$model->save();
$model = $model->fresh();
$this->assertEquals(
[
'name' => 'Taylor',
'meta' => ['title' => 'Developer'],
],
$model->array_object->toArray()
);
$this->assertEquals(
[
'name' => 'Taylor',
'meta' => ['title' => 'Developer'],
],
$model->array_object_json->toArray()
);
}
}
class TestEloquentModelWithCustomCasts extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var string[]
*/
protected $guarded = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'array_object' => AsArrayObject::class,
'array_object_json' => AsArrayObject::class,
'collection' => AsCollection::class,
'stringable' => AsStringable::class,
'password' => 'hashed',
];
}
class TestEloquentModelWithCustomCastsNullable extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var string[]
*/
protected $guarded = [];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'array_object' => AsArrayObject::class,
'array_object_json' => AsArrayObject::class,
'collection' => AsCollection::class,
'stringable' => AsStringable::class,
];
}
| |
192830
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\Eloquent\Collection as DatabaseCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphPivot;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Schema;
class EloquentPivotSerializationTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->timestamps();
});
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('project_users', function (Blueprint $table) {
$table->integer('user_id');
$table->integer('project_id');
});
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
Schema::create('taggables', function (Blueprint $table) {
$table->integer('tag_id');
$table->integer('taggable_id');
$table->string('taggable_type');
});
}
public function testPivotCanBeSerializedAndRestored()
{
$user = PivotSerializationTestUser::forceCreate(['email' => 'taylor@laravel.com']);
$project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
$project->collaborators()->attach($user);
$project = $project->fresh();
$class = new PivotSerializationTestClass($project->collaborators->first()->pivot);
$class = unserialize(serialize($class));
$this->assertEquals($project->collaborators->first()->pivot->user_id, $class->pivot->user_id);
$this->assertEquals($project->collaborators->first()->pivot->project_id, $class->pivot->project_id);
$class->pivot->save();
}
public function testMorphPivotCanBeSerializedAndRestored()
{
$project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
$tag = PivotSerializationTestTag::forceCreate(['name' => 'Test Tag']);
$project->tags()->attach($tag);
$project = $project->fresh();
$class = new PivotSerializationTestClass($project->tags->first()->pivot);
$class = unserialize(serialize($class));
$this->assertEquals($project->tags->first()->pivot->tag_id, $class->pivot->tag_id);
$this->assertEquals($project->tags->first()->pivot->taggable_id, $class->pivot->taggable_id);
$this->assertEquals($project->tags->first()->pivot->taggable_type, $class->pivot->taggable_type);
$class->pivot->save();
}
public function testCollectionOfPivotsCanBeSerializedAndRestored()
{
$user = PivotSerializationTestUser::forceCreate(['email' => 'taylor@laravel.com']);
$user2 = PivotSerializationTestUser::forceCreate(['email' => 'mohamed@laravel.com']);
$project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
$project->collaborators()->attach($user);
$project->collaborators()->attach($user2);
$project = $project->fresh();
$class = new PivotSerializationTestCollectionClass(DatabaseCollection::make($project->collaborators->map->pivot));
$class = unserialize(serialize($class));
$this->assertEquals($project->collaborators[0]->pivot->user_id, $class->pivots[0]->user_id);
$this->assertEquals($project->collaborators[1]->pivot->project_id, $class->pivots[1]->project_id);
}
public function testCollectionOfMorphPivotsCanBeSerializedAndRestored()
{
$tag = PivotSerializationTestTag::forceCreate(['name' => 'Test Tag 1']);
$tag2 = PivotSerializationTestTag::forceCreate(['name' => 'Test Tag 2']);
$project = PivotSerializationTestProject::forceCreate(['name' => 'Test Project']);
$project->tags()->attach($tag);
$project->tags()->attach($tag2);
$project = $project->fresh();
$class = new PivotSerializationTestCollectionClass(DatabaseCollection::make($project->tags->map->pivot));
$class = unserialize(serialize($class));
$this->assertEquals($project->tags[0]->pivot->tag_id, $class->pivots[0]->tag_id);
$this->assertEquals($project->tags[0]->pivot->taggable_id, $class->pivots[0]->taggable_id);
$this->assertEquals($project->tags[0]->pivot->taggable_type, $class->pivots[0]->taggable_type);
$this->assertEquals($project->tags[1]->pivot->tag_id, $class->pivots[1]->tag_id);
$this->assertEquals($project->tags[1]->pivot->taggable_id, $class->pivots[1]->taggable_id);
$this->assertEquals($project->tags[1]->pivot->taggable_type, $class->pivots[1]->taggable_type);
}
}
class PivotSerializationTestClass
{
use SerializesModels;
public $pivot;
public function __construct($pivot)
{
$this->pivot = $pivot;
}
}
class PivotSerializationTestCollectionClass
{
use SerializesModels;
public $pivots;
public function __construct($pivots)
{
$this->pivots = $pivots;
}
}
class PivotSerializationTestUser extends Model
{
public $table = 'users';
}
class PivotSerializationTestProject extends Model
{
public $table = 'projects';
public function collaborators()
{
return $this->belongsToMany(
PivotSerializationTestUser::class, 'project_users', 'project_id', 'user_id'
)->using(PivotSerializationTestCollaborator::class);
}
public function tags()
{
return $this->morphToMany(PivotSerializationTestTag::class, 'taggable', 'taggables', 'taggable_id', 'tag_id')
->using(PivotSerializationTestTagAttachment::class);
}
}
class PivotSerializationTestTag extends Model
{
public $table = 'tags';
public function projects()
{
return $this->morphedByMany(PivotSerializationTestProject::class, 'taggable', 'taggables', 'tag_id', 'taggable_id')
->using(PivotSerializationTestTagAttachment::class);
}
}
class PivotSerializationTestCollaborator extends Pivot
{
public $table = 'project_users';
public $timestamps = false;
}
class PivotSerializationTestTagAttachment extends MorphPivot
{
public $table = 'taggables';
public $timestamps = false;
}
| |
192836
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Orchestra\Testbench\TestCase;
class EloquentTransactionWithAfterCommitUsingDatabaseTransactionsTest extends TestCase
{
use EloquentTransactionWithAfterCommitTests;
use DatabaseTransactions;
/**
* The current database driver.
*
* @return string
*/
protected $driver;
protected function setUp(): void
{
$this->beforeApplicationDestroyed(function () {
foreach (array_keys($this->app['db']->getConnections()) as $name) {
$this->app['db']->purge($name);
}
});
parent::setUp();
if ($this->usesSqliteInMemoryDatabaseConnection()) {
$this->markTestSkipped('Test cannot be used with in-memory SQLite connection.');
}
}
protected function getEnvironmentSetUp($app)
{
$connection = $app->make('config')->get('database.default');
$this->driver = $app['config']->get("database.connections.$connection.driver");
}
}
| |
192839
|
#[DataProvider('connectionProvider')]
public function testModifyColumns($connection)
{
$schema = Schema::connection($connection);
$schema->create('my_schema.table', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('count');
});
$schema->create('my_table', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('count');
});
$schema->table('my_schema.table', function (Blueprint $table) {
$table->string('name')->default('default schema name')->change();
$table->bigInteger('count')->change();
});
$schema->table('my_table', function (Blueprint $table) {
$table->string('title')->default('default title')->change();
$table->bigInteger('count')->change();
});
$this->assertStringContainsString('default schema name', collect($schema->getColumns('my_schema.table'))->firstWhere('name', 'name')['default']);
$this->assertStringContainsString('default title', collect($schema->getColumns('my_table'))->firstWhere('name', 'title')['default']);
$this->assertEquals($this->driver === 'sqlsrv' ? 'nvarchar' : 'varchar', $schema->getColumnType('my_schema.table', 'name'));
$this->assertEquals($this->driver === 'sqlsrv' ? 'nvarchar' : 'varchar', $schema->getColumnType('my_table', 'title'));
$this->assertEquals($this->driver === 'pgsql' ? 'int8' : 'bigint', $schema->getColumnType('my_schema.table', 'count'));
$this->assertEquals($this->driver === 'pgsql' ? 'int8' : 'bigint', $schema->getColumnType('my_table', 'count'));
}
#[DataProvider('connectionProvider')]
public function testDropColumns($connection)
{
$schema = Schema::connection($connection);
$schema->create('my_schema.table', function (Blueprint $table) {
$table->id();
$table->string('name')->default('default schema name');
$table->integer('count')->default(20);
$table->string('title')->default('default schema title');
});
$schema->create('table', function (Blueprint $table) {
$table->id();
$table->string('name')->default('default name');
$table->integer('count')->default(10);
$table->string('title')->default('default title');
});
$this->assertTrue($schema->hasColumns('my_schema.table', ['id', 'name', 'count', 'title']));
$this->assertTrue($schema->hasColumns('table', ['id', 'name', 'count', 'title']));
$schema->dropColumns('my_schema.table', ['name', 'count']);
$schema->dropColumns('table', ['name', 'title']);
$this->assertTrue($schema->hasColumns('my_schema.table', ['id', 'title']));
$this->assertFalse($schema->hasColumn('my_schema.table', 'name'));
$this->assertFalse($schema->hasColumn('my_schema.table', 'count'));
$this->assertTrue($schema->hasColumns('table', ['id', 'count']));
$this->assertFalse($schema->hasColumn('table', 'name'));
$this->assertFalse($schema->hasColumn('table', 'title'));
$this->assertStringContainsString('default schema title', collect($schema->getColumns('my_schema.table'))->firstWhere('name', 'title')['default']);
$this->assertStringContainsString('10', collect($schema->getColumns('table'))->firstWhere('name', 'count')['default']);
}
#[DataProvider('connectionProvider')]
public function testIndexes($connection)
{
$schema = Schema::connection($connection);
$schema->create('my_schema.table', function (Blueprint $table) {
$table->string('code')->primary();
$table->string('email')->unique();
$table->integer('name')->index();
$table->integer('title')->index();
});
$schema->create('my_table', function (Blueprint $table) {
$table->string('code')->primary();
$table->string('email')->unique();
$table->integer('name')->index();
$table->integer('title')->index();
});
$this->assertTrue($schema->hasIndex('my_schema.table', ['code'], 'primary'));
$this->assertTrue($schema->hasIndex('my_schema.table', ['email'], 'unique'));
$this->assertTrue($schema->hasIndex('my_schema.table', ['name']));
$this->assertTrue($schema->hasIndex('my_table', ['code'], 'primary'));
$this->assertTrue($schema->hasIndex('my_table', ['email'], 'unique'));
$this->assertTrue($schema->hasIndex('my_table', ['name']));
$schemaIndexName = $connection === 'with-prefix' ? 'my_schema_example_table_title_index' : 'my_schema_table_title_index';
$indexName = $connection === 'with-prefix' ? 'example_my_table_title_index' : 'my_table_title_index';
$schema->table('my_schema.table', function (Blueprint $table) use ($schemaIndexName) {
$table->renameIndex($schemaIndexName, 'schema_new_index_name');
});
$schema->table('my_table', function (Blueprint $table) use ($indexName) {
$table->renameIndex($indexName, 'new_index_name');
});
$this->assertTrue($schema->hasIndex('my_schema.table', 'schema_new_index_name'));
$this->assertFalse($schema->hasIndex('my_schema.table', $schemaIndexName));
$this->assertTrue($schema->hasIndex('my_table', 'new_index_name'));
$this->assertFalse($schema->hasIndex('my_table', $indexName));
$schema->table('my_schema.table', function (Blueprint $table) {
$table->dropPrimary(['code']);
$table->dropUnique(['email']);
$table->dropIndex(['name']);
$table->dropIndex('schema_new_index_name');
});
$schema->table('my_table', function (Blueprint $table) {
$table->dropPrimary(['code']);
$table->dropUnique(['email']);
$table->dropIndex(['name']);
$table->dropIndex('new_index_name');
});
$this->assertEmpty($schema->getIndexListing('my_schema.table'));
$this->assertEmpty($schema->getIndexListing('my_table'));
}
#[DataProvider('connectionProvider')]
public function testForeignKeys($connection)
{
$schema = Schema::connection($connection);
$schema->create('my_tables', function (Blueprint $table) {
$table->id();
});
$schema->create('my_schema.table', function (Blueprint $table) {
$table->id();
$table->foreignId('my_table_id')->constrained();
});
$schema->create('table', function (Blueprint $table) {
$table->unsignedBigInteger('table_id');
$table->foreign('table_id')->references('id')->on('my_schema.table');
});
$schemaTableName = $connection === 'with-prefix' ? 'example_table' : 'table';
$tableName = $connection === 'with-prefix' ? 'example_my_tables' : 'my_tables';
$this->assertTrue(collect($schema->getForeignKeys('my_schema.table'))->contains(
fn ($foreign) => $foreign['columns'] === ['my_table_id']
&& $foreign['foreign_table'] === $tableName && in_array($foreign['foreign_schema'], ['public', 'dbo'])
&& $foreign['foreign_columns'] === ['id']
));
$this->assertTrue(collect($schema->getForeignKeys('table'))->contains(
fn ($foreign) => $foreign['columns'] === ['table_id']
&& $foreign['foreign_table'] === $schemaTableName && $foreign['foreign_schema'] === 'my_schema'
&& $foreign['foreign_columns'] === ['id']
));
$schema->table('my_schema.table', function (Blueprint $table) {
$table->dropForeign(['my_table_id']);
});
$schema->table('table', function (Blueprint $table) {
$table->dropForeign(['table_id']);
});
$this->assertEmpty($schema->getForeignKeys('my_schema.table'));
$this->assertEmpty($schema->getForeignKeys('table'));
}
| |
192843
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Database\Eloquent\Casts\ArrayObject;
use Illuminate\Database\Eloquent\Casts\AsEncryptedArrayObject;
use Illuminate\Database\Eloquent\Casts\AsEncryptedCollection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Schema;
use stdClass;
class EloquentModelEncryptedCastingTest extends DatabaseTestCase
{
protected $encrypter;
protected function setUp(): void
{
parent::setUp();
$this->encrypter = $this->mock(Encrypter::class);
Crypt::swap($this->encrypter);
Model::$encrypter = null;
}
protected function afterRefreshingDatabase()
{
Schema::create('encrypted_casts', function (Blueprint $table) {
$table->increments('id');
$table->string('secret', 1000)->nullable();
$table->text('secret_array')->nullable();
$table->text('secret_json')->nullable();
$table->text('secret_object')->nullable();
$table->text('secret_collection')->nullable();
});
}
public function testStringsAreCastable()
{
$this->encrypter->expects('encrypt')
->with('this is a secret string', false)
->andReturn('encrypted-secret-string');
$this->encrypter->expects('decrypt')
->with('encrypted-secret-string', false)
->andReturn('this is a secret string');
/** @var \Illuminate\Tests\Integration\Database\EncryptedCast $subject */
$subject = EncryptedCast::create([
'secret' => 'this is a secret string',
]);
$this->assertSame('this is a secret string', $subject->secret);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret' => 'encrypted-secret-string',
]);
}
public function testArraysAreCastable()
{
$this->encrypter->expects('encrypt')
->with('{"key1":"value1"}', false)
->andReturn('encrypted-secret-array-string');
$this->encrypter->expects('decrypt')
->with('encrypted-secret-array-string', false)
->andReturn('{"key1":"value1"}');
/** @var \Illuminate\Tests\Integration\Database\EncryptedCast $subject */
$subject = EncryptedCast::create([
'secret_array' => ['key1' => 'value1'],
]);
$this->assertSame(['key1' => 'value1'], $subject->secret_array);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_array' => 'encrypted-secret-array-string',
]);
}
public function testJsonIsCastable()
{
$this->encrypter->expects('encrypt')
->with('{"key1":"value1"}', false)
->andReturn('encrypted-secret-json-string');
$this->encrypter->expects('decrypt')
->with('encrypted-secret-json-string', false)
->andReturn('{"key1":"value1"}');
/** @var \Illuminate\Tests\Integration\Database\EncryptedCast $subject */
$subject = EncryptedCast::create([
'secret_json' => ['key1' => 'value1'],
]);
$this->assertSame(['key1' => 'value1'], $subject->secret_json);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_json' => 'encrypted-secret-json-string',
]);
}
public function testJsonAttributeIsCastable()
{
$this->encrypter->expects('encrypt')
->with('{"key1":"value1"}', false)
->andReturn('encrypted-secret-json-string');
$this->encrypter->expects('decrypt')
->with('encrypted-secret-json-string', false)
->andReturn('{"key1":"value1"}');
$this->encrypter->expects('encrypt')
->with('{"key1":"value1","key2":"value2"}', false)
->andReturn('encrypted-secret-json-string2');
$this->encrypter->expects('decrypt')
->with('encrypted-secret-json-string2', false)
->andReturn('{"key1":"value1","key2":"value2"}');
$subject = new EncryptedCast([
'secret_json' => ['key1' => 'value1'],
]);
$subject->fill([
'secret_json->key2' => 'value2',
]);
$subject->save();
$this->assertSame(['key1' => 'value1', 'key2' => 'value2'], $subject->secret_json);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_json' => 'encrypted-secret-json-string2',
]);
}
public function testObjectIsCastable()
{
$object = new stdClass;
$object->key1 = 'value1';
$this->encrypter->expects('encrypt')
->with('{"key1":"value1"}', false)
->andReturn('encrypted-secret-object-string');
$this->encrypter->expects('decrypt')
->twice()
->with('encrypted-secret-object-string', false)
->andReturn('{"key1":"value1"}');
/** @var \Illuminate\Tests\Integration\Database\EncryptedCast $object */
$object = EncryptedCast::create([
'secret_object' => $object,
]);
$this->assertInstanceOf(stdClass::class, $object->secret_object);
$this->assertSame('value1', $object->secret_object->key1);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $object->id,
'secret_object' => 'encrypted-secret-object-string',
]);
}
public function testCollectionIsCastable()
{
$this->encrypter->expects('encrypt')
->with('{"key1":"value1"}', false)
->andReturn('encrypted-secret-collection-string');
$this->encrypter->expects('decrypt')
->twice()
->with('encrypted-secret-collection-string', false)
->andReturn('{"key1":"value1"}');
/** @var \Illuminate\Tests\Integration\Database\EncryptedCast $subject */
$subject = EncryptedCast::create([
'secret_collection' => new Collection(['key1' => 'value1']),
]);
$this->assertInstanceOf(Collection::class, $subject->secret_collection);
$this->assertSame('value1', $subject->secret_collection->get('key1'));
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_collection' => 'encrypted-secret-collection-string',
]);
}
public function testAsEncryptedCollection()
{
$this->encrypter->expects('encryptString')
->twice()
->with('{"key1":"value1"}')
->andReturn('encrypted-secret-collection-string-1');
$this->encrypter->expects('encryptString')
->times(10)
->with('{"key1":"value1","key2":"value2"}')
->andReturn('encrypted-secret-collection-string-2');
$this->encrypter->expects('decryptString')
->once()
->with('encrypted-secret-collection-string-2')
->andReturn('{"key1":"value1","key2":"value2"}');
$subject = new EncryptedCast;
$subject->mergeCasts(['secret_collection' => AsEncryptedCollection::class]);
$subject->secret_collection = new Collection(['key1' => 'value1']);
$subject->secret_collection->put('key2', 'value2');
$subject->save();
$this->assertInstanceOf(Collection::class, $subject->secret_collection);
$this->assertSame('value1', $subject->secret_collection->get('key1'));
$this->assertSame('value2', $subject->secret_collection->get('key2'));
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_collection' => 'encrypted-secret-collection-string-2',
]);
$subject = $subject->fresh();
$this->assertInstanceOf(Collection::class, $subject->secret_collection);
$this->assertSame('value1', $subject->secret_collection->get('key1'));
$this->assertSame('value2', $subject->secret_collection->get('key2'));
$subject->secret_collection = null;
$subject->save();
$this->assertNull($subject->secret_collection);
$this->assertDatabaseHas('encrypted_casts', [
'id' => $subject->id,
'secret_collection' => null,
]);
$this->assertNull($subject->fresh()->secret_collection);
}
| |
192861
|
public function testOrWherePivotOnBoolean()
{
$tag = Tag::create(['name' => Str::random()])->fresh();
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => true, 'isActive' => false],
]);
$relationTag = $post->tags()->wherePivot('isActive', false)->orWherePivot('flag', true)->first();
$this->assertEquals($relationTag->getAttributes(), $tag->getAttributes());
}
public function testWherePivotNotBetween()
{
$tag = Tag::create(['name' => Str::random()])->fresh();
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => true, 'isActive' => false],
]);
$relationTag = $post->tags()
->wherePivotNotBetween('isActive', ['true', 'false'])
->orWherePivotNotBetween('flag', ['true', 'false'])
->first();
$this->assertEquals($relationTag->getAttributes(), $tag->getAttributes());
}
public function testWherePivotInMethod()
{
$tag = Tag::create(['name' => Str::random()])->fresh();
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'foo'],
]);
$relationTag = $post->tags()->wherePivotIn('flag', ['foo'])->first();
$this->assertEquals($relationTag->getAttributes(), $tag->getAttributes());
}
public function testOrWherePivotInMethod()
{
$tag1 = Tag::create(['name' => Str::random()]);
$tag2 = Tag::create(['name' => Str::random()]);
$tag3 = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => 'bar'],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag3->id, 'flag' => 'baz'],
]);
$relationTags = $post->tags()->wherePivotIn('flag', ['foo'])->orWherePivotIn('flag', ['baz'])->get();
$this->assertEquals($relationTags->pluck('id')->toArray(), [$tag1->id, $tag3->id]);
}
public function testWherePivotNotInMethod()
{
$tag1 = Tag::create(['name' => Str::random()]);
$tag2 = Tag::create(['name' => Str::random()])->fresh();
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => 'bar'],
]);
$relationTag = $post->tags()->wherePivotNotIn('flag', ['foo'])->first();
$this->assertEquals($relationTag->getAttributes(), $tag2->getAttributes());
}
public function testOrWherePivotNotInMethod()
{
$tag1 = Tag::create(['name' => Str::random()]);
$tag2 = Tag::create(['name' => Str::random()]);
$tag3 = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => 'bar'],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag3->id, 'flag' => 'baz'],
]);
$relationTags = $post->tags()->wherePivotIn('flag', ['foo'])->orWherePivotNotIn('flag', ['baz'])->get();
$this->assertEquals($relationTags->pluck('id')->toArray(), [$tag1->id, $tag2->id]);
}
public function testWherePivotNullMethod()
{
$tag1 = Tag::create(['name' => Str::random()]);
$tag2 = Tag::create(['name' => Str::random()])->fresh();
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo'],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => null],
]);
$relationTag = $post->tagsWithExtraPivot()->wherePivotNull('flag')->first();
$this->assertEquals($relationTag->getAttributes(), $tag2->getAttributes());
}
public function testWherePivotNotNullMethod()
{
$tag1 = Tag::create(['name' => Str::random()])->fresh();
$tag2 = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo', 'isActive' => true],
]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => null, 'isActive' => false],
]);
$relationTag = $post->tagsWithExtraPivot()->wherePivotNotNull('flag')->orWherePivotNotNull('isActive')->first();
$this->assertEquals($relationTag->getAttributes(), $tag1->getAttributes());
}
public function testCanUpdateExistingPivot()
{
$tag = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'],
]);
$post->tagsWithExtraPivot()->updateExistingPivot($tag->id, ['flag' => 'exclude']);
foreach ($post->tagsWithExtraPivot as $tag) {
$this->assertSame('exclude', $tag->pivot->flag);
}
}
public function testCanUpdateExistingPivotUsingArrayableOfIds()
{
$tags = new Collection([
$tag1 = Tag::create(['name' => Str::random()]),
$tag2 = Tag::create(['name' => Str::random()]),
]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'empty'],
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => 'empty'],
]);
$post->tagsWithExtraPivot()->updateExistingPivot($tags, ['flag' => 'exclude']);
foreach ($post->tagsWithExtraPivot as $tag) {
$this->assertSame('exclude', $tag->pivot->flag);
}
}
| |
192862
|
public function testCanUpdateExistingPivotUsingModel()
{
$tag = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'],
]);
$post->tagsWithExtraPivot()->updateExistingPivot($tag, ['flag' => 'exclude']);
foreach ($post->tagsWithExtraPivot as $tag) {
$this->assertSame('exclude', $tag->pivot->flag);
}
}
public function testCustomRelatedKey()
{
$post = Post::create(['title' => Str::random()]);
$tag = $post->tagsWithCustomRelatedKey()->create(['name' => Str::random()]);
$this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_name);
$post->tagsWithCustomRelatedKey()->detach($tag);
$post->tagsWithCustomRelatedKey()->attach($tag);
$this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_name);
$post->tagsWithCustomRelatedKey()->detach(new Collection([$tag]));
$post->tagsWithCustomRelatedKey()->attach(new Collection([$tag]));
$this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_name);
$post->tagsWithCustomRelatedKey()->updateExistingPivot($tag, ['flag' => 'exclude']);
$this->assertSame('exclude', $post->tagsWithCustomRelatedKey()->first()->pivot->flag);
}
public function testGlobalScopeColumns()
{
$tag = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'],
]);
$tags = $post->tagsWithGlobalScope;
$this->assertEquals(['id' => 1], $tags[0]->getAttributes());
}
public function testPivotDoesntHavePrimaryKey()
{
$user = User::create(['name' => Str::random()]);
$post1 = Post::create(['title' => Str::random()]);
$post2 = Post::create(['title' => Str::random()]);
$user->postsWithCustomPivot()->sync([$post1->uuid]);
$this->assertEquals($user->uuid, $user->postsWithCustomPivot()->first()->pivot->user_uuid);
$this->assertEquals($post1->uuid, $user->postsWithCustomPivot()->first()->pivot->post_uuid);
$this->assertEquals(1, $user->postsWithCustomPivot()->first()->pivot->is_draft);
$user->postsWithCustomPivot()->sync([$post2->uuid]);
$this->assertEquals($user->uuid, $user->postsWithCustomPivot()->first()->pivot->user_uuid);
$this->assertEquals($post2->uuid, $user->postsWithCustomPivot()->first()->pivot->post_uuid);
$this->assertEquals(1, $user->postsWithCustomPivot()->first()->pivot->is_draft);
$user->postsWithCustomPivot()->updateExistingPivot($post2->uuid, ['is_draft' => 0]);
$this->assertEquals(0, $user->postsWithCustomPivot()->first()->pivot->is_draft);
}
public function testOrderByPivotMethod()
{
$tag1 = Tag::create(['name' => Str::random()]);
$tag2 = Tag::create(['name' => Str::random()])->fresh();
$tag3 = Tag::create(['name' => Str::random()])->fresh();
$tag4 = Tag::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag1->id, 'flag' => 'foo3'],
['post_id' => $post->id, 'tag_id' => $tag2->id, 'flag' => 'foo1'],
['post_id' => $post->id, 'tag_id' => $tag3->id, 'flag' => 'foo4'],
['post_id' => $post->id, 'tag_id' => $tag4->id, 'flag' => 'foo2'],
]);
$relationTag1 = $post->tagsWithCustomExtraPivot()->orderByPivot('flag', 'asc')->first();
$this->assertEquals($relationTag1->getAttributes(), $tag2->getAttributes());
$relationTag2 = $post->tagsWithCustomExtraPivot()->orderByPivot('flag', 'desc')->first();
$this->assertEquals($relationTag2->getAttributes(), $tag3->getAttributes());
}
public function testFirstOrMethod()
{
$user1 = User::create(['name' => Str::random()]);
$user2 = User::create(['name' => Str::random()]);
$user3 = User::create(['name' => Str::random()]);
$post1 = Post::create(['title' => Str::random()]);
$post2 = Post::create(['title' => Str::random()]);
$post3 = Post::create(['title' => Str::random()]);
$user1->posts()->sync([$post1->uuid, $post2->uuid]);
$user2->posts()->sync([$post1->uuid, $post2->uuid]);
$this->assertEquals(
$post1->id,
$user2->posts()->firstOr(function () {
return Post::create(['title' => Str::random()]);
})->id
);
$this->assertEquals(
$post3->id,
$user3->posts()->firstOr(function () use ($post3) {
return $post3;
})->id
);
}
public function testUpdateOrCreateQueryBuilderIsolation()
{
$user = User::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
$user->postsWithCustomPivot()->attach($post);
$instance = $user->postsWithCustomPivot()->updateOrCreate(
['uuid' => $post->uuid],
['title' => Str::random()],
);
$this->assertArrayNotHasKey(
'user_uuid',
$instance->toArray(),
);
}
public function testFirstOrCreateQueryBuilderIsolation()
{
$user = User::create(['name' => Str::random()]);
$post = Post::create(['title' => Str::random()]);
$user->postsWithCustomPivot()->attach($post);
$instance = $user->postsWithCustomPivot()->firstOrCreate(
['uuid' => $post->uuid],
['title' => Str::random()],
);
$this->assertArrayNotHasKey(
'user_uuid',
$instance->toArray(),
);
}
}
class User extends Model
{
public $table = 'users';
public $timestamps = true;
protected $guarded = [];
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->setAttribute('uuid', Str::random());
});
}
public function posts()
{
return $this->belongsToMany(Post::class, 'users_posts', 'user_uuid', 'post_uuid', 'uuid', 'uuid')
->withPivot('is_draft')
->withTimestamps();
}
public function postsWithCustomPivot()
{
return $this->belongsToMany(Post::class, 'users_posts', 'user_uuid', 'post_uuid', 'uuid', 'uuid')
->using(UserPostPivot::class)
->withPivot('is_draft')
->withTimestamps();
}
}
class PostStringPrimaryKey extends Model
{
public $incrementing = false;
public $timestamps = false;
protected $table = 'post_string_key';
protected $keyType = 'string';
protected $fillable = ['title', 'id'];
public function tags()
{
return $this->belongsToMany(TagStringPrimaryKey::class, 'post_tag_string_key', 'post_id', 'tag_id');
}
}
class TagStringPrimaryKey extends Model
{
public $incrementing = false;
public $timestamps = false;
protected $table = 'tag_string_key';
protected $keyType = 'string';
protected $fillable = ['title', 'id'];
public function posts()
{
return $this->belongsToMany(PostStringPrimaryKey::class, 'post_tag_string_key', 'tag_id', 'post_id');
}
}
| |
192863
|
class Post extends Model
{
public $table = 'posts';
public $timestamps = true;
protected $guarded = [];
protected $touches = ['touchingTags'];
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
$model->setAttribute('uuid', Str::random());
});
}
public function users()
{
return $this->belongsToMany(User::class, 'users_posts', 'post_uuid', 'user_uuid', 'uuid', 'uuid')
->withPivot('is_draft')
->withTimestamps();
}
public function tags()
{
return $this->belongsToMany(Tag::class, 'posts_tags', 'post_id', 'tag_id')
->withPivot('flag')
->withTimestamps()
->wherePivot('flag', '<>', 'exclude');
}
public function tagsUnique()
{
return $this->belongsToMany(UniqueTag::class, 'posts_unique_tags', 'post_id', 'tag_id')
->withPivot('flag')
->withTimestamps()
->wherePivot('flag', '<>', 'exclude');
}
public function tagsWithExtraPivot()
{
return $this->belongsToMany(Tag::class, 'posts_tags', 'post_id', 'tag_id')
->withPivot('flag');
}
public function touchingTags()
{
return $this->belongsToMany(TouchingTag::class, 'posts_tags', 'post_id', 'tag_id')
->withTimestamps();
}
public function tagsWithCustomPivot()
{
return $this->belongsToMany(TagWithCustomPivot::class, 'posts_tags', 'post_id', 'tag_id')
->using(PostTagPivot::class)
->withTimestamps();
}
public function tagsWithCustomExtraPivot()
{
return $this->belongsToMany(TagWithCustomPivot::class, 'posts_tags', 'post_id', 'tag_id')
->using(PostTagPivot::class)
->withTimestamps()
->withPivot('flag');
}
public function tagsWithCustomPivotClass()
{
return $this->belongsToMany(TagWithCustomPivot::class, PostTagPivot::class, 'post_id', 'tag_id');
}
public function tagsWithCustomAccessor()
{
return $this->belongsToMany(TagWithCustomPivot::class, 'posts_tags', 'post_id', 'tag_id')
->using(PostTagPivot::class)
->as('tag');
}
public function tagsWithCustomRelatedKey()
{
return $this->belongsToMany(Tag::class, 'posts_tags', 'post_id', 'tag_name', 'id', 'name')
->withPivot('flag');
}
public function tagsWithGlobalScope()
{
return $this->belongsToMany(TagWithGlobalScope::class, 'posts_tags', 'post_id', 'tag_id');
}
}
class Tag extends Model
{
public $table = 'tags';
public $timestamps = true;
protected $fillable = ['name', 'type'];
public function posts()
{
return $this->belongsToMany(Post::class, 'posts_tags', 'tag_id', 'post_id');
}
}
class UniqueTag extends Model
{
public $table = 'unique_tags';
public $timestamps = true;
protected $fillable = ['name', 'type'];
public function posts()
{
return $this->belongsToMany(Post::class, 'posts_unique_tags', 'tag_id', 'post_id');
}
}
class TouchingTag extends Model
{
public $table = 'tags';
public $timestamps = true;
protected $guarded = [];
protected $touches = ['posts'];
public function posts()
{
return $this->belongsToMany(Post::class, 'posts_tags', 'tag_id', 'post_id');
}
}
class TagWithCustomPivot extends Model
{
public $table = 'tags';
public $timestamps = true;
protected $guarded = [];
public function posts()
{
return $this->belongsToMany(Post::class, 'posts_tags', 'tag_id', 'post_id');
}
}
class UserPostPivot extends Pivot
{
protected $table = 'users_posts';
}
class PostTagPivot extends Pivot
{
protected $table = 'posts_tags';
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->format('U');
}
}
class TagWithGlobalScope extends Model
{
public $table = 'tags';
public $timestamps = true;
protected $guarded = [];
public static function boot()
{
parent::boot();
static::addGlobalScope(function ($query) {
$query->select('tags.id');
});
}
}
| |
192867
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentMorphEagerLoadingTest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
class EloquentMorphEagerLoadingTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->softDeletes();
});
Schema::create('posts', function (Blueprint $table) {
$table->increments('post_id');
$table->unsignedInteger('user_id');
});
Schema::create('videos', function (Blueprint $table) {
$table->increments('video_id');
});
Schema::create('actions', function (Blueprint $table) {
$table->increments('id');
$table->string('target_type');
$table->integer('target_id');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('commentable_type');
$table->integer('commentable_id');
});
$user = User::create();
$user2 = User::forceCreate(['deleted_at' => now()]);
$post = tap((new Post)->user()->associate($user))->save();
$video = Video::create();
(new Comment)->commentable()->associate($post)->save();
(new Comment)->commentable()->associate($video)->save();
(new Action)->target()->associate($video)->save();
(new Action)->target()->associate($user2)->save();
}
public function testWithMorphLoading()
{
$comments = Comment::query()
->with(['commentable' => function (MorphTo $morphTo) {
$morphTo->morphWith([Post::class => ['user']]);
}])
->get();
$this->assertCount(2, $comments);
$this->assertTrue($comments[0]->relationLoaded('commentable'));
$this->assertInstanceOf(Post::class, $comments[0]->getRelation('commentable'));
$this->assertTrue($comments[0]->commentable->relationLoaded('user'));
$this->assertTrue($comments[1]->relationLoaded('commentable'));
$this->assertInstanceOf(Video::class, $comments[1]->getRelation('commentable'));
}
public function testWithMorphLoadingWithSingleRelation()
{
$comments = Comment::query()
->with(['commentable' => function (MorphTo $morphTo) {
$morphTo->morphWith([Post::class => 'user']);
}])
->get();
$this->assertTrue($comments[0]->relationLoaded('commentable'));
$this->assertTrue($comments[0]->commentable->relationLoaded('user'));
}
public function testMorphLoadingMixedWithTrashedRelations()
{
$action = Action::query()
->with('target')
->get();
$this->assertCount(2, $action);
$this->assertTrue($action[0]->relationLoaded('target'));
$this->assertInstanceOf(Video::class, $action[0]->getRelation('target'));
$this->assertTrue($action[1]->relationLoaded('target'));
$this->assertInstanceOf(User::class, $action[1]->getRelation('target'));
}
public function testMorphWithTrashedRelationLazyLoading()
{
$deletedUser = User::forceCreate(['deleted_at' => now()]);
$action = new Action;
$action->target()->associate($deletedUser)->save();
// model is already set via associate and not retrieved from the database
$this->assertInstanceOf(User::class, $action->target);
$action->unsetRelation('target');
$this->assertInstanceOf(User::class, $action->target);
}
}
class Action extends Model
{
public $timestamps = false;
public function target()
{
return $this->morphTo()->withTrashed();
}
}
class Comment extends Model
{
public $timestamps = false;
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public $timestamps = false;
protected $primaryKey = 'post_id';
public function user()
{
return $this->belongsTo(User::class);
}
}
class User extends Model
{
use SoftDeletes;
public $timestamps = false;
}
class Video extends Model
{
public $timestamps = false;
protected $primaryKey = 'video_id';
}
| |
192871
|
public function testOrWhereMonthWithInvalidOperator()
{
$sql = DB::table('posts')->where('id', 1)->orWhereMonth('created_at', '? OR 1=1', '01');
PHPUnit::assertArraySubset([
[
'column' => 'id',
'type' => 'Basic',
'value' => 1,
'boolean' => 'and',
],
[
'column' => 'created_at',
'type' => 'Month',
'value' => '00',
'boolean' => 'or',
],
], $sql->wheres);
$this->assertSame(1, $sql->count());
}
public function testWhereYear()
{
$this->assertSame(1, DB::table('posts')->whereYear('created_at', '2018')->count());
$this->assertSame(1, DB::table('posts')->whereYear('created_at', 2018)->count());
$this->assertSame(1, DB::table('posts')->whereYear('created_at', new Carbon('2018-01-02'))->count());
}
#[DefineEnvironment('defineEnvironmentWouldThrowsPDOException')]
public function testWhereYearWithInvalidOperator()
{
$sql = DB::table('posts')->whereYear('created_at', '? OR 1=1', '2018');
PHPUnit::assertArraySubset([
[
'column' => 'created_at',
'type' => 'Year',
'value' => '? OR 1=1',
'boolean' => 'and',
],
], $sql->wheres);
$this->assertSame(0, $sql->count());
}
public function testOrWhereYear()
{
$this->assertSame(2, DB::table('posts')->where('id', 1)->orWhereYear('created_at', '2018')->count());
$this->assertSame(2, DB::table('posts')->where('id', 1)->orWhereYear('created_at', 2018)->count());
$this->assertSame(2, DB::table('posts')->where('id', 1)->orWhereYear('created_at', new Carbon('2018-01-02'))->count());
}
#[DefineEnvironment('defineEnvironmentWouldThrowsPDOException')]
public function testOrWhereYearWithInvalidOperator()
{
$sql = DB::table('posts')->where('id', 1)->orWhereYear('created_at', '? OR 1=1', '2018');
PHPUnit::assertArraySubset([
[
'column' => 'id',
'type' => 'Basic',
'value' => 1,
'boolean' => 'and',
],
[
'column' => 'created_at',
'type' => 'Year',
'value' => '? OR 1=1',
'boolean' => 'or',
],
], $sql->wheres);
$this->assertSame(1, $sql->count());
}
public function testWhereTime()
{
$this->assertSame(1, DB::table('posts')->whereTime('created_at', '03:04:05')->count());
$this->assertSame(1, DB::table('posts')->whereTime('created_at', new Carbon('2018-01-02 03:04:05'))->count());
}
#[DefineEnvironment('defineEnvironmentWouldThrowsPDOException')]
public function testWhereTimeWithInvalidOperator()
{
$sql = DB::table('posts')->whereTime('created_at', '? OR 1=1', '03:04:05');
PHPUnit::assertArraySubset([
[
'column' => 'created_at',
'type' => 'Time',
'value' => '? OR 1=1',
'boolean' => 'and',
],
], $sql->wheres);
$this->assertSame(0, $sql->count());
}
public function testOrWhereTime()
{
$this->assertSame(2, DB::table('posts')->where('id', 1)->orWhereTime('created_at', '03:04:05')->count());
$this->assertSame(2, DB::table('posts')->where('id', 1)->orWhereTime('created_at', new Carbon('2018-01-02 03:04:05'))->count());
}
#[DefineEnvironment('defineEnvironmentWouldThrowsPDOException')]
public function testOrWhereTimeWithInvalidOperator()
{
$sql = DB::table('posts')->where('id', 1)->orWhereTime('created_at', '? OR 1=1', '03:04:05');
PHPUnit::assertArraySubset([
[
'column' => 'id',
'type' => 'Basic',
'value' => 1,
'boolean' => 'and',
],
[
'column' => 'created_at',
'type' => 'Time',
'value' => '? OR 1=1',
'boolean' => 'or',
],
], $sql->wheres);
$this->assertSame(1, $sql->count());
}
public function testWhereNested()
{
$results = DB::table('posts')->where('content', 'Lorem Ipsum.')->whereNested(function ($query) {
$query->where('title', 'Foo Post')
->orWhere('title', 'Bar Post');
})->count();
$this->assertSame(2, $results);
}
public function testPaginateWithSpecificColumns()
{
$result = DB::table('posts')->paginate(5, ['title', 'content']);
$this->assertInstanceOf(LengthAwarePaginator::class, $result);
$this->assertEquals($result->items(), [
(object) ['title' => 'Foo Post', 'content' => 'Lorem Ipsum.'],
(object) ['title' => 'Bar Post', 'content' => 'Lorem Ipsum.'],
]);
}
public function testChunkMap()
{
DB::enableQueryLog();
$results = DB::table('posts')->orderBy('id')->chunkMap(function ($post) {
return $post->title;
}, 1);
$this->assertCount(2, $results);
$this->assertSame('Foo Post', $results[0]);
$this->assertSame('Bar Post', $results[1]);
$this->assertCount(3, DB::getQueryLog());
}
public function testPluck()
{
// Test SELECT override, since pluck will take the first column.
$this->assertSame([
'Foo Post',
'Bar Post',
], DB::table('posts')->select(['content', 'id', 'title'])->pluck('title')->toArray());
// Test without SELECT override.
$this->assertSame([
'Foo Post',
'Bar Post',
], DB::table('posts')->pluck('title')->toArray());
// Test specific key.
$this->assertSame([
1 => 'Foo Post',
2 => 'Bar Post',
], DB::table('posts')->pluck('title', 'id')->toArray());
$results = DB::table('posts')->pluck('title', 'created_at');
// Test timestamps (truncates RDBMS differences).
$this->assertSame([
'2017-11-12 13:14:15',
'2018-01-02 03:04:05',
], $results->keys()->map(fn ($v) => substr($v, 0, 19))->toArray());
$this->assertSame([
'Foo Post',
'Bar Post',
], $results->values()->toArray());
// Test duplicate keys (a match will override a previous match).
$this->assertSame([
'Lorem Ipsum.' => 'Bar Post',
], DB::table('posts')->pluck('title', 'content')->toArray());
}
protected function defineEnvironmentWouldThrowsPDOException($app)
{
$this->afterApplicationCreated(function () {
if (in_array($this->driver, ['pgsql', 'sqlsrv'])) {
$this->expectException(PDOException::class);
}
});
}
}
| |
192880
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentMorphLazyEagerLoadingTest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
class EloquentMorphLazyEagerLoadingTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
});
Schema::create('posts', function (Blueprint $table) {
$table->increments('post_id');
$table->unsignedInteger('user_id');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('commentable_type');
$table->integer('commentable_id');
});
$user = User::create();
$post = tap((new Post)->user()->associate($user))->save();
(new Comment)->commentable()->associate($post)->save();
}
public function testLazyEagerLoading()
{
$comment = Comment::first();
$comment->loadMorph('commentable', [
Post::class => ['user'],
]);
$this->assertTrue($comment->relationLoaded('commentable'));
$this->assertTrue($comment->commentable->relationLoaded('user'));
}
}
class Comment extends Model
{
public $timestamps = false;
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
public $timestamps = false;
protected $primaryKey = 'post_id';
public function user()
{
return $this->belongsTo(User::class);
}
}
class User extends Model
{
public $timestamps = false;
}
| |
192882
|
<?php
declare(strict_types=1);
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Events\ConnectionEstablished;
use Illuminate\Events\Dispatcher;
use RuntimeException;
class DatabaseConnectionsTest extends DatabaseTestCase
{
public function testEstablishDatabaseConnection()
{
/** @var \Illuminate\Database\DatabaseManager $manager */
$manager = $this->app->make(DatabaseManager::class);
$connection = $manager->connectUsing('my-phpunit-connection', [
'driver' => 'sqlite',
'database' => ':memory:',
]);
$connection->statement('CREATE TABLE test_1 (id INTEGER PRIMARY KEY)');
$connection->statement('INSERT INTO test_1 (id) VALUES (1)');
$result = $connection->selectOne('SELECT COUNT(*) as total FROM test_1');
self::assertSame(1, $result->total);
}
public function testThrowExceptionIfConnectionAlreadyExists()
{
/** @var \Illuminate\Database\DatabaseManager $manager */
$manager = $this->app->make(DatabaseManager::class);
$manager->connectUsing('my-phpunit-connection', [
'driver' => 'sqlite',
'database' => ':memory:',
]);
$this->expectException(RuntimeException::class);
$manager->connectUsing('my-phpunit-connection', [
'driver' => 'sqlite',
'database' => ':memory:',
]);
}
public function testOverrideExistingConnection()
{
/** @var \Illuminate\Database\DatabaseManager $manager */
$manager = $this->app->make(DatabaseManager::class);
$connection = $manager->connectUsing('my-phpunit-connection', [
'driver' => 'sqlite',
'database' => ':memory:',
]);
$connection->statement('CREATE TABLE test_1 (id INTEGER PRIMARY KEY)');
$resultBeforeOverride = $connection->select("SELECT name FROM sqlite_master WHERE type='table';");
$connection = $manager->connectUsing('my-phpunit-connection', [
'driver' => 'sqlite',
'database' => ':memory:',
], force: true);
// After purging a connection of a :memory: SQLite database
// anything that was created before the override will no
// longer be available. It's a new and fresh database
$resultAfterOverride = $connection->select("SELECT name FROM sqlite_master WHERE type='table';");
self::assertSame('test_1', $resultBeforeOverride[0]->name);
self::assertEmpty($resultAfterOverride);
}
public function testEstablishingAConnectionWillDispatchAnEvent()
{
/** @var \Illuminate\Events\Dispatcher $dispatcher */
$dispatcher = $this->app->make(Dispatcher::class);
$event = null;
$dispatcher->listen(ConnectionEstablished::class, function (ConnectionEstablished $e) use (&$event) {
$event = $e;
});
/** @var \Illuminate\Database\DatabaseManager $manager */
$manager = $this->app->make(DatabaseManager::class);
$manager->connectUsing('my-phpunit-connection', [
'driver' => 'sqlite',
'database' => ':memory:',
]);
self::assertInstanceOf(
ConnectionEstablished::class,
$event,
'Expected the ConnectionEstablished event to be dispatched when establishing a connection.'
);
self::assertSame('my-phpunit-connection', $event->connectionName);
}
}
| |
192883
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Pagination\Cursor;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class EloquentCursorPaginateTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('test_posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->nullable();
$table->unsignedInteger('user_id')->nullable();
$table->timestamps();
});
Schema::create('test_users', function ($table) {
$table->increments('id');
$table->string('name')->nullable();
$table->timestamps();
});
}
public function testCursorPaginationOnTopOfColumns()
{
for ($i = 1; $i <= 50; $i++) {
TestPost::create([
'title' => 'Title '.$i,
]);
}
$this->assertCount(15, TestPost::cursorPaginate(15, ['id', 'title']));
}
public function testPaginationWithUnion()
{
TestPost::create(['title' => 'Hello world', 'user_id' => 1]);
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
TestPost::create(['title' => 'Howdy', 'user_id' => 3]);
TestPost::create(['title' => '4th', 'user_id' => 4]);
$table1 = TestPost::query()->whereIn('user_id', [1, 2]);
$table2 = TestPost::query()->whereIn('user_id', [3, 4]);
$result = $table1->unionAll($table2)
->orderBy('user_id', 'desc')
->cursorPaginate(1);
$this->assertSame(['user_id'], $result->getOptions()['parameters']);
}
public function testPaginationWithDistinct()
{
for ($i = 1; $i <= 3; $i++) {
TestPost::create(['title' => 'Hello world']);
TestPost::create(['title' => 'Goodbye world']);
}
$query = TestPost::query()->distinct();
$this->assertEquals(6, $query->get()->count());
$this->assertEquals(6, $query->count());
$this->assertCount(6, $query->cursorPaginate()->items());
}
public function testPaginationWithWhereClause()
{
for ($i = 1; $i <= 3; $i++) {
TestPost::create(['title' => 'Hello world', 'user_id' => null]);
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
}
$query = TestPost::query()->whereNull('user_id');
$this->assertEquals(3, $query->get()->count());
$this->assertEquals(3, $query->count());
$this->assertCount(3, $query->cursorPaginate()->items());
}
public function testPaginationWithHasClause()
{
for ($i = 1; $i <= 3; $i++) {
TestUser::create();
TestPost::create(['title' => 'Hello world', 'user_id' => null]);
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
TestPost::create(['title' => 'Howdy', 'user_id' => 3]);
}
$query = TestUser::query()->has('posts');
$this->assertEquals(2, $query->get()->count());
$this->assertEquals(2, $query->count());
$this->assertCount(2, $query->cursorPaginate()->items());
}
public function testPaginationWithWhereHasClause()
{
for ($i = 1; $i <= 3; $i++) {
TestUser::create();
TestPost::create(['title' => 'Hello world', 'user_id' => null]);
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
TestPost::create(['title' => 'Howdy', 'user_id' => 3]);
}
$query = TestUser::query()->whereHas('posts', function ($query) {
$query->where('title', 'Howdy');
});
$this->assertEquals(1, $query->get()->count());
$this->assertEquals(1, $query->count());
$this->assertCount(1, $query->cursorPaginate()->items());
}
public function testPaginationWithWhereExistsClause()
{
for ($i = 1; $i <= 3; $i++) {
TestUser::create();
TestPost::create(['title' => 'Hello world', 'user_id' => null]);
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
TestPost::create(['title' => 'Howdy', 'user_id' => 3]);
}
$query = TestUser::query()->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('test_posts')
->whereColumn('test_posts.user_id', 'test_users.id');
});
$this->assertEquals(2, $query->get()->count());
$this->assertEquals(2, $query->count());
$this->assertCount(2, $query->cursorPaginate()->items());
}
public function testPaginationWithMultipleWhereClauses()
{
for ($i = 1; $i <= 4; $i++) {
TestUser::create();
TestPost::create(['title' => 'Hello world', 'user_id' => null]);
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
TestPost::create(['title' => 'Howdy', 'user_id' => 3]);
TestPost::create(['title' => 'Howdy', 'user_id' => 4]);
}
$query = TestUser::query()->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('test_posts')
->whereColumn('test_posts.user_id', 'test_users.id');
})->whereHas('posts', function ($query) {
$query->where('title', 'Howdy');
})->where('id', '<', 5)->orderBy('id');
$clonedQuery = $query->clone();
$anotherQuery = $query->clone();
$this->assertEquals(2, $query->get()->count());
$this->assertEquals(2, $query->count());
$this->assertCount(2, $query->cursorPaginate()->items());
$this->assertCount(1, $clonedQuery->cursorPaginate(1)->items());
$this->assertCount(
1,
$anotherQuery->cursorPaginate(5, ['*'], 'cursor', new Cursor(['id' => 3]))
->items()
);
}
public function testPaginationWithMultipleUnionAndMultipleWhereClauses()
{
TestPost::create(['title' => 'Post A', 'user_id' => 100]);
TestPost::create(['title' => 'Post B', 'user_id' => 101]);
$table1 = TestPost::select(['id', 'title', 'user_id'])->where('user_id', 100);
$table2 = TestPost::select(['id', 'title', 'user_id'])->where('user_id', 101);
$table3 = TestPost::select(['id', 'title', 'user_id'])->where('user_id', 101);
$columns = ['id'];
$cursorName = 'cursor-name';
$cursor = new Cursor(['id' => 1]);
$result = $table1->toBase()
->union($table2->toBase())
->union($table3->toBase())
->orderBy('id', 'asc')
->cursorPaginate(1, $columns, $cursorName, $cursor);
$this->assertSame(['id'], $result->getOptions()['parameters']);
$postB = $table2->where('id', '>', 1)->first();
$this->assertEquals('Post B', $postB->title, 'Expect `Post B` is the result of the second query');
$this->assertCount(1, $result->items(), 'Expect cursor paginated query should have 1 result');
$this->assertEquals('Post B', current($result->items())->title, 'Expect the paginated query would return `Post B`');
}
| |
192891
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentMorphToSelectTest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
class EloquentMorphToSelectTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->string('commentable_type');
$table->integer('commentable_id');
});
$post = Post::create();
(new Comment)->commentable()->associate($post)->save();
}
public function testSelect()
{
$comments = Comment::with('commentable:id')->get();
$this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
}
public function testSelectRaw()
{
$comments = Comment::with(['commentable' => function ($query) {
$query->selectRaw('id');
}])->get();
$this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
}
public function testSelectSub()
{
$comments = Comment::with(['commentable' => function ($query) {
$query->selectSub(function ($query) {
$query->select('id');
}, 'id');
}])->get();
$this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
}
public function testAddSelect()
{
$comments = Comment::with(['commentable' => function ($query) {
$query->addSelect('id');
}])->get();
$this->assertEquals(['id' => 1], $comments[0]->commentable->getAttributes());
}
public function testLazyLoading()
{
$comment = Comment::first();
$post = $comment->commentable()->select('id')->first();
$this->assertEquals(['id' => 1], $post->getAttributes());
}
}
class Comment extends Model
{
public $timestamps = false;
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
//
}
| |
192895
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
| |
192897
|
public function testAttributesCanCacheNull()
{
$model = new TestEloquentModelWithAttributeCast;
$this->assertSame(0, $model->virtualNullCalls);
$first = $model->virtual_null_cached;
$this->assertNull($first);
$this->assertSame(1, $model->virtualNullCalls);
foreach (range(0, 10) as $ignored) {
$this->assertSame($first, $model->virtual_null_cached);
}
$this->assertSame(1, $model->virtualNullCalls);
}
public function testAttributesByDefaultDontCacheBooleans()
{
$model = new TestEloquentModelWithAttributeCast;
$first = $model->virtual_boolean;
$this->assertIsBool($first);
foreach (range(0, 50) as $ignored) {
$current = $model->virtual_boolean;
$this->assertIsBool($current);
if ($first !== $current) {
return;
}
}
$this->fail('"virtual_boolean" seems to be cached.');
}
public function testCastsThatOnlyHaveGetterThatReturnsObjectAreCached()
{
$model = new TestEloquentModelWithAttributeCast;
$previous = $model->virtualObject;
foreach (range(0, 10) as $ignored) {
$this->assertSame($previous, $previous = $model->virtualObject);
}
}
public function testCastsThatOnlyHaveGetterThatReturnsDateTimeAreCached()
{
$model = new TestEloquentModelWithAttributeCast;
$previous = $model->virtualDateTime;
foreach (range(0, 10) as $ignored) {
$this->assertSame($previous, $previous = $model->virtualDateTime);
}
}
public function testCastsThatOnlyHaveGetterThatReturnsObjectAreNotCached()
{
$model = new TestEloquentModelWithAttributeCast;
$previous = $model->virtualObjectWithoutCaching;
foreach (range(0, 10) as $ignored) {
$this->assertNotSame($previous, $previous = $model->virtualObjectWithoutCaching);
}
}
public function testCastsThatOnlyHaveGetterThatReturnsDateTimeAreNotCached()
{
$model = new TestEloquentModelWithAttributeCast;
$previous = $model->virtualDateTimeWithoutCaching;
foreach (range(0, 10) as $ignored) {
$this->assertNotSame($previous, $previous = $model->virtualDateTimeWithoutCaching);
}
}
public function testCastsThatOnlyHaveGetterThatReturnsObjectAreNotCachedFluent()
{
$model = new TestEloquentModelWithAttributeCast;
$previous = $model->virtualObjectWithoutCachingFluent;
foreach (range(0, 10) as $ignored) {
$this->assertNotSame($previous, $previous = $model->virtualObjectWithoutCachingFluent);
}
}
public function testCastsThatOnlyHaveGetterThatReturnsDateTimeAreNotCachedFluent()
{
$model = new TestEloquentModelWithAttributeCast;
$previous = $model->virtualDateTimeWithoutCachingFluent;
foreach (range(0, 10) as $ignored) {
$this->assertNotSame($previous, $previous = $model->virtualDateTimeWithoutCachingFluent);
}
}
}
class TestEloquentModelWithAttributeCast extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var string[]
*/
protected $guarded = [];
public function uppercase(): Attribute
{
return Attribute::make(
function ($value) {
return strtoupper($value);
},
function ($value) {
return strtoupper($value);
}
);
}
public function address(): Attribute
{
return new Attribute(
function ($value, $attributes) {
if (is_null($attributes['address_line_one'])) {
return;
}
return new AttributeCastAddress($attributes['address_line_one'], $attributes['address_line_two']);
},
function ($value) {
if (is_null($value)) {
return [
'address_line_one' => null,
'address_line_two' => null,
];
}
return ['address_line_one' => $value->lineOne, 'address_line_two' => $value->lineTwo];
}
);
}
public function options(): Attribute
{
return new Attribute(
function ($value) {
return json_decode($value, true);
},
function ($value) {
return json_encode($value);
}
);
}
public function birthdayAt(): Attribute
{
return new Attribute(
function ($value) {
return Carbon::parse($value);
},
function ($value) {
return $value->format('Y-m-d');
}
);
}
public function password(): Attribute
{
return new Attribute(null, function ($value) {
return hash('sha256', $value);
});
}
public function virtual(): Attribute
{
return new Attribute(
function () {
return collect();
}
);
}
public function virtualString(): Attribute
{
return new Attribute(
function () {
return Str::random(10);
}
);
}
public function virtualStringCached(): Attribute
{
return Attribute::get(function () {
return Str::random(10);
})->shouldCache();
}
public function virtualBooleanCached(): Attribute
{
return Attribute::get(function () {
return (bool) mt_rand(0, 1);
})->shouldCache();
}
public function virtualBoolean(): Attribute
{
return Attribute::get(function () {
return (bool) mt_rand(0, 1);
});
}
public $virtualNullCalls = 0;
public function virtualNullCached(): Attribute
{
return Attribute::get(function () {
$this->virtualNullCalls++;
return null;
})->shouldCache();
}
public function virtualObject(): Attribute
{
return new Attribute(
function () {
return new AttributeCastAddress(Str::random(10), Str::random(10));
}
);
}
public function virtualDateTime(): Attribute
{
return new Attribute(
function () {
return Date::now()->addSeconds(mt_rand(0, 10000));
}
);
}
public function virtualObjectWithoutCachingFluent(): Attribute
{
return (new Attribute(
function () {
return new AttributeCastAddress(Str::random(10), Str::random(10));
}
))->withoutObjectCaching();
}
public function virtualDateTimeWithoutCachingFluent(): Attribute
{
return (new Attribute(
function () {
return Date::now()->addSeconds(mt_rand(0, 10000));
}
))->withoutObjectCaching();
}
public function virtualObjectWithoutCaching(): Attribute
{
return Attribute::get(function () {
return new AttributeCastAddress(Str::random(10), Str::random(10));
})->withoutObjectCaching();
}
public function virtualDateTimeWithoutCaching(): Attribute
{
return Attribute::get(function () {
return Date::now()->addSeconds(mt_rand(0, 10000));
})->withoutObjectCaching();
}
}
class AttributeCastAddress
{
public $lineOne;
public $lineTwo;
public function __construct($lineOne, $lineTwo)
{
$this->lineOne = $lineOne;
$this->lineTwo = $lineTwo;
}
}
| |
192903
|
class TestEloquentBroadcastUserOnSpecificEventsOnly extends Model
{
use BroadcastsEvents;
protected $table = 'test_eloquent_broadcasting_users';
public function broadcastOn($event)
{
switch ($event) {
case 'created':
return [$this];
}
}
}
class TestEloquentBroadcastUserWithSpecificBroadcastName extends Model
{
use BroadcastsEvents;
protected $table = 'test_eloquent_broadcasting_users';
public function broadcastAs($event)
{
switch ($event) {
case 'created':
return 'foo';
}
}
}
class TestEloquentBroadcastUserWithSpecificBroadcastPayload extends Model
{
use BroadcastsEvents;
protected $table = 'test_eloquent_broadcasting_users';
public function broadcastWith($event)
{
switch ($event) {
case 'created':
return ['foo' => 'bar'];
}
}
}
| |
192917
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class EloquentCustomPivotCastTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
});
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::create('project_users', function (Blueprint $table) {
$table->integer('user_id');
$table->integer('project_id');
$table->text('permissions');
});
}
public function testCastsAreRespectedOnAttach()
{
$user = CustomPivotCastTestUser::forceCreate([
'email' => 'taylor@laravel.com',
]);
$project = CustomPivotCastTestProject::forceCreate([
'name' => 'Test Project',
]);
$project->collaborators()->attach($user, ['permissions' => ['foo' => 'bar']]);
$project = $project->fresh();
$this->assertEquals(['foo' => 'bar'], $project->collaborators[0]->pivot->permissions);
}
public function testCastsAreRespectedOnAttachArray()
{
$user = CustomPivotCastTestUser::forceCreate([
'email' => 'taylor@laravel.com',
]);
$user2 = CustomPivotCastTestUser::forceCreate([
'email' => 'mohamed@laravel.com',
]);
$project = CustomPivotCastTestProject::forceCreate([
'name' => 'Test Project',
]);
$project->collaborators()->attach([
$user->id => ['permissions' => ['foo' => 'bar']],
$user2->id => ['permissions' => ['baz' => 'bar']],
]);
$project = $project->fresh();
$this->assertEquals(['foo' => 'bar'], $project->collaborators[0]->pivot->permissions);
$this->assertEquals(['baz' => 'bar'], $project->collaborators[1]->pivot->permissions);
}
public function testCastsAreRespectedOnSync()
{
$user = CustomPivotCastTestUser::forceCreate([
'email' => 'taylor@laravel.com',
]);
$project = CustomPivotCastTestProject::forceCreate([
'name' => 'Test Project',
]);
$project->collaborators()->sync([$user->id => ['permissions' => ['foo' => 'bar']]]);
$project = $project->fresh();
$this->assertEquals(['foo' => 'bar'], $project->collaborators[0]->pivot->permissions);
}
public function testCastsAreRespectedOnSyncArray()
{
$user = CustomPivotCastTestUser::forceCreate([
'email' => 'taylor@laravel.com',
]);
$user2 = CustomPivotCastTestUser::forceCreate([
'email' => 'mohamed@laravel.com',
]);
$project = CustomPivotCastTestProject::forceCreate([
'name' => 'Test Project',
]);
$project->collaborators()->sync([
$user->id => ['permissions' => ['foo' => 'bar']],
$user2->id => ['permissions' => ['baz' => 'bar']],
]);
$project = $project->fresh();
$this->assertEquals(['foo' => 'bar'], $project->collaborators[0]->pivot->permissions);
$this->assertEquals(['baz' => 'bar'], $project->collaborators[1]->pivot->permissions);
}
public function testCastsAreRespectedOnSyncArrayWhileUpdatingExisting()
{
$user = CustomPivotCastTestUser::forceCreate([
'email' => 'taylor@laravel.com',
]);
$user2 = CustomPivotCastTestUser::forceCreate([
'email' => 'mohamed@laravel.com',
]);
$project = CustomPivotCastTestProject::forceCreate([
'name' => 'Test Project',
]);
$project->collaborators()->attach([
$user->id => ['permissions' => ['foo' => 'bar']],
$user2->id => ['permissions' => ['baz' => 'bar']],
]);
$project->collaborators()->sync([
$user->id => ['permissions' => ['foo1' => 'bar1']],
$user2->id => ['permissions' => ['baz2' => 'bar2']],
]);
$project = $project->fresh();
$this->assertEquals(['foo1' => 'bar1'], $project->collaborators[0]->pivot->permissions);
$this->assertEquals(['baz2' => 'bar2'], $project->collaborators[1]->pivot->permissions);
}
public function testDefaultAttributesAreRespectedAndCastsAreRespected()
{
$project = CustomPivotCastTestProject::forceCreate([
'name' => 'Test Project',
]);
$pivot = $project->collaborators()->newPivot();
$this->assertEquals(['permissions' => ['create', 'update']], $pivot->toArray());
}
}
class CustomPivotCastTestUser extends Model
{
public $table = 'users';
public $timestamps = false;
}
class CustomPivotCastTestProject extends Model
{
public $table = 'projects';
public $timestamps = false;
public function collaborators()
{
return $this->belongsToMany(
CustomPivotCastTestUser::class, 'project_users', 'project_id', 'user_id'
)->using(CustomPivotCastTestCollaborator::class)->withPivot('permissions');
}
}
class CustomPivotCastTestCollaborator extends Pivot
{
public $timestamps = false;
protected $attributes = [
'permissions' => '["create", "update"]',
];
protected $casts = [
'permissions' => 'json',
];
}
| |
192919
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentWhereHasMorphTest;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
class EloquentWhereHasMorphTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->softDeletes();
});
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
});
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->nullableMorphs('commentable');
$table->softDeletes();
});
$models = [];
$models[] = Post::create(['title' => 'foo']);
$models[] = Post::create(['title' => 'bar']);
$models[] = Post::create(['title' => 'baz']);
end($models)->delete();
$models[] = Video::create(['title' => 'foo']);
$models[] = Video::create(['title' => 'bar']);
$models[] = Video::create(['title' => 'baz']);
$models[] = null; // deleted
$models[] = null; // deleted
foreach ($models as $model) {
(new Comment)->commentable()->associate($model)->save();
}
}
public function testWhereHasMorph()
{
$comments = Comment::whereHasMorph('commentable', [Post::class, Video::class], function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1, 4], $comments->pluck('id')->all());
}
public function testWhereHasMorphWithMorphMap()
{
Relation::morphMap(['posts' => Post::class]);
Comment::where('commentable_type', Post::class)->update(['commentable_type' => 'posts']);
try {
$comments = Comment::whereHasMorph('commentable', [Post::class, Video::class], function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1, 4], $comments->pluck('id')->all());
} finally {
Relation::morphMap([], false);
}
}
public function testWhereHasMorphWithWildcard()
{
// Test newModelQuery() without global scopes.
Comment::where('commentable_type', Video::class)->delete();
$comments = Comment::withTrashed()
->whereHasMorph('commentable', '*', function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1, 4], $comments->pluck('id')->all());
}
public function testWhereHasMorphWithWildcardAndMorphMap()
{
Relation::morphMap(['posts' => Post::class]);
Comment::where('commentable_type', Post::class)->update(['commentable_type' => 'posts']);
try {
$comments = Comment::whereHasMorph('commentable', '*', function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1, 4], $comments->pluck('id')->all());
} finally {
Relation::morphMap([], false);
}
}
public function testWhereHasMorphWithWildcardAndOnlyNullMorphTypes()
{
Comment::whereNotNull('commentable_type')->forceDelete();
$comments = Comment::query()
->whereHasMorph('commentable', '*', function (Builder $query) {
$query->where('title', 'foo');
})
->orderBy('id')->get();
$this->assertEmpty($comments->pluck('id')->all());
}
public function testWhereHasMorphWithRelationConstraint()
{
$comments = Comment::whereHasMorph('commentableWithConstraint', Video::class, function (Builder $query) {
$query->where('title', 'like', 'ba%');
})->orderBy('id')->get();
$this->assertEquals([5], $comments->pluck('id')->all());
}
public function testWhereHasMorphWitDifferentConstraints()
{
$comments = Comment::whereHasMorph('commentable', [Post::class, Video::class], function (Builder $query, $type) {
if ($type === Post::class) {
$query->where('title', 'foo');
}
if ($type === Video::class) {
$query->where('title', 'bar');
}
})->orderBy('id')->get();
$this->assertEquals([1, 5], $comments->pluck('id')->all());
}
public function testWhereHasMorphWithOwnerKey()
{
Schema::table('posts', function (Blueprint $table) {
$table->string('slug')->nullable();
});
Schema::table('comments', function (Blueprint $table) {
$table->dropIndex('comments_commentable_type_commentable_id_index');
});
Schema::table('comments', function (Blueprint $table) {
$table->string('commentable_id')->nullable()->change();
});
Post::where('id', 1)->update(['slug' => 'foo']);
Comment::where('id', 1)->update(['commentable_id' => 'foo']);
$comments = Comment::whereHasMorph('commentableWithOwnerKey', Post::class, function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1], $comments->pluck('id')->all());
}
public function testHasMorph()
{
$comments = Comment::hasMorph('commentable', Post::class)->orderBy('id')->get();
$this->assertEquals([1, 2], $comments->pluck('id')->all());
}
public function testOrHasMorph()
{
$comments = Comment::where('id', 1)->orHasMorph('commentable', Video::class)->orderBy('id')->get();
$this->assertEquals([1, 4, 5, 6], $comments->pluck('id')->all());
}
public function testDoesntHaveMorph()
{
$comments = Comment::doesntHaveMorph('commentable', Post::class)->orderBy('id')->get();
$this->assertEquals([3], $comments->pluck('id')->all());
}
public function testOrDoesntHaveMorph()
{
$comments = Comment::where('id', 1)->orDoesntHaveMorph('commentable', Post::class)->orderBy('id')->get();
$this->assertEquals([1, 3], $comments->pluck('id')->all());
}
public function testOrWhereHasMorph()
{
$comments = Comment::where('id', 1)
->orWhereHasMorph('commentable', Video::class, function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1, 4], $comments->pluck('id')->all());
}
public function testOrWhereHasMorphWithWildcardAndOnlyNullMorphTypes()
{
Comment::whereNotNull('commentable_type')->forceDelete();
$comments = Comment::where('id', 7)
->orWhereHasMorph('commentable', '*', function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([7], $comments->pluck('id')->all());
}
public function testWhereDoesntHaveMorph()
{
$comments = Comment::whereDoesntHaveMorph('commentable', Post::class, function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([2, 3], $comments->pluck('id')->all());
}
public function testWhereDoesntHaveMorphWithWildcardAndOnlyNullMorphTypes()
{
Comment::whereNotNull('commentable_type')->forceDelete();
$comments = Comment::whereDoesntHaveMorph('commentable', [], function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([7, 8], $comments->pluck('id')->all());
}
| |
192920
|
public function testOrWhereDoesntHaveMorph()
{
$comments = Comment::where('id', 1)
->orWhereDoesntHaveMorph('commentable', Post::class, function (Builder $query) {
$query->where('title', 'foo');
})->orderBy('id')->get();
$this->assertEquals([1, 2, 3], $comments->pluck('id')->all());
}
public function testModelScopesAreAccessible()
{
$comments = Comment::whereHasMorph('commentable', [Post::class, Video::class], function (Builder $query) {
$query->someSharedModelScope();
})->orderBy('id')->get();
$this->assertEquals([1, 4], $comments->pluck('id')->all());
}
}
class Comment extends Model
{
use SoftDeletes;
public $timestamps = false;
protected $guarded = [];
public function commentable()
{
return $this->morphTo();
}
public function commentableWithConstraint()
{
return $this->morphTo('commentable')->where('title', 'bar');
}
public function commentableWithOwnerKey()
{
return $this->morphTo('commentable', null, null, 'slug');
}
}
class Post extends Model
{
use SoftDeletes;
public $timestamps = false;
protected $guarded = [];
public function scopeSomeSharedModelScope($query)
{
$query->where('title', '=', 'foo');
}
}
class Video extends Model
{
public $timestamps = false;
protected $guarded = [];
public function scopeSomeSharedModelScope($query)
{
$query->where('title', '=', 'foo');
}
}
| |
192927
|
<?php
namespace Illuminate\Tests\Integration\Database;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\MultipleRecordsFoundException;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class EloquentWhereTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email');
$table->string('address');
});
}
public function testWhereAndWhereOrBehavior()
{
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $firstUser */
$firstUser = UserWhereTest::create([
'name' => 'test-name',
'email' => 'test-email',
'address' => 'test-address',
]);
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $secondUser */
$secondUser = UserWhereTest::create([
'name' => 'test-name1',
'email' => 'test-email1',
'address' => 'test-address1',
]);
$this->assertTrue($firstUser->is(UserWhereTest::where('name', '=', $firstUser->name)->first()));
$this->assertTrue($firstUser->is(UserWhereTest::where('name', $firstUser->name)->first()));
$this->assertTrue($firstUser->is(UserWhereTest::where('name', $firstUser->name)->where('email', $firstUser->email)->first()));
$this->assertNull(UserWhereTest::where('name', $firstUser->name)->where('email', $secondUser->email)->first());
$this->assertTrue($secondUser->is(UserWhereTest::where('name', 'wrong-name')->orWhere('email', $secondUser->email)->first()));
$this->assertTrue($firstUser->is(UserWhereTest::where(['name' => 'test-name', 'email' => 'test-email'])->first()));
$this->assertNull(UserWhereTest::where(['name' => 'test-name', 'email' => 'test-email1'])->first());
$this->assertTrue($secondUser->is(
UserWhereTest::where(['name' => 'wrong-name', 'email' => 'test-email1'], null, null, 'or')->first())
);
$this->assertSame(
1,
UserWhereTest::where(['name' => 'test-name', 'email' => 'test-email1'])
->orWhere(['name' => 'test-name1', 'address' => 'wrong-address'])->count()
);
$this->assertTrue(
$secondUser->is(
UserWhereTest::where(['name' => 'test-name', 'email' => 'test-email1'])
->orWhere(['name' => 'test-name1', 'address' => 'wrong-address'])
->first()
)
);
}
public function testWhereNot()
{
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $firstUser */
$firstUser = UserWhereTest::create([
'name' => 'test-name',
'email' => 'test-email',
'address' => 'test-address',
]);
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $secondUser */
$secondUser = UserWhereTest::create([
'name' => 'test-name1',
'email' => 'test-email1',
'address' => 'test-address1',
]);
$this->assertTrue($secondUser->is(UserWhereTest::whereNot(function ($query) use ($firstUser) {
$query->where('name', '=', $firstUser->name);
})->first()));
$this->assertTrue($firstUser->is(UserWhereTest::where('name', $firstUser->name)->whereNot(function ($query) use ($secondUser) {
$query->where('email', $secondUser->email);
})->first()));
$this->assertTrue($secondUser->is(UserWhereTest::where('name', 'wrong-name')->orWhereNot(function ($query) use ($firstUser) {
$query->where('email', $firstUser->email);
})->first()));
}
public function testWhereIn()
{
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $user1 */
$user1 = UserWhereTest::create([
'name' => 'test-name1',
'email' => 'test-email1',
'address' => 'test-address1',
]);
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $user2 */
$user2 = UserWhereTest::create([
'name' => 'test-name2',
'email' => 'test-email2',
'address' => 'test-address2',
]);
/** @var \Illuminate\Tests\Integration\Database\UserWhereTest $user3 */
$user3 = UserWhereTest::create([
'name' => 'test-name2',
'email' => 'test-email3',
'address' => 'test-address3',
]);
$this->assertTrue($user2->is(UserWhereTest::whereIn('id', [2])->first()));
$users = UserWhereTest::query()->whereIn('id', [1, 2, 22])->get();
$this->assertTrue($user1->is($users[0]));
$this->assertTrue($user2->is($users[1]));
$this->assertCount(2, $users);
$users = UserWhereTest::query()->whereIn('email', ['test-email1', 'test-email2'])->get();
$this->assertTrue($user1->is($users[0]));
$this->assertTrue($user2->is($users[1]));
$this->assertCount(2, $users);
$users = UserWhereTest::query()
->whereIn('id', [1])
->orWhereIn('email', ['test-email1', 'test-email2'])
->get();
$this->assertTrue($user1->is($users[0]));
$this->assertTrue($user2->is($users[1]));
$this->assertCount(2, $users);
}
public function testWhereInCanAcceptQueryable()
{
$user1 = UserWhereTest::create([
'name' => 'test-name1',
'email' => 'test-email1',
'address' => 'test-address1',
]);
$user2 = UserWhereTest::create([
'name' => 'test-name2',
'email' => 'test-email2',
'address' => 'test-address2',
]);
$user3 = UserWhereTest::create([
'name' => 'test-name2',
'email' => 'test-email3',
'address' => 'test-address3',
]);
$query = UserWhereTest::query()->select('name')->where('id', '>', 1);
$users = UserWhereTest::query()->whereIn('name', $query)->get();
$this->assertTrue($user2->is($users[0]));
$this->assertTrue($user3->is($users[1]));
$this->assertCount(2, $users);
$users = UserWhereTest::query()->whereIn('name', function (Builder $query) {
$query->select('name')->where('id', '>', 1);
})->get();
$this->assertTrue($user2->is($users[0]));
$this->assertTrue($user3->is($users[1]));
$this->assertCount(2, $users);
$query = DB::table('users')->select('name')->where('id', '=', 1);
$users = UserWhereTest::query()->whereNotIn('name', $query)->get();
$this->assertTrue($user2->is($users[0]));
$this->assertTrue($user3->is($users[1]));
$this->assertCount(2, $users);
}
| |
192933
|
<?php
namespace Illuminate\Tests\Integration\Database\EloquentEagerLoadingLimitTest;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;
class EloquentEagerLoadingLimitTest extends DatabaseTestCase
{
protected function afterRefreshingDatabase()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
});
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->timestamps();
});
Schema::create('comments', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
Schema::create('role_user', function (Blueprint $table) {
$table->unsignedBigInteger('role_id');
$table->unsignedBigInteger('user_id');
});
User::create();
User::create();
Post::create(['user_id' => 1, 'created_at' => new Carbon('2024-01-01 00:00:01')]);
Post::create(['user_id' => 1, 'created_at' => new Carbon('2024-01-01 00:00:02')]);
Post::create(['user_id' => 1, 'created_at' => new Carbon('2024-01-01 00:00:03')]);
Post::create(['user_id' => 2, 'created_at' => new Carbon('2024-01-01 00:00:04')]);
Post::create(['user_id' => 2, 'created_at' => new Carbon('2024-01-01 00:00:05')]);
Post::create(['user_id' => 2, 'created_at' => new Carbon('2024-01-01 00:00:06')]);
Comment::create(['post_id' => 1, 'created_at' => new Carbon('2024-01-01 00:00:01')]);
Comment::create(['post_id' => 2, 'created_at' => new Carbon('2024-01-01 00:00:02')]);
Comment::create(['post_id' => 3, 'created_at' => new Carbon('2024-01-01 00:00:03')]);
Comment::create(['post_id' => 4, 'created_at' => new Carbon('2024-01-01 00:00:04')]);
Comment::create(['post_id' => 5, 'created_at' => new Carbon('2024-01-01 00:00:05')]);
Comment::create(['post_id' => 6, 'created_at' => new Carbon('2024-01-01 00:00:06')]);
Role::create(['created_at' => new Carbon('2024-01-01 00:00:01')]);
Role::create(['created_at' => new Carbon('2024-01-01 00:00:02')]);
Role::create(['created_at' => new Carbon('2024-01-01 00:00:03')]);
Role::create(['created_at' => new Carbon('2024-01-01 00:00:04')]);
Role::create(['created_at' => new Carbon('2024-01-01 00:00:05')]);
Role::create(['created_at' => new Carbon('2024-01-01 00:00:06')]);
DB::table('role_user')->insert([
['role_id' => 1, 'user_id' => 1],
['role_id' => 2, 'user_id' => 1],
['role_id' => 3, 'user_id' => 1],
['role_id' => 4, 'user_id' => 2],
['role_id' => 5, 'user_id' => 2],
['role_id' => 6, 'user_id' => 2],
]);
}
public function testBelongsToMany(): void
{
$users = User::with(['roles' => fn ($query) => $query->latest()->limit(2)])
->orderBy('id')
->get();
$this->assertEquals([3, 2], $users[0]->roles->pluck('id')->all());
$this->assertEquals([6, 5], $users[1]->roles->pluck('id')->all());
$this->assertArrayNotHasKey('laravel_row', $users[0]->roles[0]);
$this->assertArrayNotHasKey('@laravel_group := `user_id`', $users[0]->roles[0]);
}
public function testBelongsToManyWithOffset(): void
{
$users = User::with(['roles' => fn ($query) => $query->latest()->limit(2)->offset(1)])
->orderBy('id')
->get();
$this->assertEquals([2, 1], $users[0]->roles->pluck('id')->all());
$this->assertEquals([5, 4], $users[1]->roles->pluck('id')->all());
}
public function testHasMany(): void
{
$users = User::with(['posts' => fn ($query) => $query->latest()->limit(2)])
->orderBy('id')
->get();
$this->assertEquals([3, 2], $users[0]->posts->pluck('id')->all());
$this->assertEquals([6, 5], $users[1]->posts->pluck('id')->all());
$this->assertArrayNotHasKey('laravel_row', $users[0]->posts[0]);
$this->assertArrayNotHasKey('@laravel_group := `user_id`', $users[0]->posts[0]);
}
public function testHasManyWithOffset(): void
{
$users = User::with(['posts' => fn ($query) => $query->latest()->limit(2)->offset(1)])
->orderBy('id')
->get();
$this->assertEquals([2, 1], $users[0]->posts->pluck('id')->all());
$this->assertEquals([5, 4], $users[1]->posts->pluck('id')->all());
}
public function testHasManyThrough(): void
{
$users = User::with(['comments' => fn ($query) => $query->latest('comments.created_at')->limit(2)])
->orderBy('id')
->get();
$this->assertEquals([3, 2], $users[0]->comments->pluck('id')->all());
$this->assertEquals([6, 5], $users[1]->comments->pluck('id')->all());
$this->assertArrayNotHasKey('laravel_row', $users[0]->comments[0]);
$this->assertArrayNotHasKey('@laravel_group := `user_id`', $users[0]->comments[0]);
}
public function testHasManyThroughWithOffset(): void
{
$users = User::with(['comments' => fn ($query) => $query->latest('comments.created_at')->limit(2)->offset(1)])
->orderBy('id')
->get();
$this->assertEquals([2, 1], $users[0]->comments->pluck('id')->all());
$this->assertEquals([5, 4], $users[1]->comments->pluck('id')->all());
}
}
class Comment extends Model
{
public $timestamps = false;
protected $guarded = [];
}
class Post extends Model
{
protected $guarded = [];
}
class Role extends Model
{
protected $guarded = [];
}
class User extends Model
{
public $timestamps = false;
protected $guarded = [];
public function comments(): HasManyThrough
{
return $this->hasManyThrough(Comment::class, Post::class);
}
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class);
}
}
| |
192938
|
public function testModifyingColumnToAutoIncrementColumn()
{
if (in_array($this->driver, ['pgsql', 'sqlsrv'])) {
$this->markTestSkipped('Changing a column to auto increment is not supported on PostgreSQL and SQL Server.');
}
Schema::create('test', function (Blueprint $table) {
$table->unsignedBigInteger('id');
});
$this->assertFalse(collect(Schema::getColumns('test'))->firstWhere('name', 'id')['auto_increment']);
$this->assertFalse(Schema::hasIndex('test', ['id'], 'primary'));
Schema::table('test', function (Blueprint $table) {
$table->bigIncrements('id')->primary()->change();
});
$this->assertTrue(collect(Schema::getColumns('test'))->firstWhere('name', 'id')['auto_increment']);
$this->assertTrue(Schema::hasIndex('test', ['id'], 'primary'));
}
public function testAddingAutoIncrementColumn()
{
if ($this->driver === 'sqlite') {
$this->markTestSkipped('Adding a primary column is not supported on SQLite.');
}
Schema::create('test', function (Blueprint $table) {
$table->string('name');
});
Schema::table('test', function (Blueprint $table) {
$table->bigIncrements('id');
});
$this->assertTrue(collect(Schema::getColumns('test'))->firstWhere('name', 'id')['auto_increment']);
$this->assertTrue(Schema::hasIndex('test', ['id'], 'primary'));
}
public function testGetTables()
{
Schema::create('foo', function (Blueprint $table) {
$table->comment('This is a comment');
$table->increments('id');
});
Schema::create('bar', function (Blueprint $table) {
$table->string('name');
});
Schema::create('baz', function (Blueprint $table) {
$table->integer('votes');
});
$tables = Schema::getTables();
$this->assertEmpty(array_diff(['foo', 'bar', 'baz'], array_column($tables, 'name')));
if (in_array($this->driver, ['mysql', 'mariadb', 'pgsql'])) {
$this->assertNotEmpty(array_filter($tables, function ($table) {
return $table['name'] === 'foo' && $table['comment'] === 'This is a comment';
}));
}
}
public function testHasView()
{
DB::statement('create view foo (id) as select 1');
$this->assertTrue(Schema::hasView('foo'));
}
public function testGetViews()
{
DB::statement('create view foo (id) as select 1');
DB::statement('create view bar (name) as select 1');
DB::statement('create view baz (votes) as select 1');
$views = Schema::getViews();
$this->assertEmpty(array_diff(['foo', 'bar', 'baz'], array_column($views, 'name')));
}
#[RequiresDatabase('pgsql')]
public function testGetAndDropTypes()
{
DB::statement('create type pseudo_foo');
DB::statement('create type comp_foo as (f1 int, f2 text)');
DB::statement("create type enum_foo as enum ('new', 'open', 'closed')");
DB::statement('create type range_foo as range (subtype = float8)');
DB::statement('create domain domain_foo as text');
DB::statement('create type base_foo');
DB::statement("create function foo_in(cstring) returns base_foo language internal immutable strict parallel safe as 'int2in'");
DB::statement("create function foo_out(base_foo) returns cstring language internal immutable strict parallel safe as 'int2out'");
DB::statement('create type base_foo (input = foo_in, output = foo_out)');
$types = Schema::getTypes();
if (version_compare($this->getConnection()->getServerVersion(), '14.0', '<')) {
$this->assertCount(10, $types);
} else {
$this->assertCount(13, $types);
}
$this->assertTrue(collect($types)->contains(fn ($type) => $type['name'] === 'pseudo_foo' && $type['type'] === 'pseudo' && ! $type['implicit']));
$this->assertTrue(collect($types)->contains(fn ($type) => $type['name'] === 'comp_foo' && $type['type'] === 'composite' && ! $type['implicit']));
$this->assertTrue(collect($types)->contains(fn ($type) => $type['name'] === 'enum_foo' && $type['type'] === 'enum' && ! $type['implicit']));
$this->assertTrue(collect($types)->contains(fn ($type) => $type['name'] === 'range_foo' && $type['type'] === 'range' && ! $type['implicit']));
$this->assertTrue(collect($types)->contains(fn ($type) => $type['name'] === 'domain_foo' && $type['type'] === 'domain' && ! $type['implicit']));
$this->assertTrue(collect($types)->contains(fn ($type) => $type['name'] === 'base_foo' && $type['type'] === 'base' && ! $type['implicit']));
Schema::dropAllTypes();
$types = Schema::getTypes();
$this->assertEmpty($types);
}
public function testGetColumns()
{
Schema::create('foo', function (Blueprint $table) {
$table->id();
$table->string('bar')->nullable();
$table->string('baz')->default('test');
});
$columns = Schema::getColumns('foo');
$this->assertCount(3, $columns);
$this->assertTrue(collect($columns)->contains(
fn ($column) => $column['name'] === 'id' && $column['auto_increment'] && ! $column['nullable']
));
$this->assertTrue(collect($columns)->contains(
fn ($column) => $column['name'] === 'bar' && $column['nullable']
));
$this->assertTrue(collect($columns)->contains(
fn ($column) => $column['name'] === 'baz' && ! $column['nullable'] && str_contains($column['default'], 'test')
));
}
public function testGetColumnsOnView()
{
DB::statement('create view foo (bar) as select 1');
$columns = Schema::getColumns('foo');
$this->assertCount(1, $columns);
$this->assertTrue($columns[0]['name'] === 'bar');
}
public function testGetIndexes()
{
Schema::create('foo', function (Blueprint $table) {
$table->string('bar')->index('my_index');
});
$indexes = Schema::getIndexes('foo');
$this->assertCount(1, $indexes);
$this->assertTrue(
$indexes[0]['name'] === 'my_index'
&& $indexes[0]['columns'] === ['bar']
&& ! $indexes[0]['unique']
&& ! $indexes[0]['primary']
);
$this->assertTrue(Schema::hasIndex('foo', 'my_index'));
$this->assertTrue(Schema::hasIndex('foo', ['bar']));
$this->assertFalse(Schema::hasIndex('foo', 'my_index', 'primary'));
$this->assertFalse(Schema::hasIndex('foo', ['bar'], 'unique'));
}
public function testGetUniqueIndexes()
{
Schema::create('foo', function (Blueprint $table) {
$table->id();
$table->string('bar');
$table->integer('baz');
$table->unique(['baz', 'bar']);
});
$indexes = Schema::getIndexes('foo');
$this->assertCount(2, $indexes);
$this->assertTrue(collect($indexes)->contains(
fn ($index) => $index['columns'] === ['id'] && $index['primary']
));
$this->assertTrue(collect($indexes)->contains(
fn ($index) => $index['name'] === 'foo_baz_bar_unique' && $index['columns'] === ['baz', 'bar'] && $index['unique']
));
$this->assertTrue(Schema::hasIndex('foo', 'foo_baz_bar_unique'));
$this->assertTrue(Schema::hasIndex('foo', 'foo_baz_bar_unique', 'unique'));
$this->assertTrue(Schema::hasIndex('foo', ['baz', 'bar']));
$this->assertTrue(Schema::hasIndex('foo', ['baz', 'bar'], 'unique'));
$this->assertFalse(Schema::hasIndex('foo', ['baz', 'bar'], 'primary'));
}
| |
192940
|
#[RequiresDatabase('pgsql', '>=12.0')]
public function testGettingGeneratedColumns()
{
Schema::create('test', function (Blueprint $table) {
$table->integer('price');
if ($this->driver === 'sqlsrv') {
$table->computed('virtual_price', 'price - 5');
$table->computed('stored_price', 'price - 10')->persisted();
} else {
if ($this->driver !== 'pgsql') {
$table->integer('virtual_price')->virtualAs('price - 5');
}
$table->integer('stored_price')->storedAs('price - 10');
}
});
$columns = Schema::getColumns('test');
$this->assertTrue(collect($columns)->contains(
fn ($column) => $column['name'] === 'price' && is_null($column['generation'])
));
if ($this->driver !== 'pgsql') {
$this->assertTrue(collect($columns)->contains(
fn ($column) => $column['name'] === 'virtual_price'
&& $column['generation']['type'] === 'virtual'
&& match ($this->driver) {
'mysql' => $column['generation']['expression'] === '(`price` - 5)',
'mariadb' => $column['generation']['expression'] === '`price` - 5',
'sqlsrv' => $column['generation']['expression'] === '([price]-(5))',
default => $column['generation']['expression'] === 'price - 5',
}
));
}
$this->assertTrue(collect($columns)->contains(
fn ($column) => $column['name'] === 'stored_price'
&& $column['generation']['type'] === 'stored'
&& match ($this->driver) {
'mysql' => $column['generation']['expression'] === '(`price` - 10)',
'mariadb' => $column['generation']['expression'] === '`price` - 10',
'sqlsrv' => $column['generation']['expression'] === '([price]-(10))',
'pgsql' => $column['generation']['expression'] === '(price - 10)',
default => $column['generation']['expression'] === 'price - 10',
}
));
}
#[RequiresDatabase('sqlite')]
public function testAddForeignKeysOnSqlite()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
});
Schema::create('posts', function (Blueprint $table) {
$table->string('title')->unique();
});
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->nullable()->index()->constrained();
$table->string('user_name');
$table->foreign('user_name')->references('name')->on('users');
});
$foreignKeys = Schema::getForeignKeys('posts');
$this->assertCount(2, $foreignKeys);
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_id'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['id']));
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_name'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['name']));
$this->assertTrue(Schema::hasColumns('posts', ['title', 'user_id', 'user_name']));
$this->assertTrue(Schema::hasIndex('posts', ['user_id']));
$this->assertTrue(Schema::hasIndex('posts', ['title'], 'unique'));
}
#[RequiresDatabase('sqlite')]
public function testDropForeignKeysOnSqlite()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
});
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->nullable()->index()->constrained();
$table->string('user_name')->unique();
$table->foreign('user_name')->references('name')->on('users');
});
$foreignKeys = Schema::getForeignKeys('posts');
$this->assertCount(2, $foreignKeys);
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_id'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['id']));
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_name'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['name']));
$this->assertTrue(Schema::hasIndex('posts', ['id'], 'primary'));
Schema::table('posts', function (Blueprint $table) {
$table->string('title')->unique();
$table->dropIndex(['user_id']);
$table->dropForeign(['user_id']);
$table->dropColumn('user_id');
});
$foreignKeys = Schema::getForeignKeys('posts');
$this->assertCount(1, $foreignKeys);
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_name'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['name']));
$this->assertTrue(Schema::hasColumns('posts', ['user_name', 'title']));
$this->assertTrue(Schema::hasIndex('posts', ['id'], 'primary'));
$this->assertTrue(Schema::hasIndex('posts', ['title'], 'unique'));
$this->assertTrue(Schema::hasIndex('posts', ['user_name'], 'unique'));
$this->assertFalse(Schema::hasColumn('posts', 'user_id'));
$this->assertFalse(Schema::hasIndex('posts', ['user_id']));
}
#[RequiresDatabase('sqlite')]
public function testAddAndDropPrimaryOnSqlite()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
});
Schema::create('posts', function (Blueprint $table) {
$table->foreignId('user_id')->nullable()->index()->constrained();
$table->string('user_name')->unique();
$table->foreign('user_name')->references('name')->on('users');
});
Schema::table('posts', function (Blueprint $table) {
$table->string('title')->primary();
$table->dropIndex(['user_id']);
$table->dropForeign(['user_id']);
$table->dropColumn('user_id');
});
$foreignKeys = Schema::getForeignKeys('posts');
$this->assertCount(1, $foreignKeys);
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_name'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['name']));
$this->assertTrue(Schema::hasColumns('posts', ['user_name', 'title']));
$this->assertTrue(Schema::hasIndex('posts', ['title'], 'primary'));
$this->assertTrue(Schema::hasIndex('posts', ['user_name'], 'unique'));
$this->assertFalse(Schema::hasColumn('posts', 'user_id'));
$this->assertFalse(Schema::hasIndex('posts', ['user_id']));
Schema::table('posts', function (Blueprint $table) {
$table->dropPrimary();
$table->integer('votes');
});
$foreignKeys = Schema::getForeignKeys('posts');
$this->assertCount(1, $foreignKeys);
$this->assertTrue(collect($foreignKeys)->contains(fn ($foreign) => $foreign['columns'] === ['user_name'] && $foreign['foreign_table'] === 'users' && $foreign['foreign_columns'] === ['name']));
$this->assertTrue(Schema::hasColumns('posts', ['user_name', 'title', 'votes']));
$this->assertFalse(Schema::hasIndex('posts', ['title'], 'primary'));
$this->assertTrue(Schema::hasIndex('posts', ['user_name'], 'unique'));
}
#[RequiresDatabase('sqlite')]
public function testSetJournalModeOnSqlite()
{
file_put_contents(DB::connection('sqlite')->getConfig('database'), '');
$this->assertSame('delete', DB::connection('sqlite')->select('PRAGMA journal_mode')[0]->journal_mode);
Schema::connection('sqlite')->setJournalMode('WAL');
$this->assertSame('wal', DB::connection('sqlite')->select('PRAGMA journal_mode')[0]->journal_mode);
}
| |
192948
|
<?php
namespace Illuminate\Tests\Integration\Database\MariaDb;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
class EloquentCastTest extends MariaDbTestCase
{
protected $driver = 'mariadb';
protected function afterRefreshingDatabase()
{
Schema::create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->integer('created_at');
$table->integer('updated_at');
});
Schema::create('users_nullable_timestamps', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
}
protected function destroyDatabaseMigrations()
{
Schema::drop('users');
}
public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasNotPassed()
{
Carbon::setTestNow(now());
$createdAt = now()->timestamp;
$castUser = UserWithIntTimestampsViaCasts::create([
'email' => fake()->unique()->email,
]);
$attributeUser = UserWithIntTimestampsViaAttribute::create([
'email' => fake()->unique()->email,
]);
$mutatorUser = UserWithIntTimestampsViaMutator::create([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($createdAt, $castUser->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($createdAt, $attributeUser->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);
$castUser->update([
'email' => fake()->unique()->email,
]);
$attributeUser->update([
'email' => fake()->unique()->email,
]);
$mutatorUser->update([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($createdAt, $castUser->updated_at->timestamp);
$this->assertSame($createdAt, $castUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($createdAt, $attributeUser->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->fresh()->updated_at->timestamp);
}
public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasPassed()
{
Carbon::setTestNow(now());
$createdAt = now()->timestamp;
$castUser = UserWithIntTimestampsViaCasts::create([
'email' => fake()->unique()->email,
]);
$attributeUser = UserWithIntTimestampsViaAttribute::create([
'email' => fake()->unique()->email,
]);
$mutatorUser = UserWithIntTimestampsViaMutator::create([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($createdAt, $castUser->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($createdAt, $attributeUser->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);
Carbon::setTestNow(now()->addSecond());
$updatedAt = now()->timestamp;
$castUser->update([
'email' => fake()->unique()->email,
]);
$attributeUser->update([
'email' => fake()->unique()->email,
]);
$mutatorUser->update([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($updatedAt, $castUser->updated_at->timestamp);
$this->assertSame($updatedAt, $castUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($updatedAt, $attributeUser->updated_at->timestamp);
$this->assertSame($updatedAt, $attributeUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
}
public function testItCastTimestampsUpdatedByAMutator()
{
Carbon::setTestNow(now());
$mutatorUser = UserWithUpdatedAtViaMutator::create([
'email' => fake()->unique()->email,
]);
$this->assertNull($mutatorUser->updated_at);
Carbon::setTestNow(now()->addSecond());
$updatedAt = now()->timestamp;
$mutatorUser->update([
'email' => fake()->unique()->email,
]);
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
}
}
class UserWithIntTimestampsViaCasts extends Model
{
protected $table = 'users';
protected $fillable = ['email'];
protected $casts = [
'created_at' => UnixTimeStampToCarbon::class,
'updated_at' => UnixTimeStampToCarbon::class,
];
}
class UnixTimeStampToCarbon implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return Carbon::parse($value);
}
public function set($model, string $key, $value, array $attributes)
{
return Carbon::parse($value)->timestamp;
}
}
class UserWithIntTimestampsViaAttribute extends Model
{
protected $table = 'users';
protected $fillable = ['email'];
protected function updatedAt(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value),
set: fn ($value) => Carbon::parse($value)->timestamp,
);
}
protected function createdAt(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value),
set: fn ($value) => Carbon::parse($value)->timestamp,
);
}
}
class UserWithIntTimestampsViaMutator extends Model
{
protected $table = 'users';
protected $fillable = ['email'];
protected function getUpdatedAtAttribute($value)
{
return Carbon::parse($value);
}
protected function setUpdatedAtAttribute($value)
{
$this->attributes['updated_at'] = Carbon::parse($value)->timestamp;
}
protected function getCreatedAtAttribute($value)
{
return Carbon::parse($value);
}
protected function setCreatedAtAttribute($value)
{
$this->attributes['created_at'] = Carbon::parse($value)->timestamp;
}
}
class UserWithUpdatedAtViaMutator extends Model
{
protected $table = 'users_nullable_timestamps';
protected $fillable = ['email', 'updated_at'];
public function setUpdatedAtAttribute($value)
{
if (! $this->id) {
return;
}
$this->updated_at = $value;
}
}
| |
192958
|
public function testAddUniqueIndexWithoutNameWorks()
{
DB::connection()->getSchemaBuilder()->create('users', function ($table) {
$table->string('name')->nullable();
});
$blueprintMySql = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique()->change();
});
$queries = $blueprintMySql->toSql(DB::connection(), new MySqlGrammar);
$expected = [
'alter table `users` modify `name` varchar(255) null',
'alter table `users` add unique `users_name_unique`(`name`)',
];
$this->assertEquals($expected, $queries);
$blueprintPostgres = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique()->change();
});
$queries = $blueprintPostgres->toSql(DB::connection(), new PostgresGrammar);
$expected = [
'alter table "users" alter column "name" type varchar(255), alter column "name" drop not null, alter column "name" drop default, alter column "name" drop identity if exists',
'alter table "users" add constraint "users_name_unique" unique ("name")',
'comment on column "users"."name" is NULL',
];
$this->assertEquals($expected, $queries);
$blueprintSQLite = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique()->change();
});
$queries = $blueprintSQLite->toSql(DB::connection(), new SQLiteGrammar);
$expected = [
'create table "__temp__users" ("name" varchar)',
'insert into "__temp__users" ("name") select "name" from "users"',
'drop table "users"',
'alter table "__temp__users" rename to "users"',
'create unique index "users_name_unique" on "users" ("name")',
];
$this->assertEquals($expected, $queries);
$blueprintSqlServer = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique()->change();
});
$queries = $blueprintSqlServer->toSql(DB::connection(), new SqlServerGrammar);
$expected = [
"DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE \"users\" DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM sys.columns WHERE [object_id] = OBJECT_ID(N'\"users\"') AND [name] in ('name') AND [default_object_id] <> 0;EXEC(@sql)",
'alter table "users" alter column "name" nvarchar(255) null',
'create unique index "users_name_unique" on "users" ("name")',
];
$this->assertEquals($expected, $queries);
}
public function testAddUniqueIndexWithNameWorks()
{
DB::connection()->getSchemaBuilder()->create('users', function ($table) {
$table->string('name')->nullable();
});
$blueprintMySql = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique('index1')->change();
});
$queries = $blueprintMySql->toSql(DB::connection(), new MySqlGrammar);
$expected = [
'alter table `users` modify `name` varchar(255) null',
'alter table `users` add unique `index1`(`name`)',
];
$this->assertEquals($expected, $queries);
$blueprintPostgres = new Blueprint('users', function ($table) {
$table->unsignedInteger('name')->nullable()->unique('index1')->change();
});
$queries = $blueprintPostgres->toSql(DB::connection(), new PostgresGrammar);
$expected = [
'alter table "users" alter column "name" type integer, alter column "name" drop not null, alter column "name" drop default, alter column "name" drop identity if exists',
'alter table "users" add constraint "index1" unique ("name")',
'comment on column "users"."name" is NULL',
];
$this->assertEquals($expected, $queries);
$blueprintSQLite = new Blueprint('users', function ($table) {
$table->unsignedInteger('name')->nullable()->unique('index1')->change();
});
$queries = $blueprintSQLite->toSql(DB::connection(), new SQLiteGrammar);
$expected = [
'create table "__temp__users" ("name" integer)',
'insert into "__temp__users" ("name") select "name" from "users"',
'drop table "users"',
'alter table "__temp__users" rename to "users"',
'create unique index "index1" on "users" ("name")',
];
$this->assertEquals($expected, $queries);
$blueprintSqlServer = new Blueprint('users', function ($table) {
$table->unsignedInteger('name')->nullable()->unique('index1')->change();
});
$queries = $blueprintSqlServer->toSql(DB::connection(), new SqlServerGrammar);
$expected = [
"DECLARE @sql NVARCHAR(MAX) = '';SELECT @sql += 'ALTER TABLE \"users\" DROP CONSTRAINT ' + OBJECT_NAME([default_object_id]) + ';' FROM sys.columns WHERE [object_id] = OBJECT_ID(N'\"users\"') AND [name] in ('name') AND [default_object_id] <> 0;EXEC(@sql)",
'alter table "users" alter column "name" int null',
'create unique index "index1" on "users" ("name")',
];
$this->assertEquals($expected, $queries);
}
public function testAddColumnNamedCreateWorks()
{
Schema::create('users', function (Blueprint $table) {
$table->string('name');
});
Schema::table('users', function (Blueprint $table) {
$table->string('create')->nullable();
});
$this->assertTrue(Schema::hasColumn('users', 'create'));
}
public function testDropIndexOnColumnChangeWorks()
{
$connection = DB::connection();
$connection->getSchemaBuilder()->create('users', function ($table) {
$table->string('name')->nullable();
});
$blueprint = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique(false)->change();
});
$this->assertContains(
'alter table `users` drop index `users_name_unique`',
$blueprint->toSql($connection, new MySqlGrammar)
);
$blueprint = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique(false)->change();
});
$this->assertContains(
'alter table "users" drop constraint "users_name_unique"',
$blueprint->toSql($connection, new PostgresGrammar)
);
$blueprint = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique(false)->change();
});
$this->assertContains(
'drop index "users_name_unique"',
$blueprint->toSql($connection, new SQLiteGrammar)
);
$blueprint = new Blueprint('users', function ($table) {
$table->string('name')->nullable()->unique(false)->change();
});
$this->assertContains(
'drop index "users_name_unique" on "users"',
$blueprint->toSql($connection, new SqlServerGrammar)
);
}
public function testItDoesNotSetPrecisionHigherThanSupportedWhenRenamingTimestamps()
{
Schema::create('users', function (Blueprint $table) {
$table->timestamp('created_at');
});
try {
// this would only fail in mysql, postgres and sql server
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('created_at', 'new_created_at');
});
$this->addToAssertionCount(1); // it did not throw
} catch (\Exception $e) {
// Expecting something similar to:
// Illuminate\Database\QueryException
// SQLSTATE[42000]: Syntax error or access violation: 1426 Too big precision 10 specified for 'my_timestamp'. Maximum is 6....
$this->fail('test_it_does_not_set_precision_higher_than_supported_when_renaming_timestamps has failed. Error: '.$e->getMessage());
}
}
public function testItEnsuresDroppingForeignKeyIsAvailable()
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('This database driver does not support dropping foreign keys by name.');
Schema::table('users', function (Blueprint $table) {
$table->dropForeign('something');
});
}
}
| |
192971
|
<?php
namespace Illuminate\Tests\Integration\Database\MySql;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
class EloquentCastTest extends MySqlTestCase
{
protected $driver = 'mysql';
protected function afterRefreshingDatabase()
{
Schema::create('users', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->integer('created_at');
$table->integer('updated_at');
});
Schema::create('users_nullable_timestamps', function ($table) {
$table->increments('id');
$table->string('email')->unique();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
});
}
protected function destroyDatabaseMigrations()
{
Schema::drop('users');
}
public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasNotPassed()
{
Carbon::setTestNow(now());
$createdAt = now()->timestamp;
$castUser = UserWithIntTimestampsViaCasts::create([
'email' => fake()->unique()->email,
]);
$attributeUser = UserWithIntTimestampsViaAttribute::create([
'email' => fake()->unique()->email,
]);
$mutatorUser = UserWithIntTimestampsViaMutator::create([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($createdAt, $castUser->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($createdAt, $attributeUser->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);
$castUser->update([
'email' => fake()->unique()->email,
]);
$attributeUser->update([
'email' => fake()->unique()->email,
]);
$mutatorUser->update([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($createdAt, $castUser->updated_at->timestamp);
$this->assertSame($createdAt, $castUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($createdAt, $attributeUser->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->fresh()->updated_at->timestamp);
}
public function testItCastTimestampsCreatedByTheBuilderWhenTimeHasPassed()
{
Carbon::setTestNow(now());
$createdAt = now()->timestamp;
$castUser = UserWithIntTimestampsViaCasts::create([
'email' => fake()->unique()->email,
]);
$attributeUser = UserWithIntTimestampsViaAttribute::create([
'email' => fake()->unique()->email,
]);
$mutatorUser = UserWithIntTimestampsViaMutator::create([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($createdAt, $castUser->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($createdAt, $attributeUser->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->updated_at->timestamp);
Carbon::setTestNow(now()->addSecond());
$updatedAt = now()->timestamp;
$castUser->update([
'email' => fake()->unique()->email,
]);
$attributeUser->update([
'email' => fake()->unique()->email,
]);
$mutatorUser->update([
'email' => fake()->unique()->email,
]);
$this->assertSame($createdAt, $castUser->created_at->timestamp);
$this->assertSame($updatedAt, $castUser->updated_at->timestamp);
$this->assertSame($updatedAt, $castUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $attributeUser->created_at->timestamp);
$this->assertSame($updatedAt, $attributeUser->updated_at->timestamp);
$this->assertSame($updatedAt, $attributeUser->fresh()->updated_at->timestamp);
$this->assertSame($createdAt, $mutatorUser->created_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
}
public function testItCastTimestampsUpdatedByAMutator()
{
Carbon::setTestNow(now());
$mutatorUser = UserWithUpdatedAtViaMutator::create([
'email' => fake()->unique()->email,
]);
$this->assertNull($mutatorUser->updated_at);
Carbon::setTestNow(now()->addSecond());
$updatedAt = now()->timestamp;
$mutatorUser->update([
'email' => fake()->unique()->email,
]);
$this->assertSame($updatedAt, $mutatorUser->updated_at->timestamp);
$this->assertSame($updatedAt, $mutatorUser->fresh()->updated_at->timestamp);
}
}
class UserWithIntTimestampsViaCasts extends Model
{
protected $table = 'users';
protected $fillable = ['email'];
protected $casts = [
'created_at' => UnixTimeStampToCarbon::class,
'updated_at' => UnixTimeStampToCarbon::class,
];
}
class UnixTimeStampToCarbon implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return Carbon::parse($value);
}
public function set($model, string $key, $value, array $attributes)
{
return Carbon::parse($value)->timestamp;
}
}
class UserWithIntTimestampsViaAttribute extends Model
{
protected $table = 'users';
protected $fillable = ['email'];
protected function updatedAt(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value),
set: fn ($value) => Carbon::parse($value)->timestamp,
);
}
protected function createdAt(): Attribute
{
return Attribute::make(
get: fn ($value) => Carbon::parse($value),
set: fn ($value) => Carbon::parse($value)->timestamp,
);
}
}
class UserWithIntTimestampsViaMutator extends Model
{
protected $table = 'users';
protected $fillable = ['email'];
protected function getUpdatedAtAttribute($value)
{
return Carbon::parse($value);
}
protected function setUpdatedAtAttribute($value)
{
$this->attributes['updated_at'] = Carbon::parse($value)->timestamp;
}
protected function getCreatedAtAttribute($value)
{
return Carbon::parse($value);
}
protected function setCreatedAtAttribute($value)
{
$this->attributes['created_at'] = Carbon::parse($value)->timestamp;
}
}
class UserWithUpdatedAtViaMutator extends Model
{
protected $table = 'users_nullable_timestamps';
protected $fillable = ['email', 'updated_at'];
public function setUpdatedAtAttribute($value)
{
if (! $this->id) {
return;
}
$this->updated_at = $value;
}
}
| |
193014
|
<?php
namespace Illuminate\Tests\Integration\Auth;
use Illuminate\Auth\Access\Events\GateEvaluated;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate;
use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser;
use Illuminate\Tests\Integration\Auth\Fixtures\Policies\AuthenticationTestUserPolicy;
use Orchestra\Testbench\TestCase;
class GatePolicyResolutionTest extends TestCase
{
public function testGateEvaluationEventIsFired()
{
Event::fake();
Gate::check('foo');
Event::assertDispatched(GateEvaluated::class);
}
public function testPolicyCanBeGuessedUsingClassConventions()
{
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(AuthenticationTestUser::class)
);
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(Fixtures\Models\AuthenticationTestUser::class)
);
$this->assertNull(
Gate::getPolicyFor(static::class)
);
}
public function testPolicyCanBeGuessedUsingCallback()
{
Gate::guessPolicyNamesUsing(function () {
return AuthenticationTestUserPolicy::class;
});
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(AuthenticationTestUser::class)
);
}
public function testPolicyCanBeGuessedMultipleTimes()
{
Gate::guessPolicyNamesUsing(function () {
return [
'App\\Policies\\TestUserPolicy',
AuthenticationTestUserPolicy::class,
];
});
$this->assertInstanceOf(
AuthenticationTestUserPolicy::class,
Gate::getPolicyFor(AuthenticationTestUser::class)
);
}
}
| |
193020
|
<?php
namespace Illuminate\Tests\Integration\Auth\Middleware;
use Illuminate\Auth\Middleware\RedirectIfAuthenticated;
use Illuminate\Contracts\Routing\Registrar;
use Illuminate\Support\Str;
use Illuminate\Tests\Integration\Auth\Fixtures\AuthenticationTestUser;
use Orchestra\Testbench\Factories\UserFactory;
use Orchestra\Testbench\TestCase;
class RedirectIfAuthenticatedTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->withoutExceptionHandling();
/** @var \Illuminate\Contracts\Routing\Registrar $router */
$this->router = $this->app->make(Registrar::class);
$this->router->get('/login', function () {
return response('Login Form');
})->middleware(RedirectIfAuthenticated::class);
UserFactory::new()->create();
$user = AuthenticationTestUser::first();
$this->router->get('/login', function () {
return response('Login Form');
})->middleware(RedirectIfAuthenticated::class);
UserFactory::new()->create();
$this->user = AuthenticationTestUser::first();
}
protected function defineEnvironment($app)
{
$app['config']->set('app.key', Str::random(32));
$app['config']->set('auth.providers.users.model', AuthenticationTestUser::class);
}
protected function defineDatabaseMigrations()
{
$this->loadLaravelMigrations();
}
public function testWhenDashboardNamedRouteIsAvailable()
{
$this->router->get('/named-dashboard', function () {
return response('Named Dashboard');
})->name('dashboard');
$response = $this->actingAs($this->user)->get('/login');
$response->assertRedirect('/named-dashboard');
}
public function testWhenHomeNamedRouteIsAvailable()
{
$this->router->get('/named-home', function () {
return response('Named Home');
})->name('home');
$response = $this->actingAs($this->user)->get('/login');
$response->assertRedirect('/named-home');
}
public function testWhenDashboardSlugIsAvailable()
{
$this->router->get('/dashboard', function () {
return response('My Dashboard');
});
$response = $this->actingAs($this->user)->get('/login');
$response->assertRedirect('/dashboard');
}
public function testWhenHomeSlugIsAvailable()
{
$this->router->get('/home', function () {
return response('My Home');
})->name('home');
$response = $this->actingAs($this->user)->get('/login');
$response->assertRedirect('/home');
}
public function testWhenHomeOrDashboardAreNotAvailable()
{
$response = $this->actingAs($this->user)->get('/login');
$response->assertRedirect('/');
}
public function testWhenGuest()
{
$response = $this->get('/login');
$response->assertOk();
$response->assertSee('Login Form');
}
}
| |
193049
|
<?php
namespace Illuminate\Tests\Integration\Foundation\Testing\Concerns;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Foundation\Auth\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
use Orchestra\Testbench\Attributes\WithMigration;
use Orchestra\Testbench\TestCase;
#[WithMigration]
class InteractsWithAuthenticationTest extends TestCase
{
use RefreshDatabase;
protected function defineEnvironment($app)
{
$app['config']->set('auth.guards.api', [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
]);
}
protected function afterRefreshingDatabase()
{
Schema::table('users', function (Blueprint $table) {
$table->renameColumn('name', 'username');
});
Schema::table('users', function (Blueprint $table) {
$table->tinyInteger('is_active')->default(0);
});
User::forceCreate([
'username' => 'taylorotwell',
'email' => 'taylorotwell@laravel.com',
'password' => bcrypt('password'),
'is_active' => true,
]);
}
public function testActingAsIsProperlyHandledForSessionAuth()
{
Route::get('me', function (Request $request) {
return 'Hello '.$request->user()->username;
})->middleware(['auth']);
$user = User::where('username', '=', 'taylorotwell')->first();
$this->actingAs($user)
->get('/me')
->assertSuccessful()
->assertSeeText('Hello taylorotwell');
}
public function testActingAsIsProperlyHandledForAuthViaRequest()
{
Route::get('me', function (Request $request) {
return 'Hello '.$request->user()->username;
})->middleware(['auth:api']);
Auth::viaRequest('api', function ($request) {
return $request->user();
});
$user = User::where('username', '=', 'taylorotwell')->first();
$this->actingAs($user, 'api')
->get('/me')
->assertSuccessful()
->assertSeeText('Hello taylorotwell');
}
}
| |
193053
|
My custom 404
<?php $foo();
| |
193069
|
<?php
namespace Illuminate\Tests\Integration\Filesystem;
use Illuminate\Support\Facades\Storage;
use Orchestra\Testbench\TestCase;
class ServeFileTest extends TestCase
{
protected function setUp(): void
{
$this->afterApplicationCreated(function () {
Storage::put('serve-file-test.txt', 'Hello World');
});
$this->beforeApplicationDestroyed(function () {
Storage::delete('serve-file-test.txt');
});
parent::setUp();
}
public function testItCanServeAnExistingFile()
{
$url = Storage::temporaryUrl('serve-file-test.txt', now()->addMinutes(1));
$response = $this->get($url);
$this->assertEquals('Hello World', $response->streamedContent());
}
public function testItWill404OnMissingFile()
{
$url = Storage::temporaryUrl('serve-missing-test.txt', now()->addMinutes(1));
$response = $this->get($url);
$response->assertNotFound();
}
public function testItWill403OnWrongSignature()
{
$url = Storage::temporaryUrl('serve-file-test.txt', now()->addMinutes(1));
$url = $url.'c';
$response = $this->get($url);
$response->assertForbidden();
}
protected function getEnvironmentSetup($app)
{
tap($app['config'], function ($config) {
$config->set('filesystems.disks.local.serve', true);
});
}
}
| |
193071
|
<?php
namespace Illuminate\Tests\Integration\Filesystem;
use Illuminate\Support\Facades\File;
use Orchestra\Testbench\TestCase;
use PHPUnit\Framework\Attributes\RequiresOperatingSystem;
use Symfony\Component\Process\Process;
#[RequiresOperatingSystem('Linux|Darwin')]
class FilesystemTest extends TestCase
{
protected $stubFile;
protected function setUp(): void
{
$this->afterApplicationCreated(function () {
File::put($file = storage_path('app/public/StardewTaylor.png'), File::get(__DIR__.'/Fixtures/StardewTaylor.png'));
$this->stubFile = $file;
});
$this->beforeApplicationDestroyed(function () {
if (File::exists($this->stubFile)) {
File::delete($this->stubFile);
}
});
parent::setUp();
}
public function testItCanDeleteViaFilesystemShouldUpdatesFileExists()
{
$this->assertTrue(File::exists($this->stubFile));
$this->assertTrue(File::isFile($this->stubFile));
File::delete($this->stubFile);
$this->assertFalse(File::exists($this->stubFile));
}
public function testItCanDeleteViaFilesystemRequiresManualClearStatCacheOnFileExistsFromDifferentProcess()
{
$this->assertTrue(File::exists($this->stubFile));
$this->assertTrue(File::isFile($this->stubFile));
Process::fromShellCommandline("rm {$this->stubFile}")->run();
clearstatcache(true, $this->stubFile);
$this->assertFalse(File::exists($this->stubFile));
}
public function testItCanDeleteViaFilesystemShouldUpdatesIsFile()
{
$this->assertTrue(File::exists($this->stubFile));
$this->assertTrue(File::isFile($this->stubFile));
File::delete($this->stubFile);
$this->assertFalse(File::isFile($this->stubFile));
}
public function testItCanDeleteViaFilesystemRequiresManualClearStatCacheOnIsFileFromDifferentProcess()
{
$this->assertTrue(File::exists($this->stubFile));
$this->assertTrue(File::isFile($this->stubFile));
Process::fromShellCommandline("rm {$this->stubFile}")->run();
clearstatcache(true, $this->stubFile);
$this->assertFalse(File::isFile($this->stubFile));
}
public function testItCanDeleteDirectoryViaFilesystem()
{
if (! File::exists(storage_path('app/public/testdir'))) {
File::makeDirectory(storage_path('app/public/testdir'));
}
$this->assertTrue(File::exists(storage_path('app/public/testdir')));
File::deleteDirectory(storage_path('app/public/testdir'));
$this->assertFalse(File::exists(storage_path('app/public/testdir')));
}
}
| |
193085
|
<?php
namespace Illuminate\Tests\Integration\Support;
use Illuminate\Support\Facades\Auth;
use Orchestra\Testbench\TestCase;
use RuntimeException;
class AuthFacadeTest extends TestCase
{
public function testItFailsIfTheUiPackageIsMissing()
{
$this->expectExceptionObject(new RuntimeException(
'In order to use the Auth::routes() method, please install the laravel/ui package.'
));
Auth::routes();
}
}
| |
193106
|
{
use ValidatesRequests;
protected function defineEnvironment($app)
{
$app['config']['cors'] = [
'paths' => ['api/*'],
'supports_credentials' => false,
'allowed_origins' => ['http://localhost'],
'allowed_headers' => ['X-Custom-1', 'X-Custom-2'],
'allowed_methods' => ['GET', 'POST'],
'exposed_headers' => [],
'max_age' => 0,
];
$kernel = $app->make(Kernel::class);
$kernel->prependMiddleware(HandleCors::class);
}
protected function defineRoutes($router)
{
$this->addWebRoutes($router);
$this->addApiRoutes($router);
}
public function testShouldReturnHeaderAssessControlAllowOriginWhenDontHaveHttpOriginOnRequest()
{
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://localhost', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(204, $crawler->getStatusCode());
}
public function testOptionsAllowOriginAllowed()
{
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://localhost', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(204, $crawler->getStatusCode());
}
public function testAllowAllOrigins()
{
$this->app['config']->set('cors.allowed_origins', ['*']);
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://laravel.com',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('*', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(204, $crawler->getStatusCode());
}
public function testAllowAllOriginsWildcard()
{
$this->app['config']->set('cors.allowed_origins', ['*.laravel.com']);
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://test.laravel.com',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://test.laravel.com', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(204, $crawler->getStatusCode());
}
public function testOriginsWildcardIncludesNestedSubdomains()
{
$this->app['config']->set('cors.allowed_origins', ['*.laravel.com']);
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://api.service.test.laravel.com',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://api.service.test.laravel.com', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(204, $crawler->getStatusCode());
}
public function testAllowAllOriginsWildcardNoMatch()
{
$this->app['config']->set('cors.allowed_origins', ['*.laravel.com']);
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://test.symfony.com',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertEquals(null, $crawler->headers->get('Access-Control-Allow-Origin'));
}
public function testOptionsAllowOriginAllowedNonExistingRoute()
{
$crawler = $this->call('OPTIONS', 'api/pang', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://localhost', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(204, $crawler->getStatusCode());
}
public function testOptionsAllowOriginNotAllowed()
{
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://otherhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://localhost', $crawler->headers->get('Access-Control-Allow-Origin'));
}
public function testAllowMethodAllowed()
{
$crawler = $this->call('POST', 'web/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertEquals(null, $crawler->headers->get('Access-Control-Allow-Methods'));
$this->assertEquals(200, $crawler->getStatusCode());
$this->assertSame('PONG', $crawler->getContent());
}
public function testAllowMethodNotAllowed()
{
$crawler = $this->call('POST', 'web/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'PUT',
]);
$this->assertEquals(null, $crawler->headers->get('Access-Control-Allow-Methods'));
$this->assertEquals(200, $crawler->getStatusCode());
}
public function testAllowHeaderAllowedOptions()
{
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'x-custom-1, x-custom-2',
]);
$this->assertSame('x-custom-1, x-custom-2', $crawler->headers->get('Access-Control-Allow-Headers'));
$this->assertEquals(204, $crawler->getStatusCode());
$this->assertSame('', $crawler->getContent());
}
public function testAllowHeaderAllowedWildcardOptions()
{
$this->app['config']->set('cors.allowed_headers', ['*']);
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'x-custom-3',
]);
$this->assertSame('x-custom-3', $crawler->headers->get('Access-Control-Allow-Headers'));
$this->assertEquals(204, $crawler->getStatusCode());
$this->assertSame('', $crawler->getContent());
}
public function testAllowHeaderNotAllowedOptions()
{
$crawler = $this->call('OPTIONS', 'api/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'x-custom-3',
]);
$this->assertSame('x-custom-1, x-custom-2', $crawler->headers->get('Access-Control-Allow-Headers'));
}
public function testAllowHeaderAllowed()
{
$crawler = $this->call('POST', 'web/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'x-custom-1, x-custom-2',
]);
$this->assertEquals(null, $crawler->headers->get('Access-Control-Allow-Headers'));
$this->assertEquals(200, $crawler->getStatusCode());
$this->assertSame('PONG', $crawler->getContent());
}
public function testAllowHeaderAllowedWildcard()
{
$this->app['config']->set('cors.allowed_headers', ['*']);
$crawler = $this->call('POST', 'web/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'x-custom-3',
]);
$this->assertEquals(null, $crawler->headers->get('Access-Control-Allow-Headers'));
$this->assertEquals(200, $crawler->getStatusCode());
$this->assertSame('PONG', $crawler->getContent());
}
public function testAllowHeaderNotAllowed()
{
$crawler = $this->call('POST', 'web/ping', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'x-custom-3',
]);
$this->assertEquals(null, $crawler->headers->get('Access-Control-Allow-Headers'));
$this->assertEquals(200, $crawler->getStatusCode());
}
public function testError()
{
$crawler = $this->call('POST', 'api/error', [], [], [], [
'HTTP_ORIGIN' => 'http://localhost',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertSame('http://localhost', $crawler->headers->get('Access-Control-Allow-Origin'));
$this->assertEquals(500, $crawler->getStatusCode());
}
| |
193134
|
<?php
namespace Illuminate\Tests\Integration\Http\Fixtures;
use Illuminate\Database\Eloquent\Model;
class Author extends Model
{
/**
* The attributes that aren't mass assignable.
*
* @var string[]
*/
protected $guarded = [];
}
| |
193148
|
<div class="app-layout">
{{ $slot }}
</div>
| |
193162
|
@props(['name'])
<div {{ $attributes }}>
Hello {{ $name }}
</div>
| |
193165
|
@props(['href'])
<a href="{{ $href }}">{{ $slot }}</a>
| |
193199
|
<?php
namespace Illuminate\Tests\Integration\Queue;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Queue;
use Orchestra\Testbench\Attributes\WithMigration;
#[WithMigration]
#[WithMigration('queue')]
class WorkCommandTest extends QueueTestCase
{
use DatabaseMigrations;
protected function setUp(): void
{
$this->beforeApplicationDestroyed(function () {
FirstJob::$ran = false;
SecondJob::$ran = false;
ThirdJob::$ran = false;
});
parent::setUp();
$this->markTestSkippedWhenUsingSyncQueueDriver();
}
public function testRunningOneJob()
{
Queue::push(new FirstJob);
Queue::push(new SecondJob);
$this->artisan('queue:work', [
'--once' => true,
'--memory' => 1024,
])->assertExitCode(0);
$this->assertSame(1, Queue::size());
$this->assertTrue(FirstJob::$ran);
$this->assertFalse(SecondJob::$ran);
}
public function testRunTimestampOutputWithDefaultAppTimezone()
{
// queue.output_timezone not set at all
$this->travelTo(Carbon::create(2023, 1, 18, 10, 10, 11));
Queue::push(new FirstJob);
$this->artisan('queue:work', [
'--once' => true,
'--memory' => 1024,
])->expectsOutputToContain('2023-01-18 10:10:11')
->assertExitCode(0);
}
public function testRunTimestampOutputWithDifferentLogTimezone()
{
$this->app['config']->set('queue.output_timezone', 'Europe/Helsinki');
$this->travelTo(Carbon::create(2023, 1, 18, 10, 10, 11));
Queue::push(new FirstJob);
$this->artisan('queue:work', [
'--once' => true,
'--memory' => 1024,
])->expectsOutputToContain('2023-01-18 12:10:11')
->assertExitCode(0);
}
public function testRunTimestampOutputWithSameAppDefaultAndQueueLogDefault()
{
$this->app['config']->set('queue.output_timezone', 'UTC');
$this->travelTo(Carbon::create(2023, 1, 18, 10, 10, 11));
Queue::push(new FirstJob);
$this->artisan('queue:work', [
'--once' => true,
'--memory' => 1024,
])->expectsOutputToContain('2023-01-18 10:10:11')
->assertExitCode(0);
}
public function testDaemon()
{
Queue::push(new FirstJob);
Queue::push(new SecondJob);
$this->artisan('queue:work', [
'--daemon' => true,
'--stop-when-empty' => true,
'--memory' => 1024,
])->assertExitCode(0);
$this->assertSame(0, Queue::size());
$this->assertTrue(FirstJob::$ran);
$this->assertTrue(SecondJob::$ran);
}
public function testMemoryExceeded()
{
Queue::push(new FirstJob);
Queue::push(new SecondJob);
$this->artisan('queue:work', [
'--daemon' => true,
'--stop-when-empty' => true,
'--memory' => 0.1,
])->assertExitCode(12);
// Memory limit isn't checked until after the first job is attempted.
$this->assertSame(1, Queue::size());
$this->assertTrue(FirstJob::$ran);
$this->assertFalse(SecondJob::$ran);
}
public function testMaxJobsExceeded()
{
$this->markTestSkippedWhenUsingQueueDrivers(['redis', 'beanstalkd']);
Queue::push(new FirstJob);
Queue::push(new SecondJob);
$this->artisan('queue:work', [
'--daemon' => true,
'--stop-when-empty' => true,
'--max-jobs' => 1,
]);
// Memory limit isn't checked until after the first job is attempted.
$this->assertSame(1, Queue::size());
$this->assertTrue(FirstJob::$ran);
$this->assertFalse(SecondJob::$ran);
}
public function testMaxTimeExceeded()
{
$this->markTestSkippedWhenUsingQueueDrivers(['redis', 'beanstalkd']);
Queue::push(new ThirdJob);
Queue::push(new FirstJob);
Queue::push(new SecondJob);
$this->artisan('queue:work', [
'--daemon' => true,
'--stop-when-empty' => true,
'--max-time' => 1,
]);
// Memory limit isn't checked until after the first job is attempted.
$this->assertSame(2, Queue::size());
$this->assertTrue(ThirdJob::$ran);
$this->assertFalse(FirstJob::$ran);
$this->assertFalse(SecondJob::$ran);
}
}
class FirstJob implements ShouldQueue
{
use Dispatchable, Queueable;
public static $ran = false;
public function handle()
{
static::$ran = true;
}
}
class SecondJob implements ShouldQueue
{
use Dispatchable, Queueable;
public static $ran = false;
public function handle()
{
static::$ran = true;
}
}
class ThirdJob implements ShouldQueue
{
use Dispatchable, Queueable;
public static $ran = false;
public function handle()
{
sleep(1);
static::$ran = true;
}
}
| |
193208
|
<?php
namespace Illuminate\Tests\Integration\Cookie;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Http\Response;
use Illuminate\Session\NullSessionHandler;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Mockery as m;
use Orchestra\Testbench\TestCase;
class CookieTest extends TestCase
{
public function test_cookie_is_sent_back_with_proper_expire_time_when_should_expire_on_close()
{
$this->app['config']->set('session.expire_on_close', true);
Route::get('/', function () {
return 'hello world';
})->middleware('web');
$response = $this->get('/');
$this->assertCount(2, $response->headers->getCookies());
$this->assertEquals(0, $response->headers->getCookies()[1]->getExpiresTime());
}
public function test_cookie_is_sent_back_with_proper_expire_time_with_respect_to_lifetime()
{
$this->app['config']->set('session.expire_on_close', false);
$this->app['config']->set('session.lifetime', 1);
Route::get('/', function () {
return 'hello world';
})->middleware('web');
Carbon::setTestNow(Carbon::now());
$response = $this->get('/');
$this->assertCount(2, $response->headers->getCookies());
$this->assertEquals(Carbon::now()->getTimestamp() + 60, $response->headers->getCookies()[1]->getExpiresTime());
}
protected function getEnvironmentSetUp($app)
{
$app->instance(
ExceptionHandler::class,
$handler = m::mock(ExceptionHandler::class)->shouldIgnoreMissing()
);
$handler->shouldReceive('render')->andReturn(new Response);
$app['config']->set('app.key', Str::random(32));
$app['config']->set('session.driver', 'fake-null');
Session::extend('fake-null', function () {
return new NullSessionHandler;
});
}
}
| |
193223
|
<?php
namespace Illuminate\Tests\Integration\Generators;
class PolicyMakeCommandTest extends TestCase
{
protected $files = [
'app/Policies/FooPolicy.php',
];
public function testItCanGeneratePolicyFile()
{
$this->artisan('make:policy', ['name' => 'FooPolicy'])
->assertExitCode(0);
$this->assertFileContains([
'namespace App\Policies;',
'use Illuminate\Foundation\Auth\User;',
'class FooPolicy',
], 'app/Policies/FooPolicy.php');
}
public function testItCanGeneratePolicyFileWithModelOption()
{
$this->artisan('make:policy', ['name' => 'FooPolicy', '--model' => 'Post'])
->assertExitCode(0);
$this->assertFileContains([
'namespace App\Policies;',
'use App\Models\Post;',
'use Illuminate\Foundation\Auth\User;',
'class FooPolicy',
'public function viewAny(User $user)',
'public function view(User $user, Post $post)',
'public function create(User $user)',
'public function update(User $user, Post $post)',
'public function delete(User $user, Post $post)',
'public function restore(User $user, Post $post)',
'public function forceDelete(User $user, Post $post)',
], 'app/Policies/FooPolicy.php');
}
}
| |
193238
|
<?php
namespace Illuminate\Tests\Integration\Generators;
class MigrateMakeCommandTest extends TestCase
{
public function testItCanGenerateMigrationFile()
{
$this->artisan('make:migration', ['name' => 'AddBarToFoosTable'])
->assertExitCode(0);
$this->assertMigrationFileContains([
'use Illuminate\Database\Migrations\Migration;',
'return new class extends Migration',
'Schema::table(\'foos\', function (Blueprint $table) {',
], 'add_bar_to_foos_table.php');
}
public function testItCanGenerateMigrationFileWIthTableOption()
{
$this->artisan('make:migration', ['name' => 'AddBarToFoosTable', '--table' => 'foobar'])
->assertExitCode(0);
$this->assertMigrationFileContains([
'use Illuminate\Database\Migrations\Migration;',
'return new class extends Migration',
'Schema::table(\'foobar\', function (Blueprint $table) {',
], 'add_bar_to_foos_table.php');
}
public function testItCanGenerateMigrationFileUsingCreateKeyword()
{
$this->artisan('make:migration', ['name' => 'CreateFoosTable'])
->assertExitCode(0);
$this->assertMigrationFileContains([
'use Illuminate\Database\Migrations\Migration;',
'return new class extends Migration',
'Schema::create(\'foos\', function (Blueprint $table) {',
'Schema::dropIfExists(\'foos\');',
], 'create_foos_table.php');
}
public function testItCanGenerateMigrationFileUsingCreateOption()
{
$this->artisan('make:migration', ['name' => 'FoosTable', '--create' => 'foobar'])
->assertExitCode(0);
$this->assertMigrationFileContains([
'use Illuminate\Database\Migrations\Migration;',
'return new class extends Migration',
'Schema::create(\'foobar\', function (Blueprint $table) {',
'Schema::dropIfExists(\'foobar\');',
], 'foos_table.php');
}
}
| |
193239
|
<?php
namespace Illuminate\Tests\Integration\Generators;
use Illuminate\Session\Console\SessionTableCommand;
class SessionTableCommandTest extends TestCase
{
public function testCreateMakesMigration()
{
$this->artisan(SessionTableCommand::class)->assertExitCode(0);
$this->assertMigrationFileContains([
'use Illuminate\Database\Migrations\Migration;',
'return new class extends Migration',
'Schema::create(\'sessions\', function (Blueprint $table) {',
'Schema::dropIfExists(\'sessions\');',
], 'create_sessions_table.php');
}
}
| |
193253
|
class PrecognitionTestController
{
use ValidatesRequests;
public function methodWhereEscapedDotRuleIsValidatedViaControllerValidate(Request $request)
{
precognitive(function () use ($request) {
$this->validate($request, [
'escaped\.dot' => 'required',
]);
fail();
});
fail();
}
public function methodWhereEscapedDotRuleIsValidatedViaControllerValidateWith()
{
precognitive(function () {
$this->validateWith([
'escaped\.dot' => 'required',
]);
fail();
});
fail();
}
public function methodWhereNestedRulesAreValidatedViaControllerValidate(Request $request)
{
precognitive(function () use ($request) {
$this->validate($request, [
'nested' => ['required', 'array', 'min:1'],
'nested.*.name' => ['required', 'string'],
]);
fail();
});
fail();
}
public function methodWhereNestedRulesAreValidatedViaControllerValidateWith(Request $request)
{
precognitive(function () {
$this->validateWith([
'nested' => ['required', 'array', 'min:1'],
'nested.*.name' => ['required', 'string'],
]);
fail();
});
fail();
}
public function methodWherePredictionValidatesViaControllerValidate(Request $request)
{
precognitive(function () use ($request) {
$this->validate($request, [
'required_integer' => 'required|integer',
...! $request->isPrecognitive() ? ['required_integer_when_not_precognitive' => 'required|integer'] : [],
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]);
fail();
});
fail();
}
public function methodWherePredictionValidatesViaControllerValidateWithBag(Request $request)
{
precognitive(function () use ($request) {
$this->validateWithBag('custom-bag', $request, [
'required_integer' => 'required|integer',
...! $request->isPrecognitive() ? ['required_integer_when_not_precognitive' => 'required|integer'] : [],
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]);
fail();
});
fail();
}
public function methodWherePredictionValidatesViaControllerValidateWith(Request $request)
{
precognitive(function () use ($request) {
$this->validateWith([
'required_integer' => 'required|integer',
...! $request->isPrecognitive() ? ['required_integer_when_not_precognitive' => 'required|integer'] : [],
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]);
fail();
});
fail();
}
public function methodWherePredictionReturnsResponseWithControllerValidate(Request $request)
{
precognitive(function ($bail) use ($request) {
$this->validate($request, [
'required_integer' => 'required|integer',
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]);
$bail(response('Post-validation code was executed.'));
fail();
});
fail();
}
public function methodWherePredictionReturnsResponseWithControllerValidateWithBag(Request $request)
{
precognitive(function ($bail) use ($request) {
$this->validateWithBag('custom-bag', $request, [
'required_integer' => 'required|integer',
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]);
$bail(response('Post-validation code was executed.'));
fail();
});
fail();
}
public function methodWherePredictionReturnsResponseWithControllerValidateWith(Request $request)
{
precognitive(function ($bail) {
$this->validateWith([
'required_integer' => 'required|integer',
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]);
$bail(response('Post-validation code was executed.'));
fail();
});
fail();
}
public function methodWherePredictionReturnsResponseWithControllerValidateWithPassingValidator(Request $request)
{
precognitive(function ($bail) use ($request) {
$this->validateWith(Validator::make($request->all(), [
'required_integer' => 'required|integer',
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
]));
$bail(response('Post-validation code was executed.'));
fail();
});
fail();
}
public function methodThatFails(ClassThatBindsOnInstantiation $foo)
{
fail();
}
}
class PrecognitionTestRequest extends FormRequest
{
public function rules()
{
$rules = [
'required_integer' => 'required|integer',
'optional_integer_1' => 'integer',
'optional_integer_2' => 'integer',
' input with spaces ' => 'integer',
];
if (! $this->isPrecognitive()) {
$rules['required_integer_when_not_precognitive'] = 'required|integer';
}
return $rules;
}
}
class NestedPrecognitionTestRequest extends FormRequest
{
public function rules()
{
return [
'nested' => ['required', 'array', 'min:1'],
'nested.*.name' => ['required', 'string'],
];
}
}
class PrecognitionRequestWithEscapedDots extends FormRequest
{
public function rules()
{
return [
'escaped\.dot' => ['required'],
];
}
}
class ClassThatBindsOnInstantiation
{
public function __construct()
{
app()->instance('ClassWasInstantiated', true);
}
}
class PrecognitionInvokingController extends HandlePrecognitiveRequests
{
protected function prepareForPrecognition($request)
{
parent::prepareForPrecognition($request);
app()->bind(CallableDispatcherContract::class, fn ($app) => new CallableDispatcher($app));
app()->bind(ControllerDispatcherContract::class, fn ($app) => new ControllerDispatcher($app));
}
}
class MiddlewareReturningSymfonyResponse
{
public function handle($request, $next)
{
return response()->streamDownload(function () {
//
}, null, ['Expected' => 'Header']);
}
}
class MiddlewareThatReturnsNoContent
{
public function handle()
{
return response()->noContent();
}
}
| |
193261
|
<?php
namespace Illuminate\Tests\Integration\Routing;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Session\SessionServiceProvider;
use Illuminate\Support\Facades\Route;
use Orchestra\Testbench\TestCase;
class PreviousUrlTest extends TestCase
{
public function testPreviousUrlWithoutSession()
{
Route::post('/previous-url', function (DummyFormRequest $request) {
return 'OK';
});
$response = $this->postJson('/previous-url');
$this->assertEquals(422, $response->status());
}
protected function getApplicationProviders($app)
{
$providers = parent::getApplicationProviders($app);
return array_filter($providers, function ($provider) {
return $provider !== SessionServiceProvider::class;
});
}
}
class DummyFormRequest extends FormRequest
{
public function rules()
{
return [
'foo' => [
'required',
'string',
],
];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.