diff --git a/.github/workflows/build-ci.yml b/.github/workflows/build-ci.yml index 8feea0f6c..ecbf50b50 100644 --- a/.github/workflows/build-ci.yml +++ b/.github/workflows/build-ci.yml @@ -7,27 +7,6 @@ on: pull_request: jobs: - php-cs-fixer: - runs-on: ubuntu-latest - env: - PHP_CS_FIXER_VERSION: v3.6.0 - strategy: - matrix: - php: - - '8.1' - steps: - - name: Checkout - uses: actions/checkout@v3 - - name: Setup PHP - uses: shivammathur/setup-php@v2 - with: - php-version: ${{ matrix.php }} - extensions: curl,mbstring - tools: php-cs-fixer:${{ env.PHP_CS_FIXER_VERSION }} - coverage: none - - name: Run PHP-CS-Fixer Fix, version ${{ env.PHP_CS_FIXER_VERSION }} - run: php-cs-fixer fix --dry-run --diff --ansi - build: runs-on: ${{ matrix.os }} name: PHP v${{ matrix.php }} with MongoDB ${{ matrix.mongodb }} diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml new file mode 100644 index 000000000..45daae584 --- /dev/null +++ b/.github/workflows/coding-standards.yml @@ -0,0 +1,55 @@ +name: "Coding Standards" + +on: + push: + branches: + tags: + pull_request: + +env: + PHP_VERSION: "8.2" + DRIVER_VERSION: "stable" + +jobs: + phpcs: + name: "phpcs" + runs-on: "ubuntu-22.04" + + steps: + - name: "Checkout" + uses: "actions/checkout@v3" + + - name: Setup cache environment + id: extcache + uses: shivammathur/cache-extensions@v1 + with: + php-version: ${{ env.PHP_VERSION }} + extensions: "mongodb-${{ env.DRIVER_VERSION }}" + key: "extcache-v1" + + - name: Cache extensions + uses: actions/cache@v3 + with: + path: ${{ steps.extcache.outputs.dir }} + key: ${{ steps.extcache.outputs.key }} + restore-keys: ${{ steps.extcache.outputs.key }} + + - name: "Install PHP" + uses: "shivammathur/setup-php@v2" + with: + coverage: "none" + extensions: "mongodb-${{ env.DRIVER_VERSION }}" + php-version: "${{ env.PHP_VERSION }}" + tools: "cs2pr" + + - name: "Show driver information" + run: "php --ri mongodb" + + - name: "Install dependencies with Composer" + uses: "ramsey/composer-install@2.2.0" + with: + composer-options: "--no-suggest" + + # The -q option is required until phpcs v4 is released + - name: "Run PHP_CodeSniffer" + run: "vendor/bin/phpcs -q --no-colors --report=checkstyle | cs2pr" diff --git a/.gitignore b/.gitignore index 8a586f33b..4a03159de 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,7 @@ .DS_Store .idea/ .phpunit.result.cache -/.php-cs-fixer.php -/.php-cs-fixer.cache +.phpcs-cache /vendor composer.lock composer.phar diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php deleted file mode 100644 index 20c262e3a..000000000 --- a/.php-cs-fixer.dist.php +++ /dev/null @@ -1,187 +0,0 @@ - true, - 'align_multiline_comment' => [ - 'comment_type' => 'phpdocs_like', - ], - 'ordered_imports' => [ - 'sort_algorithm' => 'alpha', - ], - 'array_indentation' => true, - 'binary_operator_spaces' => [ - 'operators' => [ - '=>' => null, - '=' => 'single_space', - ], - ], - 'blank_line_after_namespace' => true, - 'blank_line_after_opening_tag' => true, - 'blank_line_before_statement' => [ - 'statements' => [ - 'return', - ], - ], - 'cast_spaces' => true, - 'class_definition' => false, - 'clean_namespace' => true, - 'compact_nullable_typehint' => true, - 'concat_space' => [ - 'spacing' => 'none', - ], - 'declare_equal_normalize' => true, - 'no_alias_language_construct_call' => true, - 'elseif' => true, - 'encoding' => true, - 'full_opening_tag' => true, - 'function_declaration' => true, - 'function_typehint_space' => true, - 'single_line_comment_style' => [ - 'comment_types' => [ - 'hash', - ], - ], - 'heredoc_to_nowdoc' => true, - 'include' => true, - 'indentation_type' => true, - 'integer_literal_case' => true, - 'braces' => false, - 'lowercase_cast' => true, - 'constant_case' => [ - 'case' => 'lower', - ], - 'lowercase_keywords' => true, - 'lowercase_static_reference' => true, - 'magic_constant_casing' => true, - 'magic_method_casing' => true, - 'method_argument_space' => [ - 'on_multiline' => 'ignore', - ], - 'class_attributes_separation' => [ - 'elements' => [ - 'method' => 'one', - ], - ], - 'visibility_required' => [ - 'elements' => [ - 'method', - 'property', - ], - ], - 'native_function_casing' => true, - 'native_function_type_declaration_casing' => true, - 'no_alternative_syntax' => true, - 'no_binary_string' => true, - 'no_blank_lines_after_class_opening' => true, - 'no_blank_lines_after_phpdoc' => true, - 'no_extra_blank_lines' => [ - 'tokens' => [ - 'throw', - 'use', - 'extra', - ], - ], - 'no_closing_tag' => true, - 'no_empty_phpdoc' => true, - 'no_empty_statement' => true, - 'no_leading_import_slash' => true, - 'no_leading_namespace_whitespace' => true, - 'no_multiline_whitespace_around_double_arrow' => true, - 'multiline_whitespace_before_semicolons' => true, - 'no_short_bool_cast' => true, - 'no_singleline_whitespace_before_semicolons' => true, - 'no_space_around_double_colon' => true, - 'no_spaces_after_function_name' => true, - 'no_spaces_around_offset' => [ - 'positions' => [ - 'inside', - ], - ], - 'no_spaces_inside_parenthesis' => true, - 'no_trailing_comma_in_list_call' => true, - 'no_trailing_comma_in_singleline_array' => true, - 'no_trailing_whitespace' => true, - 'no_trailing_whitespace_in_comment' => true, - 'no_unneeded_control_parentheses' => true, - 'no_unneeded_curly_braces' => true, - 'no_unset_cast' => true, - 'no_unused_imports' => true, - 'lambda_not_used_import' => true, - 'no_useless_return' => true, - 'no_whitespace_before_comma_in_array' => true, - 'no_whitespace_in_blank_line' => true, - 'normalize_index_brace' => true, - 'not_operator_with_successor_space' => true, - 'object_operator_without_whitespace' => true, - 'phpdoc_indent' => true, - 'phpdoc_inline_tag_normalizer' => true, - 'phpdoc_no_access' => true, - 'phpdoc_no_package' => true, - 'phpdoc_no_useless_inheritdoc' => true, - 'phpdoc_return_self_reference' => true, - 'phpdoc_scalar' => true, - 'phpdoc_single_line_var_spacing' => true, - 'phpdoc_summary' => true, - 'phpdoc_trim' => true, - 'phpdoc_no_alias_tag' => [ - 'replacements' => [ - 'type' => 'var', - ], - ], - 'phpdoc_types' => true, - 'phpdoc_var_without_name' => true, - 'increment_style' => [ - 'style' => 'post', - ], - 'no_mixed_echo_print' => [ - 'use' => 'echo', - ], - 'return_type_declaration' => [ - 'space_before' => 'none', - ], - 'array_syntax' => [ - 'syntax' => 'short', - ], - 'list_syntax' => [ - 'syntax' => 'short', - ], - 'short_scalar_cast' => true, - 'single_blank_line_at_eof' => true, - 'single_blank_line_before_namespace' => true, - 'single_class_element_per_statement' => true, - 'single_import_per_statement' => true, - 'single_line_after_imports' => true, - 'single_quote' => true, - 'space_after_semicolon' => true, - 'standardize_not_equals' => true, - 'switch_case_semicolon_to_colon' => true, - 'switch_case_space' => true, - 'switch_continue_to_break' => true, - 'ternary_operator_spaces' => true, - 'trailing_comma_in_multiline' => [ - 'elements' => [ - 'arrays', - ], - ], - 'trim_array_spaces' => true, - 'unary_operator_spaces' => true, - 'types_spaces' => [ - 'space' => 'none', - ], - 'line_ending' => true, - 'whitespace_after_comma_in_array' => true, - 'no_alias_functions' => true, - 'no_unreachable_default_argument_value' => true, - 'psr_autoloading' => true, - 'self_accessor' => true, -]; - -$finder = PhpCsFixer\Finder::create() - ->in(__DIR__); - -return (new PhpCsFixer\Config()) - ->setRiskyAllowed(true) - ->setRules($rules) - ->setFinder($finder); diff --git a/composer.json b/composer.json index b5c2ddd8d..eb0ac3d9e 100644 --- a/composer.json +++ b/composer.json @@ -33,7 +33,8 @@ "require-dev": { "phpunit/phpunit": "^9.5.10", "orchestra/testbench": "^8.0", - "mockery/mockery": "^1.4.4" + "mockery/mockery": "^1.4.4", + "doctrine/coding-standard": "12.0.x-dev" }, "replace": { "jenssegers/mongodb": "self.version" @@ -56,5 +57,10 @@ ] } }, - "minimum-stability": "dev" + "minimum-stability": "dev", + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } } diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 000000000..36cc870e9 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,38 @@ + + + + + + + + + + + + src + tests + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Auth/DatabaseTokenRepository.php b/src/Auth/DatabaseTokenRepository.php index b2f43c748..83ce9bf6d 100644 --- a/src/Auth/DatabaseTokenRepository.php +++ b/src/Auth/DatabaseTokenRepository.php @@ -1,5 +1,7 @@ convertDateTime($createdAt); @@ -32,9 +33,7 @@ protected function tokenExpired($createdAt) return parent::tokenExpired($createdAt); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function tokenRecentlyCreated($createdAt) { $createdAt = $this->convertDateTime($createdAt); @@ -50,7 +49,7 @@ private function convertDateTime($createdAt) $date->setTimezone(new DateTimeZone(date_default_timezone_get())); $createdAt = $date->format('Y-m-d H:i:s'); } elseif (is_array($createdAt) && isset($createdAt['date'])) { - $date = new DateTime($createdAt['date'], new DateTimeZone(isset($createdAt['timezone']) ? $createdAt['timezone'] : 'UTC')); + $date = new DateTime($createdAt['date'], new DateTimeZone($createdAt['timezone'] ?? 'UTC')); $date->setTimezone(new DateTimeZone(date_default_timezone_get())); $createdAt = $date->format('Y-m-d H:i:s'); } diff --git a/src/Auth/PasswordBrokerManager.php b/src/Auth/PasswordBrokerManager.php index 0a2f615e5..157df3d97 100644 --- a/src/Auth/PasswordBrokerManager.php +++ b/src/Auth/PasswordBrokerManager.php @@ -1,14 +1,14 @@ app['config']['app.key'], $config['expire'], - $config['throttle'] ?? 0 + $config['throttle'] ?? 0, ); } } diff --git a/src/Auth/PasswordResetServiceProvider.php b/src/Auth/PasswordResetServiceProvider.php index fc06ab584..a8aa61da4 100644 --- a/src/Auth/PasswordResetServiceProvider.php +++ b/src/Auth/PasswordResetServiceProvider.php @@ -1,14 +1,14 @@ app->singleton('auth.password', function ($app) { diff --git a/src/Auth/User.php b/src/Auth/User.php index d7d3d7c93..d14aa4822 100644 --- a/src/Auth/User.php +++ b/src/Auth/User.php @@ -1,5 +1,7 @@ connection = $connection; @@ -38,13 +41,11 @@ public function __construct(Connection $connection, MongoCollection $collection) /** * Handle dynamic method calls. * - * @param string $method - * @param array $parameters * @return mixed */ public function __call(string $method, array $parameters) { - $start = microtime(true); + $start = microtime(true); $result = $this->collection->$method(...$parameters); // Once we have run the query we will calculate the time that it took to run and @@ -64,13 +65,13 @@ public function __call(string $method, array $parameters) // Convert the query parameters to a json string. foreach ($parameters as $parameter) { try { - $query[] = json_encode($parameter); - } catch (Exception $e) { + $query[] = json_encode($parameter, JSON_THROW_ON_ERROR); + } catch (Exception) { $query[] = '{...}'; } } - $queryString = $this->collection->getCollectionName().'.'.$method.'('.implode(',', $query).')'; + $queryString = $this->collection->getCollectionName() . '.' . $method . '(' . implode(',', $query) . ')'; $this->connection->logQuery($queryString, [], $time); diff --git a/src/Concerns/ManagesTransactions.php b/src/Concerns/ManagesTransactions.php index e4771343a..ac3c1c6f7 100644 --- a/src/Concerns/ManagesTransactions.php +++ b/src/Concerns/ManagesTransactions.php @@ -1,26 +1,25 @@ connection = $this->createConnection($dsn, $config, $options); - // Get default database name - $default_db = $this->getDefaultDatabaseName($dsn, $config); - // Select database - $this->db = $this->connection->selectDatabase($default_db); + $this->db = $this->connection->selectDatabase($this->getDefaultDatabaseName($dsn, $config)); $this->useDefaultPostProcessor(); @@ -68,7 +72,8 @@ public function __construct(array $config) /** * Begin a fluent query against a database collection. * - * @param string $collection + * @param string $collection + * * @return Query\Builder */ public function collection($collection) @@ -81,8 +86,9 @@ public function collection($collection) /** * Begin a fluent query against a database collection. * - * @param string $table - * @param string|null $as + * @param string $table + * @param string|null $as + * * @return Query\Builder */ public function table($table, $as = null) @@ -93,7 +99,8 @@ public function table($table, $as = null) /** * Get a MongoDB collection. * - * @param string $name + * @param string $name + * * @return Collection */ public function getCollection($name) @@ -101,9 +108,7 @@ public function getCollection($name) return new Collection($this, $this->db->selectCollection($name)); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getSchemaBuilder() { return new Schema\Builder($this); @@ -130,7 +135,7 @@ public function getMongoClient() } /** - * {@inheritdoc} + * {@inheritDoc} */ public function getDatabaseName() { @@ -140,20 +145,16 @@ public function getDatabaseName() /** * Get the name of the default database based on db config or try to detect it from dsn. * - * @param string $dsn - * @param array $config - * @return string - * * @throws InvalidArgumentException */ protected function getDefaultDatabaseName(string $dsn, array $config): string { if (empty($config['database'])) { - if (preg_match('/^mongodb(?:[+]srv)?:\\/\\/.+\\/([^?&]+)/s', $dsn, $matches)) { - $config['database'] = $matches[1]; - } else { + if (! preg_match('/^mongodb(?:[+]srv)?:\\/\\/.+\\/([^?&]+)/s', $dsn, $matches)) { throw new InvalidArgumentException('Database is not properly configured.'); } + + $config['database'] = $matches[1]; } return $config['database']; @@ -161,13 +162,8 @@ protected function getDefaultDatabaseName(string $dsn, array $config): string /** * Create a new MongoDB connection. - * - * @param string $dsn - * @param array $config - * @param array $options - * @return Client */ - protected function createConnection($dsn, array $config, array $options): Client + protected function createConnection(string $dsn, array $config, array $options): Client { // By default driver options is an empty array. $driverOptions = []; @@ -185,6 +181,7 @@ protected function createConnection($dsn, array $config, array $options): Client if (! isset($options['username']) && ! empty($config['username'])) { $options['username'] = $config['username']; } + if (! isset($options['password']) && ! empty($config['password'])) { $options['password'] = $config['password']; } @@ -192,9 +189,7 @@ protected function createConnection($dsn, array $config, array $options): Client return new Client($dsn, $options, $driverOptions); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function disconnect() { unset($this->connection); @@ -202,20 +197,14 @@ public function disconnect() /** * Determine if the given configuration array has a dsn string. - * - * @param array $config - * @return bool */ - protected function hasDsnString(array $config) + protected function hasDsnString(array $config): bool { - return isset($config['dsn']) && ! empty($config['dsn']); + return ! empty($config['dsn']); } /** * Get the DSN string form configuration. - * - * @param array $config - * @return string */ protected function getDsnString(array $config): string { @@ -224,9 +213,6 @@ protected function getDsnString(array $config): string /** * Get the DSN string for a host / port configuration. - * - * @param array $config - * @return string */ protected function getHostDsn(array $config): string { @@ -235,30 +221,27 @@ protected function getHostDsn(array $config): string foreach ($hosts as &$host) { // ipv6 - if (filter_var($host, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { - $host = '['.$host.']'; + if (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + $host = '[' . $host . ']'; if (! empty($config['port'])) { - $host = $host.':'.$config['port']; + $host .= ':' . $config['port']; } } else { // Check if we need to add a port to the host if (! str_contains($host, ':') && ! empty($config['port'])) { - $host = $host.':'.$config['port']; + $host .= ':' . $config['port']; } } } // Check if we want to authenticate against a specific database. - $auth_database = isset($config['options']) && ! empty($config['options']['database']) ? $config['options']['database'] : null; + $authDatabase = isset($config['options']) && ! empty($config['options']['database']) ? $config['options']['database'] : null; - return 'mongodb://'.implode(',', $hosts).($auth_database ? '/'.$auth_database : ''); + return 'mongodb://' . implode(',', $hosts) . ($authDatabase ? '/' . $authDatabase : ''); } /** * Create a DSN string from a configuration. - * - * @param array $config - * @return string */ protected function getDsn(array $config): string { @@ -267,41 +250,31 @@ protected function getDsn(array $config): string : $this->getHostDsn($config); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getElapsedTime($start) { return parent::getElapsedTime($start); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getDriverName() { return 'mongodb'; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function getDefaultPostProcessor() { return new Query\Processor(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function getDefaultQueryGrammar() { return new Query\Grammar(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function getDefaultSchemaGrammar() { return new Schema\Grammar(); @@ -309,10 +282,8 @@ protected function getDefaultSchemaGrammar() /** * Set database. - * - * @param \MongoDB\Database $db */ - public function setDatabase(\MongoDB\Database $db) + public function setDatabase(Database $db) { $this->db = $db; } @@ -320,8 +291,9 @@ public function setDatabase(\MongoDB\Database $db) /** * Dynamically pass methods to the connection. * - * @param string $method + * @param string $method * @param array $parameters + * * @return mixed */ public function __call($method, $parameters) @@ -339,7 +311,7 @@ private static function lookupVersion(): string if (class_exists(InstalledVersions::class)) { try { return self::$version = InstalledVersions::getPrettyVersion('mongodb/laravel-mongodb'); - } catch (Throwable $t) { + } catch (Throwable) { // Ignore exceptions and return unknown version } } diff --git a/src/Eloquent/Builder.php b/src/Eloquent/Builder.php index 7951a93a8..4d210c873 100644 --- a/src/Eloquent/Builder.php +++ b/src/Eloquent/Builder.php @@ -1,12 +1,21 @@ model->getParentRelation()) { + $relation = $this->model->getParentRelation(); + if ($relation) { $relation->performUpdate($this->model, $values); return 1; @@ -57,14 +65,13 @@ public function update(array $values, array $options = []) return $this->toBase()->update($this->addUpdatedAtColumn($values), $options); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function insert(array $values) { // Intercept operations on embedded models and delegate logic // to the parent relation instance. - if ($relation = $this->model->getParentRelation()) { + $relation = $this->model->getParentRelation(); + if ($relation) { $relation->performInsert($this->model, $values); return true; @@ -73,14 +80,13 @@ public function insert(array $values) return parent::insert($values); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function insertGetId(array $values, $sequence = null) { // Intercept operations on embedded models and delegate logic // to the parent relation instance. - if ($relation = $this->model->getParentRelation()) { + $relation = $this->model->getParentRelation(); + if ($relation) { $relation->performInsert($this->model, $values); return $this->model->getKey(); @@ -89,14 +95,13 @@ public function insertGetId(array $values, $sequence = null) return parent::insertGetId($values, $sequence); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function delete() { // Intercept operations on embedded models and delegate logic // to the parent relation instance. - if ($relation = $this->model->getParentRelation()) { + $relation = $this->model->getParentRelation(); + if ($relation) { $relation->performDelete($this->model); return $this->model->getKey(); @@ -105,14 +110,13 @@ public function delete() return parent::delete(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function increment($column, $amount = 1, array $extra = []) { // Intercept operations on embedded models and delegate logic // to the parent relation instance. - if ($relation = $this->model->getParentRelation()) { + $relation = $this->model->getParentRelation(); + if ($relation) { $value = $this->model->{$column}; // When doing increment and decrements, Eloquent will automatically @@ -122,22 +126,19 @@ public function increment($column, $amount = 1, array $extra = []) $this->model->syncOriginalAttribute($column); - $result = $this->model->update([$column => $value]); - - return $result; + return $this->model->update([$column => $value]); } return parent::increment($column, $amount, $extra); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function decrement($column, $amount = 1, array $extra = []) { // Intercept operations on embedded models and delegate logic // to the parent relation instance. - if ($relation = $this->model->getParentRelation()) { + $relation = $this->model->getParentRelation(); + if ($relation) { $value = $this->model->{$column}; // When doing increment and decrements, Eloquent will automatically @@ -153,9 +154,7 @@ public function decrement($column, $amount = 1, array $extra = []) return parent::decrement($column, $amount, $extra); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function raw($value = null) { // Get raw results from the query builder. @@ -166,13 +165,17 @@ public function raw($value = null) $results = iterator_to_array($results, false); return $this->model->hydrate($results); - } // Convert MongoDB BSONDocument to a single object. - elseif ($results instanceof BSONDocument) { + } + + // Convert MongoDB BSONDocument to a single object. + if ($results instanceof BSONDocument) { $results = $results->getArrayCopy(); return $this->model->newFromBuilder((array) $results); - } // The result is a single object. - elseif (is_array($results) && array_key_exists('_id', $results)) { + } + + // The result is a single object. + if (is_array($results) && array_key_exists('_id', $results)) { return $this->model->newFromBuilder((array) $results); } @@ -182,10 +185,9 @@ public function raw($value = null) /** * Add the "updated at" column to an array of values. * TODO Remove if https://github.com/laravel/framework/commit/6484744326531829341e1ff886cc9b628b20d73e - * wiil be reverted - * Issue in laravel frawework https://github.com/laravel/framework/issues/27791. + * will be reverted + * Issue in laravel/frawework https://github.com/laravel/framework/issues/27791. * - * @param array $values * @return array */ protected function addUpdatedAtColumn(array $values) @@ -197,23 +199,19 @@ protected function addUpdatedAtColumn(array $values) $column = $this->model->getUpdatedAtColumn(); $values = array_merge( [$column => $this->model->freshTimestampString()], - $values + $values, ); return $values; } - /** - * @return \Illuminate\Database\ConnectionInterface - */ + /** @return ConnectionInterface */ public function getConnection() { return $this->query->getConnection(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function ensureOrderForCursorPagination($shouldReverse = false) { if (empty($this->query->orders)) { diff --git a/src/Eloquent/Casts/BinaryUuid.php b/src/Eloquent/Casts/BinaryUuid.php index 7549680fe..c7832f125 100644 --- a/src/Eloquent/Casts/BinaryUuid.php +++ b/src/Eloquent/Casts/BinaryUuid.php @@ -1,13 +1,19 @@ newQuery(); - $instance = new $related; + $instance = new $related(); return new EmbedsMany($query, $this, $instance, $localKey, $foreignKey, $relation); } @@ -48,9 +56,10 @@ protected function embedsMany($related, $localKey = null, $foreignKey = null, $r * Define an embedded one-to-many relationship. * * @param class-string $related - * @param string|null $localKey - * @param string|null $foreignKey - * @param string|null $relation + * @param string|null $localKey + * @param string|null $foreignKey + * @param string|null $relation + * * @return EmbedsOne */ protected function embedsOne($related, $localKey = null, $foreignKey = null, $relation = null) @@ -72,7 +81,7 @@ protected function embedsOne($related, $localKey = null, $foreignKey = null, $re $query = $this->newQuery(); - $instance = new $related; + $instance = new $related(); return new EmbedsOne($query, $this, $instance, $localKey, $foreignKey, $relation); } diff --git a/src/Eloquent/HybridRelations.php b/src/Eloquent/HybridRelations.php index dc735b973..9d6aa90e1 100644 --- a/src/Eloquent/HybridRelations.php +++ b/src/Eloquent/HybridRelations.php @@ -1,5 +1,7 @@ getForeignKey(); - $instance = new $related; + $instance = new $related(); $localKey = $localKey ?: $this->getKeyName(); @@ -49,14 +58,15 @@ public function hasOne($related, $foreignKey = null, $localKey = null) /** * Define a polymorphic one-to-one relationship. * + * @see HasRelationships::morphOne() + * * @param class-string $related - * @param string $name - * @param string|null $type - * @param string|null $id - * @param string|null $localKey - * @return \Illuminate\Database\Eloquent\Relations\MorphOne + * @param string $name + * @param string|null $type + * @param string|null $id + * @param string|null $localKey * - * @see HasRelationships::morphOne() + * @return MorphOne */ public function morphOne($related, $name, $type = null, $id = null, $localKey = null) { @@ -65,7 +75,7 @@ public function morphOne($related, $name, $type = null, $id = null, $localKey = return parent::morphOne($related, $name, $type, $id, $localKey); } - $instance = new $related; + $instance = new $related(); [$type, $id] = $this->getMorphs($name, $type, $id); @@ -77,12 +87,13 @@ public function morphOne($related, $name, $type = null, $id = null, $localKey = /** * Define a one-to-many relationship. * + * @see HasRelationships::hasMany() + * * @param class-string $related - * @param string|null $foreignKey - * @param string|null $localKey - * @return \Illuminate\Database\Eloquent\Relations\HasMany + * @param string|null $foreignKey + * @param string|null $localKey * - * @see HasRelationships::hasMany() + * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function hasMany($related, $foreignKey = null, $localKey = null) { @@ -93,7 +104,7 @@ public function hasMany($related, $foreignKey = null, $localKey = null) $foreignKey = $foreignKey ?: $this->getForeignKey(); - $instance = new $related; + $instance = new $related(); $localKey = $localKey ?: $this->getKeyName(); @@ -103,14 +114,15 @@ public function hasMany($related, $foreignKey = null, $localKey = null) /** * Define a polymorphic one-to-many relationship. * + * @see HasRelationships::morphMany() + * * @param class-string $related - * @param string $name - * @param string|null $type - * @param string|null $id - * @param string|null $localKey - * @return \Illuminate\Database\Eloquent\Relations\MorphMany + * @param string $name + * @param string|null $type + * @param string|null $id + * @param string|null $localKey * - * @see HasRelationships::morphMany() + * @return \Illuminate\Database\Eloquent\Relations\MorphMany */ public function morphMany($related, $name, $type = null, $id = null, $localKey = null) { @@ -119,7 +131,7 @@ public function morphMany($related, $name, $type = null, $id = null, $localKey = return parent::morphMany($related, $name, $type, $id, $localKey); } - $instance = new $related; + $instance = new $related(); // Here we will gather up the morph type and ID for the relationship so that we // can properly query the intermediate table of a relation. Finally, we will @@ -136,13 +148,14 @@ public function morphMany($related, $name, $type = null, $id = null, $localKey = /** * Define an inverse one-to-one or many relationship. * + * @see HasRelationships::belongsTo() + * * @param class-string $related - * @param string|null $foreignKey - * @param string|null $ownerKey - * @param string|null $relation - * @return \Illuminate\Database\Eloquent\Relations\BelongsTo + * @param string|null $foreignKey + * @param string|null $ownerKey + * @param string|null $relation * - * @see HasRelationships::belongsTo() + * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null) { @@ -162,10 +175,10 @@ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relat // foreign key name by using the name of the relationship function, which // when combined with an "_id" should conventionally match the columns. if ($foreignKey === null) { - $foreignKey = Str::snake($relation).'_id'; + $foreignKey = Str::snake($relation) . '_id'; } - $instance = new $related; + $instance = new $related(); // Once we have the foreign key names, we'll just create a new Eloquent query // for the related models and returns the relationship instance which will @@ -180,13 +193,14 @@ public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relat /** * Define a polymorphic, inverse one-to-one or many relationship. * - * @param string $name + * @see HasRelationships::morphTo() + * + * @param string $name * @param string|null $type * @param string|null $id * @param string|null $ownerKey - * @return \Illuminate\Database\Eloquent\Relations\MorphTo * - * @see HasRelationships::morphTo() + * @return \Illuminate\Database\Eloquent\Relations\MorphTo */ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null) { @@ -202,9 +216,15 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null // If the type value is null it is probably safe to assume we're eager loading // the relationship. When that is the case we will pass in a dummy query as // there are multiple types in the morph and we can't use single queries. - if (($class = $this->$type) === null) { + $class = $this->$type; + if ($class === null) { return new MorphTo( - $this->newQuery(), $this, $id, $ownerKey, $type, $name + $this->newQuery(), + $this, + $id, + $ownerKey, + $type, + $name, ); } @@ -213,28 +233,34 @@ public function morphTo($name = null, $type = null, $id = null, $ownerKey = null // we will pass in the appropriate values so that it behaves as expected. $class = $this->getActualClassNameForMorph($class); - $instance = new $class; + $instance = new $class(); - $ownerKey = $ownerKey ?? $instance->getKeyName(); + $ownerKey ??= $instance->getKeyName(); return new MorphTo( - $instance->newQuery(), $this, $id, $ownerKey, $type, $name + $instance->newQuery(), + $this, + $id, + $ownerKey, + $type, + $name, ); } /** * Define a many-to-many relationship. * + * @see HasRelationships::belongsToMany() + * * @param class-string $related - * @param string|null $collection - * @param string|null $foreignPivotKey - * @param string|null $relatedPivotKey - * @param string|null $parentKey - * @param string|null $relatedKey - * @param string|null $relation - * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany + * @param string|null $collection + * @param string|null $foreignPivotKey + * @param string|null $relatedPivotKey + * @param string|null $parentKey + * @param string|null $relatedKey + * @param string|null $relation * - * @see HasRelationships::belongsToMany() + * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function belongsToMany( $related, @@ -243,7 +269,7 @@ public function belongsToMany( $relatedPivotKey = null, $parentKey = null, $relatedKey = null, - $relation = null + $relation = null, ) { // If no relationship name was passed, we will pull backtraces to get the // name of the calling function. We will use that function name as the @@ -261,18 +287,18 @@ public function belongsToMany( $relatedPivotKey, $parentKey, $relatedKey, - $relation + $relation, ); } // First, we'll need to determine the foreign key and "other key" for the // relationship. Once we have determined the keys we'll make the query // instances as well as the relationship instances we need for this. - $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey().'s'; + $foreignPivotKey = $foreignPivotKey ?: $this->getForeignKey() . 's'; - $instance = new $related; + $instance = new $related(); - $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey().'s'; + $relatedPivotKey = $relatedPivotKey ?: $instance->getForeignKey() . 's'; // If no table name was provided, we can guess it by concatenating the two // models using underscores in alphabetical order. The two model names @@ -294,7 +320,7 @@ public function belongsToMany( $relatedPivotKey, $parentKey ?: $this->getKeyName(), $relatedKey ?: $instance->getKeyName(), - $relation + $relation, ); } @@ -312,9 +338,7 @@ protected function guessBelongsToManyRelation() return parent::guessBelongsToManyRelation(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function newEloquentBuilder($query) { if ($this instanceof MongoDBModel) { diff --git a/src/Eloquent/MassPrunable.php b/src/Eloquent/MassPrunable.php index df8839d5d..98e947842 100644 --- a/src/Eloquent/MassPrunable.php +++ b/src/Eloquent/MassPrunable.php @@ -1,10 +1,16 @@ prunable(); - $total = in_array(SoftDeletes::class, class_uses_recursive(get_class($this))) + $total = in_array(SoftDeletes::class, class_uses_recursive(static::class)) ? $query->forceDelete() : $query->delete(); diff --git a/src/Eloquent/Model.php b/src/Eloquent/Model.php index 45f583501..05a20bb31 100644 --- a/src/Eloquent/Model.php +++ b/src/Eloquent/Model.php @@ -1,10 +1,10 @@ getData(); } return $value; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getQualifiedKeyName() { return $this->getKeyName(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function fromDateTime($value) { // If the value is already a UTCDateTime instance, we don't need to parse it. @@ -109,18 +127,16 @@ public function fromDateTime($value) return new UTCDateTime($value); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function asDateTime($value) { // Convert UTCDateTime instances. if ($value instanceof UTCDateTime) { $date = $value->toDateTime(); - $seconds = $date->format('U'); - $milliseconds = abs($date->format('v')); - $timestampMs = sprintf('%d%03d', $seconds, $milliseconds); + $seconds = $date->format('U'); + $milliseconds = abs((int) $date->format('v')); + $timestampMs = sprintf('%d%03d', $seconds, $milliseconds); return Date::createFromTimestampMs($timestampMs); } @@ -128,33 +144,25 @@ protected function asDateTime($value) return parent::asDateTime($value); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getDateFormat() { return $this->dateFormat ?: 'Y-m-d H:i:s'; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function freshTimestamp() { return new UTCDateTime(Date::now()); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getTable() { return $this->collection ?: parent::getTable(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getAttribute($key) { if (! $key) { @@ -183,9 +191,7 @@ public function getAttribute($key) return parent::getAttribute($key); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function getAttributeFromArray($key) { // Support keys in dot notation. @@ -196,20 +202,21 @@ protected function getAttributeFromArray($key) return parent::getAttributeFromArray($key); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function setAttribute($key, $value) { // Convert _id to ObjectID. - if ($key == '_id' && is_string($value)) { + if ($key === '_id' && is_string($value)) { $builder = $this->newBaseQueryBuilder(); $value = $builder->convertKey($value); - } // Support keys in dot notation. - elseif (str_contains($key, '.')) { + } + + // Support keys in dot notation. + if (str_contains($key, '.')) { // Store to a temporary key, then move data to the actual key $uniqueKey = uniqid($key); + parent::setAttribute($uniqueKey, $value); Arr::set($this->attributes, $key, $this->attributes[$uniqueKey] ?? null); @@ -224,9 +231,7 @@ public function setAttribute($key, $value) return parent::setAttribute($key, $value); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function attributesToArray() { $attributes = parent::attributesToArray(); @@ -246,32 +251,26 @@ public function attributesToArray() return $attributes; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getCasts() { return $this->casts; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getDirty() { $dirty = parent::getDirty(); // The specified value in the $unset expression does not impact the operation. - if (! empty($this->unset)) { + if ($this->unset !== []) { $dirty['$unset'] = $this->unset; } return $dirty; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function originalIsEquivalent($key) { if (! array_key_exists($key, $this->original)) { @@ -284,20 +283,22 @@ public function originalIsEquivalent($key) } $attribute = Arr::get($this->attributes, $key); - $original = Arr::get($this->original, $key); + $original = Arr::get($this->original, $key); if ($attribute === $original) { return true; } - if (null === $attribute) { + if ($attribute === null) { return false; } if ($this->isDateAttribute($key)) { $attribute = $attribute instanceof UTCDateTime ? $this->asDateTime($attribute) : $attribute; - $original = $original instanceof UTCDateTime ? $this->asDateTime($original) : $original; + $original = $original instanceof UTCDateTime ? $this->asDateTime($original) : $original; + // Comparison on DateTimeInterface values + // phpcs:disable SlevomatCodingStandard.Operators.DisallowEqualOperators.DisallowedEqualOperator return $attribute == $original; } @@ -310,9 +311,7 @@ public function originalIsEquivalent($key) && strcmp((string) $attribute, (string) $original) === 0; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function offsetUnset($offset): void { if (str_contains($offset, '.')) { @@ -327,9 +326,7 @@ public function offsetUnset($offset): void } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function offsetSet($offset, $value): void { parent::offsetSet($offset, $value); @@ -341,10 +338,11 @@ public function offsetSet($offset, $value): void /** * Remove one or more fields. * - * @param string|string[] $columns - * @return void - * * @deprecated Use unset() instead. + * + * @param string|string[] $columns + * + * @return void */ public function drop($columns) { @@ -354,7 +352,8 @@ public function drop($columns) /** * Remove one or more fields. * - * @param string|string[] $columns + * @param string|string[] $columns + * * @return void */ public function unset($columns) @@ -367,12 +366,11 @@ public function unset($columns) } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function push() { - if ($parameters = func_get_args()) { + $parameters = func_get_args(); + if ($parameters) { $unique = false; if (count($parameters) === 3) { @@ -397,8 +395,9 @@ public function push() /** * Remove one or more values from an array. * - * @param string $column + * @param string $column * @param mixed $values + * * @return mixed */ public function pull($column, $values) @@ -416,9 +415,8 @@ public function pull($column, $values) /** * Append one or more values to the underlying attribute value and sync with original. * - * @param string $column - * @param array $values - * @param bool $unique + * @param string $column + * @param bool $unique */ protected function pushAttributeValues($column, array $values, $unique = false) { @@ -441,8 +439,7 @@ protected function pushAttributeValues($column, array $values, $unique = false) /** * Remove one or more values to the underlying attribute value and sync with original. * - * @param string $column - * @param array $values + * @param string $column */ protected function pullAttributeValues($column, array $values) { @@ -463,18 +460,14 @@ protected function pullAttributeValues($column, array $values) $this->syncOriginalAttribute($column); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getForeignKey() { - return Str::snake(class_basename($this)).'_'.ltrim($this->primaryKey, '_'); + return Str::snake(class_basename($this)) . '_' . ltrim($this->primaryKey, '_'); } /** * Set the parent relation. - * - * @param \Illuminate\Database\Eloquent\Relations\Relation $relation */ public function setParentRelation(Relation $relation) { @@ -484,24 +477,20 @@ public function setParentRelation(Relation $relation) /** * Get the parent relation. * - * @return \Illuminate\Database\Eloquent\Relations\Relation + * @return Relation */ public function getParentRelation() { return $this->parentRelation; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function newEloquentBuilder($query) { return new Builder($query); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function newBaseQueryBuilder() { $connection = $this->getConnection(); @@ -509,9 +498,7 @@ protected function newBaseQueryBuilder() return new QueryBuilder($connection, $connection->getQueryGrammar(), $connection->getPostProcessor()); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function removeTableFromKey($key) { return $key; @@ -533,13 +520,13 @@ public function getQueueableRelations() if ($relation instanceof QueueableCollection) { foreach ($relation->getQueueableRelations() as $collectionValue) { - $relations[] = $key.'.'.$collectionValue; + $relations[] = $key . '.' . $collectionValue; } } if ($relation instanceof QueueableEntity) { foreach ($relation->getQueueableRelations() as $entityKey => $entityValue) { - $relations[] = $key.'.'.$entityValue; + $relations[] = $key . '.' . $entityValue; } } } @@ -556,7 +543,8 @@ protected function getRelationsWithoutParent() { $relations = $this->getRelations(); - if ($parentRelation = $this->getParentRelation()) { + $parentRelation = $this->getParentRelation(); + if ($parentRelation) { unset($relations[$parentRelation->getQualifiedForeignKeyName()]); } @@ -567,7 +555,8 @@ protected function getRelationsWithoutParent() * Checks if column exists on a table. As this is a document model, just return true. This also * prevents calls to non-existent function Grammar::compileColumnListing(). * - * @param string $key + * @param string $key + * * @return bool */ protected function isGuardableColumn($key) @@ -575,9 +564,7 @@ protected function isGuardableColumn($key) return true; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function addCastAttributesToArray(array $attributes, array $mutatedAttributes) { foreach ($this->getCasts() as $key => $castType) { @@ -591,7 +578,8 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt // then we will serialize the date for the array. This will convert the dates // to strings based on the date format specified for these Eloquent models. $castValue = $this->castAttribute( - $key, $originalValue + $key, + $originalValue, ); // If the attribute cast was a date or a datetime, we will serialize the date as @@ -601,13 +589,11 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt $castValue = $this->serializeDate($castValue); } - if ($castValue !== null && ($this->isCustomDateTimeCast($castType) || - $this->isImmutableCustomDateTimeCast($castType))) { + if ($castValue !== null && ($this->isCustomDateTimeCast($castType) || $this->isImmutableCustomDateTimeCast($castType))) { $castValue = $castValue->format(explode(':', $castType, 2)[1]); } - if ($castValue instanceof DateTimeInterface && - $this->isClassCastable($key)) { + if ($castValue instanceof DateTimeInterface && $this->isClassCastable($key)) { $castValue = $this->serializeDate($castValue); } diff --git a/src/Eloquent/SoftDeletes.php b/src/Eloquent/SoftDeletes.php index 8263e4c53..135c55dcf 100644 --- a/src/Eloquent/SoftDeletes.php +++ b/src/Eloquent/SoftDeletes.php @@ -1,14 +1,14 @@ getDeletedAtColumn(); diff --git a/src/Helpers/EloquentBuilder.php b/src/Helpers/EloquentBuilder.php index e408b78f8..3140330e5 100644 --- a/src/Helpers/EloquentBuilder.php +++ b/src/Helpers/EloquentBuilder.php @@ -1,5 +1,7 @@ =', $count = 1, $boolean = 'and', Closure $callback = null) + public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', ?Closure $callback = null) { if (is_string($relation)) { if (strpos($relation, '.') !== false) { @@ -48,7 +63,8 @@ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', C : 'getRelationExistenceCountQuery'; $hasQuery = $relation->{$method}( - $relation->getRelated()->newQuery(), $this + $relation->getRelated()->newQuery(), + $this ); // Next we will call any given callback as an "anonymous" scope so they can get the @@ -59,14 +75,15 @@ public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', C } return $this->addHasWhere( - $hasQuery, $relation, $operator, $count, $boolean + $hasQuery, + $relation, + $operator, + $count, + $boolean, ); } - /** - * @param Relation $relation - * @return bool - */ + /** @return bool */ protected function isAcrossConnections(Relation $relation) { return $relation->getParent()->getConnectionName() !== $relation->getRelated()->getConnectionName(); @@ -75,15 +92,15 @@ protected function isAcrossConnections(Relation $relation) /** * Compare across databases. * - * @param Relation $relation * @param string $operator - * @param int $count + * @param int $count * @param string $boolean - * @param Closure|null $callback + * * @return mixed + * * @throws Exception */ - public function addHybridHas(Relation $relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) + public function addHybridHas(Relation $relation, $operator = '>=', $count = 1, $boolean = 'and', ?Closure $callback = null) { $hasQuery = $relation->getQuery(); if ($callback) { @@ -93,7 +110,7 @@ public function addHybridHas(Relation $relation, $operator = '>=', $count = 1, $ // If the operator is <, <= or !=, we will use whereNotIn. $not = in_array($operator, ['<', '<=', '!=']); // If we are comparing to 0, we need an additional $not flip. - if ($count == 0) { + if ($count === 0) { $not = ! $not; } @@ -104,10 +121,7 @@ public function addHybridHas(Relation $relation, $operator = '>=', $count = 1, $ return $this->whereIn($this->getRelatedConstraintKey($relation), $relatedIds, $boolean, $not); } - /** - * @param Relation $relation - * @return string - */ + /** @return string */ protected function getHasCompareKey(Relation $relation) { if (method_exists($relation, 'getHasCompareKey')) { @@ -118,9 +132,10 @@ protected function getHasCompareKey(Relation $relation) } /** - * @param $relations - * @param $operator - * @param $count + * @param Collection $relations + * @param string $operator + * @param int $count + * * @return array */ protected function getConstrainedRelatedIds($relations, $operator, $count) @@ -131,9 +146,10 @@ protected function getConstrainedRelatedIds($relations, $operator, $count) // Remove unwanted related objects based on the operator and count. $relationCount = array_filter($relationCount, function ($counted) use ($count, $operator) { // If we are comparing to 0, we always need all results. - if ($count == 0) { + if ($count === 0) { return true; } + switch ($operator) { case '>=': case '<': @@ -143,7 +159,7 @@ protected function getConstrainedRelatedIds($relations, $operator, $count) return $counted > $count; case '=': case '!=': - return $counted == $count; + return $counted === $count; } }); @@ -154,8 +170,8 @@ protected function getConstrainedRelatedIds($relations, $operator, $count) /** * Returns key we are constraining this parent model's query with. * - * @param Relation $relation * @return string + * * @throws Exception */ protected function getRelatedConstraintKey(Relation $relation) @@ -172,6 +188,6 @@ protected function getRelatedConstraintKey(Relation $relation) return $this->model->getKeyName(); } - throw new Exception(class_basename($relation).' is not supported for hybrid query constraints.'); + throw new Exception(class_basename($relation) . ' is not supported for hybrid query constraints.'); } } diff --git a/src/MongodbQueueServiceProvider.php b/src/MongodbQueueServiceProvider.php index 7ec851d09..7b2066ecb 100644 --- a/src/MongodbQueueServiceProvider.php +++ b/src/MongodbQueueServiceProvider.php @@ -1,11 +1,15 @@ app->singleton('queue.failer', function ($app) { $config = $app['config']['queue.failed']; - if (array_key_exists('driver', $config) && - (is_null($config['driver']) || $config['driver'] === 'null')) { - return new NullFailedJobProvider; + if (array_key_exists('driver', $config) && ($config['driver'] === null || $config['driver'] === 'null')) { + return new NullFailedJobProvider(); } if (isset($config['driver']) && $config['driver'] === 'mongodb') { return $this->mongoFailedJobProvider($config); - } elseif (isset($config['driver']) && $config['driver'] === 'dynamodb') { + } + + if (isset($config['driver']) && $config['driver'] === 'dynamodb') { return $this->dynamoFailedJobProvider($config); - } elseif (isset($config['driver']) && $config['driver'] === 'database-uuids') { + } + + if (isset($config['driver']) && $config['driver'] === 'database-uuids') { return $this->databaseUuidFailedJobProvider($config); - } elseif (isset($config['table'])) { + } + + if (isset($config['table'])) { return $this->databaseFailedJobProvider($config); - } else { - return new NullFailedJobProvider; } + + return new NullFailedJobProvider(); }); } diff --git a/src/MongodbServiceProvider.php b/src/MongodbServiceProvider.php index ece75d2b7..a9ebc1d17 100644 --- a/src/MongodbServiceProvider.php +++ b/src/MongodbServiceProvider.php @@ -1,5 +1,7 @@ where('_id', '=', $this->convertKey($id))->first($columns); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function value($column) { $result = (array) $this->first([$column]); @@ -192,23 +230,20 @@ public function value($column) return Arr::get($result, $column); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function get($columns = []) { return $this->getFresh($columns); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function cursor($columns = []) { $result = $this->getFresh($columns, true); if ($result instanceof LazyCollection) { return $result; } + throw new RuntimeException('Query not compatible with cursor'); } @@ -232,24 +267,24 @@ public function toMql(): array // Use MongoDB's aggregation framework when using grouping or aggregation functions. if ($this->groups || $this->aggregate) { - $group = []; + $group = []; $unwinds = []; // Add grouping columns to the $group part of the aggregation pipeline. if ($this->groups) { foreach ($this->groups as $column) { - $group['_id'][$column] = '$'.$column; + $group['_id'][$column] = '$' . $column; // When grouping, also add the $last operator to each grouped field, // this mimics MySQL's behaviour a bit. - $group[$column] = ['$last' => '$'.$column]; + $group[$column] = ['$last' => '$' . $column]; } // Do the same for other columns that are selected. foreach ($columns as $column) { $key = str_replace('.', '_', $column); - $group[$key] = ['$last' => '$'.$column]; + $group[$key] = ['$last' => '$' . $column]; } } @@ -261,22 +296,25 @@ public function toMql(): array foreach ($this->aggregate['columns'] as $column) { // Add unwind if a subdocument array should be aggregated // column: subarray.price => {$unwind: '$subarray'} - if (count($splitColumns = explode('.*.', $column)) == 2) { + $splitColumns = explode('.*.', $column); + if (count($splitColumns) === 2) { $unwinds[] = $splitColumns[0]; - $column = implode('.', $splitColumns); + $column = implode('.', $splitColumns); } $aggregations = blank($this->aggregate['columns']) ? [] : $this->aggregate['columns']; - if (in_array('*', $aggregations) && $function == 'count') { + if (in_array('*', $aggregations) && $function === 'count') { $options = $this->inheritConnectionOptions(); return ['countDocuments' => [$wheres, $options]]; - } elseif ($function == 'count') { + } + + if ($function === 'count') { // Translate count into sum. $group['aggregate'] = ['$sum' => 1]; } else { - $group['aggregate'] = ['$'.$function => '$'.$column]; + $group['aggregate'] = ['$' . $function => '$' . $column]; } } } @@ -294,7 +332,7 @@ public function toMql(): array // apply unwinds for subdocument array aggregation foreach ($unwinds as $unwind) { - $pipeline[] = ['$unwind' => '$'.$unwind]; + $pipeline[] = ['$unwind' => '$' . $unwind]; } if ($group) { @@ -305,12 +343,15 @@ public function toMql(): array if ($this->orders) { $pipeline[] = ['$sort' => $this->orders]; } + if ($this->offset) { $pipeline[] = ['$skip' => $this->offset]; } + if ($this->limit) { $pipeline[] = ['$limit' => $this->limit]; } + if ($this->projections) { $pipeline[] = ['$project' => $this->projections]; } @@ -327,64 +368,73 @@ public function toMql(): array $options = $this->inheritConnectionOptions($options); return ['aggregate' => [$pipeline, $options]]; - } // Distinct query - elseif ($this->distinct) { + } + + // Distinct query + if ($this->distinct) { // Return distinct results directly - $column = isset($columns[0]) ? $columns[0] : '_id'; + $column = $columns[0] ?? '_id'; $options = $this->inheritConnectionOptions(); return ['distinct' => [$column, $wheres, $options]]; - } // Normal query - else { - // Convert select columns to simple projections. - $projection = array_fill_keys($columns, true); + } - // Add custom projections. - if ($this->projections) { - $projection = array_merge($projection, $this->projections); - } - $options = []; + // Normal query + // Convert select columns to simple projections. + $projection = array_fill_keys($columns, true); - // Apply order, offset, limit and projection - if ($this->timeout) { - $options['maxTimeMS'] = $this->timeout * 1000; - } - if ($this->orders) { - $options['sort'] = $this->orders; - } - if ($this->offset) { - $options['skip'] = $this->offset; - } - if ($this->limit) { - $options['limit'] = $this->limit; - } - if ($this->hint) { - $options['hint'] = $this->hint; - } - if ($projection) { - $options['projection'] = $projection; - } + // Add custom projections. + if ($this->projections) { + $projection = array_merge($projection, $this->projections); + } - // Fix for legacy support, converts the results to arrays instead of objects. - $options['typeMap'] = ['root' => 'array', 'document' => 'array']; + $options = []; - // Add custom query options - if (count($this->options)) { - $options = array_merge($options, $this->options); - } + // Apply order, offset, limit and projection + if ($this->timeout) { + $options['maxTimeMS'] = $this->timeout * 1000; + } - $options = $this->inheritConnectionOptions($options); + if ($this->orders) { + $options['sort'] = $this->orders; + } + + if ($this->offset) { + $options['skip'] = $this->offset; + } + + if ($this->limit) { + $options['limit'] = $this->limit; + } + + if ($this->hint) { + $options['hint'] = $this->hint; + } + + if ($projection) { + $options['projection'] = $projection; + } + + // Fix for legacy support, converts the results to arrays instead of objects. + $options['typeMap'] = ['root' => 'array', 'document' => 'array']; - return ['find' => [$wheres, $options]]; + // Add custom query options + if (count($this->options)) { + $options = array_merge($options, $this->options); } + + $options = $this->inheritConnectionOptions($options); + + return ['find' => [$wheres, $options]]; } /** * Execute the query as a fresh "select" statement. * - * @param array $columns + * @param array $columns * @param bool $returnLazy + * * @return array|static[]|Collection|LazyCollection */ public function getFresh($columns = [], $returnLazy = false) @@ -456,12 +506,13 @@ public function generateCacheKey() return md5(serialize(array_values($key))); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function aggregate($function, $columns = []) { - $this->aggregate = compact('function', 'columns'); + $this->aggregate = [ + 'function' => $function, + 'columns' => $columns, + ]; $previousColumns = $this->columns; @@ -477,8 +528,8 @@ public function aggregate($function, $columns = []) // Once we have executed the query, we will reset the aggregate property so // that more select queries can be executed against the database without // the aggregate value getting in the way when the grammar builds it. - $this->aggregate = null; - $this->columns = $previousColumns; + $this->aggregate = null; + $this->columns = $previousColumns; $this->bindings['select'] = $previousSelectBindings; if (isset($results[0])) { @@ -488,17 +539,13 @@ public function aggregate($function, $columns = []) } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function exists() { return $this->first() !== null; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function distinct($column = false) { $this->distinct = true; @@ -511,8 +558,9 @@ public function distinct($column = false) } /** - * @inheritdoc * @param int|string|array $direction + * + * @inheritdoc */ public function orderBy($column, $direction = 'asc') { @@ -520,22 +568,24 @@ public function orderBy($column, $direction = 'asc') $direction = match ($direction) { 'asc', 'ASC' => 1, 'desc', 'DESC' => -1, - default => throw new \InvalidArgumentException('Order direction must be "asc" or "desc".'), + default => throw new InvalidArgumentException('Order direction must be "asc" or "desc".'), }; } - if ($column == 'natural') { + $column = (string) $column; + if ($column === 'natural') { $this->orders['$natural'] = $direction; } else { - $this->orders[(string) $column] = $direction; + $this->orders[$column] = $direction; } return $this; } /** - * @inheritdoc * @param list{mixed, mixed}|CarbonPeriod $values + * + * @inheritdoc */ public function whereBetween($column, iterable $values, $boolean = 'and', $not = false) { @@ -546,17 +596,21 @@ public function whereBetween($column, iterable $values, $boolean = 'and', $not = } if (is_array($values) && (! array_is_list($values) || count($values) !== 2)) { - throw new \InvalidArgumentException('Between $values must be a list with exactly two elements: [min, max]'); + throw new InvalidArgumentException('Between $values must be a list with exactly two elements: [min, max]'); } - $this->wheres[] = compact('column', 'type', 'boolean', 'values', 'not'); + $this->wheres[] = [ + 'column' => $column, + 'type' => $type, + 'boolean' => $boolean, + 'values' => $values, + 'not' => $not, + ]; return $this; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function insert(array $values) { // Since every insert gets treated like a batch insert, we will have to detect @@ -580,39 +634,38 @@ public function insert(array $values) $result = $this->collection->insertMany($values, $options); - return 1 == (int) $result->isAcknowledged(); + return $result->isAcknowledged(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function insertGetId(array $values, $sequence = null) { $options = $this->inheritConnectionOptions(); $result = $this->collection->insertOne($values, $options); - if (1 == (int) $result->isAcknowledged()) { - if ($sequence === null) { - $sequence = '_id'; - } + if (! $result->isAcknowledged()) { + return null; + } - // Return id - return $sequence == '_id' ? $result->getInsertedId() : $values[$sequence]; + if ($sequence === null || $sequence === '_id') { + return $result->getInsertedId(); } + + return $values[$sequence]; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function update(array $values, array $options = []) { // Use $set as default operator for field names that are not in an operator foreach ($values as $key => $value) { - if (! str_starts_with($key, '$')) { - $values['$set'][$key] = $value; - unset($values[$key]); + if (str_starts_with($key, '$')) { + continue; } + + $values['$set'][$key] = $value; + unset($values[$key]); } $options = $this->inheritConnectionOptions($options); @@ -620,9 +673,7 @@ public function update(array $values, array $options = []) return $this->performUpdate($values, $options); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function increment($column, $amount = 1, array $extra = [], array $options = []) { $query = ['$inc' => [(string) $column => $amount]]; @@ -643,39 +694,31 @@ public function increment($column, $amount = 1, array $extra = [], array $option return $this->performUpdate($query, $options); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function decrement($column, $amount = 1, array $extra = [], array $options = []) { return $this->increment($column, -1 * $amount, $extra, $options); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function chunkById($count, callable $callback, $column = '_id', $alias = null) { return parent::chunkById($count, $callback, $column, $alias); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function forPageAfterId($perPage = 15, $lastId = 0, $column = '_id') { return parent::forPageAfterId($perPage, $lastId, $column); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function pluck($column, $key = null) { $results = $this->get($key === null ? [$column] : [$column, $key]); // Convert ObjectID's to strings - if ($key == '_id') { + if (((string) $key) === '_id') { $results = $results->map(function ($item) { $item['_id'] = (string) $item['_id']; @@ -688,9 +731,7 @@ public function pluck($column, $key = null) return new Collection($p); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function delete($id = null) { // If an ID is passed to the method, we will set the where clause to check @@ -700,28 +741,27 @@ public function delete($id = null) $this->where('_id', '=', $id); } - $wheres = $this->compileWheres(); + $wheres = $this->compileWheres(); $options = $this->inheritConnectionOptions(); if (is_int($this->limit)) { if ($this->limit !== 1) { - throw new \LogicException(sprintf('Delete limit can be 1 or null (unlimited). Got %d', $this->limit)); + throw new LogicException(sprintf('Delete limit can be 1 or null (unlimited). Got %d', $this->limit)); } + $result = $this->collection->deleteOne($wheres, $options); } else { $result = $this->collection->deleteMany($wheres, $options); } - if (1 == (int) $result->isAcknowledged()) { + if ($result->isAcknowledged()) { return $result->getDeletedCount(); } return 0; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function from($collection, $as = null) { if ($collection) { @@ -731,34 +771,30 @@ public function from($collection, $as = null) return parent::from($collection); } - /** - * @inheritdoc - */ public function truncate(): bool { $options = $this->inheritConnectionOptions(); - $result = $this->collection->deleteMany([], $options); + $result = $this->collection->deleteMany([], $options); - return 1 === (int) $result->isAcknowledged(); + return $result->isAcknowledged(); } /** * Get an array with the values of a given column. * - * @param string $column - * @param string $key - * @return array + * @deprecated Use pluck instead. + * + * @param string $column + * @param string $key * - * @deprecated + * @return Collection */ public function lists($column, $key = null) { return $this->pluck($column, $key); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function raw($value = null) { // Execute the closure on the mongodb collection @@ -778,9 +814,10 @@ public function raw($value = null) /** * Append one or more values to an array. * - * @param string|array $column - * @param mixed $value - * @param bool $unique + * @param string|array $column + * @param mixed $value + * @param bool $unique + * * @return int */ public function push($column, $value = null, $unique = false) @@ -793,8 +830,9 @@ public function push($column, $value = null, $unique = false) if (is_array($column)) { if ($value !== null) { - throw new \InvalidArgumentException(sprintf('2nd argument of %s() must be "null" when 1st argument is an array. Got "%s" instead.', __METHOD__, get_debug_type($value))); + throw new InvalidArgumentException(sprintf('2nd argument of %s() must be "null" when 1st argument is an array. Got "%s" instead.', __METHOD__, get_debug_type($value))); } + $query = [$operator => $column]; } elseif ($batch) { $query = [$operator => [(string) $column => ['$each' => $value]]]; @@ -808,8 +846,9 @@ public function push($column, $value = null, $unique = false) /** * Remove one or more values from an array. * - * @param string|array $column - * @param mixed $value + * @param string|array $column + * @param mixed $value + * * @return int */ public function pull($column, $value = null) @@ -832,7 +871,8 @@ public function pull($column, $value = null) /** * Remove one or more fields. * - * @param string|string[] $columns + * @param string|string[] $columns + * * @return int */ public function drop($columns) @@ -853,9 +893,9 @@ public function drop($columns) } /** - * @inheritdoc - * * @return static + * + * @inheritdoc */ public function newQuery() { @@ -865,8 +905,8 @@ public function newQuery() /** * Perform an update query. * - * @param array $query - * @param array $options + * @param array $query + * * @return int */ protected function performUpdate($query, array $options = []) @@ -880,7 +920,7 @@ protected function performUpdate($query, array $options = []) $wheres = $this->compileWheres(); $result = $this->collection->updateMany($wheres, $query, $options); - if (1 == (int) $result->isAcknowledged()) { + if ($result->isAcknowledged()) { return $result->getModifiedCount() ? $result->getModifiedCount() : $result->getUpsertedCount(); } @@ -890,7 +930,8 @@ protected function performUpdate($query, array $options = []) /** * Convert a key to ObjectID if needed. * - * @param mixed $id + * @param mixed $id + * * @return mixed */ public function convertKey($id) @@ -906,9 +947,7 @@ public function convertKey($id) return $id; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function where($column, $operator = null, $value = null, $boolean = 'and') { $params = func_get_args(); @@ -922,8 +961,8 @@ public function where($column, $operator = null, $value = null, $boolean = 'and' } } - if (func_num_args() == 1 && is_string($column)) { - throw new \ArgumentCountError(sprintf('Too few arguments to function %s("%s"), 1 passed and at least 2 expected when the 1st is a string.', __METHOD__, $column)); + if (func_num_args() === 1 && is_string($column)) { + throw new ArgumentCountError(sprintf('Too few arguments to function %s("%s"), 1 passed and at least 2 expected when the 1st is a string.', __METHOD__, $column)); } return parent::where(...$params); @@ -953,15 +992,20 @@ protected function compileWheres(): array } } + // Convert column name to string to use as array key + if (isset($where['column']) && $where['column'] instanceof Stringable) { + $where['column'] = (string) $where['column']; + } + // Convert id's. - if (isset($where['column']) && ($where['column'] == '_id' || str_ends_with($where['column'], '._id'))) { - // Multiple values. + if (isset($where['column']) && ($where['column'] === '_id' || str_ends_with($where['column'], '._id'))) { if (isset($where['values'])) { + // Multiple values. foreach ($where['values'] as &$value) { $value = $this->convertKey($value); } - } // Single value. - elseif (isset($where['value'])) { + } elseif (isset($where['value'])) { + // Single value. $where['value'] = $this->convertKey($where['value']); } } @@ -997,21 +1041,16 @@ protected function compileWheres(): array // In a sequence of "where" clauses, the logical operator of the // first "where" is determined by the 2nd "where". // $where['boolean'] = "and", "or", "and not" or "or not" - if ($i == 0 && count($wheres) > 1 + if ( + $i === 0 && count($wheres) > 1 && str_starts_with($where['boolean'], 'and') && str_starts_with($wheres[$i + 1]['boolean'], 'or') ) { - $where['boolean'] = 'or'.(str_ends_with($where['boolean'], 'not') ? ' not' : ''); - } - - // Column name can be a Stringable object. - if (isset($where['column']) && $where['column'] instanceof \Stringable) { - $where['column'] = (string) $where['column']; + $where['boolean'] = 'or' . (str_ends_with($where['boolean'], 'not') ? ' not' : ''); } // We use different methods to compile different wheres. - $method = "compileWhere{$where['type']}"; - + $method = 'compileWhere' . $where['type']; $result = $this->{$method}($where); if (str_ends_with($where['boolean'], 'not')) { @@ -1021,6 +1060,7 @@ protected function compileWheres(): array // Wrap the where with an $or operator. if (str_starts_with($where['boolean'], 'or')) { $result = ['$or' => [$result]]; + // phpcs:ignore Squiz.ControlStructures.ControlSignature.SpaceAfterCloseBrace } // If there are multiple wheres, we will wrap it with $and. This is needed @@ -1037,12 +1077,15 @@ protected function compileWheres(): array } /** - * @param array $where + * @param array $where + * * @return array */ protected function compileWhereBasic(array $where): array { - extract($where); + $column = $where['column']; + $operator = $where['operator']; + $value = $where['value']; // Replace like or not like with a Regex instance. if (in_array($operator, ['like', 'not like'])) { @@ -1062,10 +1105,11 @@ protected function compileWhereBasic(array $where): array // All backslashes are converted to \\, which are needed in matching regexes. preg_quote($value), ); - $value = new Regex('^'.$regex.'$', 'i'); + $value = new Regex('^' . $regex . '$', 'i'); // For inverse like operations, we can just use the $not operator with the Regex $operator = $operator === 'like' ? '=' : 'not'; + // phpcs:ignore Squiz.ControlStructures.ControlSignature.SpaceAfterCloseBrace } // Manipulate regex operations. @@ -1075,18 +1119,20 @@ protected function compileWhereBasic(array $where): array // Detect the delimiter and validate the preg pattern $delimiter = substr($value, 0, 1); if (! in_array($delimiter, self::REGEX_DELIMITERS)) { - throw new \LogicException(sprintf('Missing expected starting delimiter in regular expression "%s", supported delimiters are: %s', $value, implode(' ', self::REGEX_DELIMITERS))); + throw new LogicException(sprintf('Missing expected starting delimiter in regular expression "%s", supported delimiters are: %s', $value, implode(' ', self::REGEX_DELIMITERS))); } + $e = explode($delimiter, $value); // We don't try to detect if the last delimiter is escaped. This would be an invalid regex. if (count($e) < 3) { - throw new \LogicException(sprintf('Missing expected ending delimiter "%s" in regular expression "%s"', $delimiter, $value)); + throw new LogicException(sprintf('Missing expected ending delimiter "%s" in regular expression "%s"', $delimiter, $value)); } + // Flags are after the last delimiter $flags = end($e); // Extract the regex string between the delimiters $regstr = substr($value, 1, -1 - strlen($flags)); - $value = new Regex($regstr, $flags); + $value = new Regex($regstr, $flags); } // For inverse regex operations, we can just use the $not operator with the Regex @@ -1096,76 +1142,48 @@ protected function compileWhereBasic(array $where): array if (! isset($operator) || $operator === '=' || $operator === 'eq') { $query = [$column => $value]; } else { - $query = [$column => ['$'.$operator => $value]]; + $query = [$column => ['$' . $operator => $value]]; } return $query; } - /** - * @param array $where - * @return mixed - */ protected function compileWhereNested(array $where): mixed { - extract($where); - - return $query->compileWheres(); + return $where['query']->compileWheres(); } - /** - * @param array $where - * @return array - */ protected function compileWhereIn(array $where): array { - extract($where); - - return [$column => ['$in' => array_values($values)]]; + return [$where['column'] => ['$in' => array_values($where['values'])]]; } - /** - * @param array $where - * @return array - */ protected function compileWhereNotIn(array $where): array { - extract($where); - - return [$column => ['$nin' => array_values($values)]]; + return [$where['column'] => ['$nin' => array_values($where['values'])]]; } - /** - * @param array $where - * @return array - */ protected function compileWhereNull(array $where): array { $where['operator'] = '='; - $where['value'] = null; + $where['value'] = null; return $this->compileWhereBasic($where); } - /** - * @param array $where - * @return array - */ protected function compileWhereNotNull(array $where): array { $where['operator'] = 'ne'; - $where['value'] = null; + $where['value'] = null; return $this->compileWhereBasic($where); } - /** - * @param array $where - * @return array - */ protected function compileWhereBetween(array $where): array { - extract($where); + $column = $where['column']; + $not = $where['not']; + $values = $where['values']; if ($not) { return [ @@ -1192,16 +1210,12 @@ protected function compileWhereBetween(array $where): array ]; } - /** - * @param array $where - * @return array - */ protected function compileWhereDate(array $where): array { $startOfDay = new UTCDateTime(Carbon::parse($where['value'])->startOfDay()); - $endOfDay = new UTCDateTime(Carbon::parse($where['value'])->endOfDay()); + $endOfDay = new UTCDateTime(Carbon::parse($where['value'])->endOfDay()); - return match($where['operator']) { + return match ($where['operator']) { 'eq', '=' => [ $where['column'] => [ '$gte' => $startOfDay, @@ -1217,29 +1231,21 @@ protected function compileWhereDate(array $where): array ], ], 'lt', 'gte' => [ - $where['column'] => [ - '$'.$where['operator'] => $startOfDay, - ], + $where['column'] => ['$' . $where['operator'] => $startOfDay], ], 'gt', 'lte' => [ - $where['column'] => [ - '$'.$where['operator'] => $endOfDay, - ], + $where['column'] => ['$' . $where['operator'] => $endOfDay], ], }; } - /** - * @param array $where - * @return array - */ protected function compileWhereMonth(array $where): array { return [ '$expr' => [ - '$'.$where['operator'] => [ + '$' . $where['operator'] => [ [ - '$month' => '$'.$where['column'], + '$month' => '$' . $where['column'], ], (int) $where['value'], ], @@ -1247,17 +1253,13 @@ protected function compileWhereMonth(array $where): array ]; } - /** - * @param array $where - * @return array - */ protected function compileWhereDay(array $where): array { return [ '$expr' => [ - '$'.$where['operator'] => [ + '$' . $where['operator'] => [ [ - '$dayOfMonth' => '$'.$where['column'], + '$dayOfMonth' => '$' . $where['column'], ], (int) $where['value'], ], @@ -1265,17 +1267,13 @@ protected function compileWhereDay(array $where): array ]; } - /** - * @param array $where - * @return array - */ protected function compileWhereYear(array $where): array { return [ '$expr' => [ - '$'.$where['operator'] => [ + '$' . $where['operator'] => [ [ - '$year' => '$'.$where['column'], + '$year' => '$' . $where['column'], ], (int) $where['value'], ], @@ -1283,14 +1281,10 @@ protected function compileWhereYear(array $where): array ]; } - /** - * @param array $where - * @return array - */ protected function compileWhereTime(array $where): array { if (! is_string($where['value']) || ! preg_match('/^[0-2][0-9](:[0-6][0-9](:[0-6][0-9])?)?$/', $where['value'], $matches)) { - throw new \InvalidArgumentException(sprintf('Invalid time format, expected HH:MM:SS, HH:MM or HH, got "%s"', is_string($where['value']) ? $where['value'] : get_debug_type($where['value']))); + throw new InvalidArgumentException(sprintf('Invalid time format, expected HH:MM:SS, HH:MM or HH, got "%s"', is_string($where['value']) ? $where['value'] : get_debug_type($where['value']))); } $format = match (count($matches)) { @@ -1301,9 +1295,9 @@ protected function compileWhereTime(array $where): array return [ '$expr' => [ - '$'.$where['operator'] => [ + '$' . $where['operator'] => [ [ - '$dateToString' => ['date' => '$'.$where['column'], 'format' => $format], + '$dateToString' => ['date' => '$' . $where['column'], 'format' => $format], ], $where['value'], ], @@ -1311,10 +1305,6 @@ protected function compileWhereTime(array $where): array ]; } - /** - * @param array $where - * @return mixed - */ protected function compileWhereRaw(array $where): mixed { return $where['sql']; @@ -1323,7 +1313,6 @@ protected function compileWhereRaw(array $where): mixed /** * Set custom options for the query. * - * @param array $options * @return $this */ public function options(array $options) @@ -1338,19 +1327,20 @@ public function options(array $options) */ private function inheritConnectionOptions(array $options = []): array { - if (! isset($options['session']) && ($session = $this->connection->getSession())) { - $options['session'] = $session; + if (! isset($options['session'])) { + $session = $this->connection->getSession(); + if ($session) { + $options['session'] = $session; + } } return $options; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function __call($method, $parameters) { - if ($method == 'unset') { + if ($method === 'unset') { return $this->drop(...$parameters); } @@ -1360,90 +1350,90 @@ public function __call($method, $parameters) /** @internal This method is not supported by MongoDB. */ public function toSql() { - throw new \BadMethodCallException('This method is not supported by MongoDB. Try "toMql()" instead.'); + throw new BadMethodCallException('This method is not supported by MongoDB. Try "toMql()" instead.'); } /** @internal This method is not supported by MongoDB. */ public function toRawSql() { - throw new \BadMethodCallException('This method is not supported by MongoDB. Try "toMql()" instead.'); + throw new BadMethodCallException('This method is not supported by MongoDB. Try "toMql()" instead.'); } /** @internal This method is not supported by MongoDB. */ public function whereColumn($first, $operator = null, $second = null, $boolean = 'and') { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function whereFullText($columns, $value, array $options = [], $boolean = 'and') { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function groupByRaw($sql, array $bindings = []) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function orderByRaw($sql, $bindings = []) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function unionAll($query) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function union($query, $all = false) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function having($column, $operator = null, $value = null, $boolean = 'and') { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function havingRaw($sql, array $bindings = [], $boolean = 'and') { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function havingBetween($column, iterable $values, $boolean = 'and', $not = false) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = false) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function orWhereIntegerInRaw($column, $values) { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function whereIntegerNotInRaw($column, $values, $boolean = 'and') { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } /** @internal This method is not supported by MongoDB. */ public function orWhereIntegerNotInRaw($column, $values, $boolean = 'and') { - throw new \BadMethodCallException('This method is not supported by MongoDB'); + throw new BadMethodCallException('This method is not supported by MongoDB'); } } diff --git a/src/Query/Grammar.php b/src/Query/Grammar.php index d06e945bc..381a98eaa 100644 --- a/src/Query/Grammar.php +++ b/src/Query/Grammar.php @@ -1,5 +1,7 @@ getTimestamp(); - - $exception = (string) $exception; - - $this->getTable()->insert(compact('connection', 'queue', 'payload', 'failed_at', 'exception')); + $this->getTable()->insert([ + 'connection' => $connection, + 'queue' => $queue, + 'payload' => $payload, + 'failed_at' => Carbon::now()->getTimestamp(), + 'exception' => (string) $exception, + ]); } /** @@ -47,6 +55,7 @@ public function all() * Get a single failed job. * * @param mixed $id + * * @return object */ public function find($id) @@ -66,6 +75,7 @@ public function find($id) * Delete a single failed job from storage. * * @param mixed $id + * * @return bool */ public function forget($id) diff --git a/src/Queue/MongoConnector.php b/src/Queue/MongoConnector.php index d9e5b97e5..4f987694a 100644 --- a/src/Queue/MongoConnector.php +++ b/src/Queue/MongoConnector.php @@ -1,7 +1,10 @@ connections->connection($config['connection'] ?? null), $config['table'], $config['queue'], - $config['expire'] ?? 60 + $config['expire'] ?? 60, ); } } diff --git a/src/Queue/MongoJob.php b/src/Queue/MongoJob.php index ce9bae75e..13e458aac 100644 --- a/src/Queue/MongoJob.php +++ b/src/Queue/MongoJob.php @@ -1,7 +1,10 @@ job->reserved; } - /** - * @return \DateTime - */ + /** @return DateTime */ public function reservedAt() { return $this->job->reserved_at; diff --git a/src/Queue/MongoQueue.php b/src/Queue/MongoQueue.php index fd67a437a..eeac36c78 100644 --- a/src/Queue/MongoQueue.php +++ b/src/Queue/MongoQueue.php @@ -1,11 +1,14 @@ retryAfter = $retryAfter; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function pop($queue = null) { $queue = $this->getQueue($queue); @@ -43,11 +43,18 @@ public function pop($queue = null) $this->releaseJobsThatHaveBeenReservedTooLong($queue); } - if ($job = $this->getNextAvailableJobAndReserve($queue)) { - return new MongoJob( - $this->container, $this, $job, $this->connectionName, $queue - ); + $job = $this->getNextAvailableJobAndReserve($queue); + if (! $job) { + return null; } + + return new MongoJob( + $this->container, + $this, + $job, + $this->connectionName, + $queue, + ); } /** @@ -55,12 +62,13 @@ public function pop($queue = null) * When using multiple daemon queue listeners to process jobs there * is a possibility that multiple processes can end up reading the * same record before one has flagged it as reserved. - * This race condition can result in random jobs being run more then + * This race condition can result in random jobs being run more than * once. To solve this we use findOneAndUpdate to lock the next jobs * record while flagging it as reserved at the same time. * * @param string|null $queue - * @return \StdClass|null + * + * @return stdClass|null */ protected function getNextAvailableJobAndReserve($queue) { @@ -75,14 +83,12 @@ protected function getNextAvailableJobAndReserve($queue) 'reserved' => 1, 'reserved_at' => Carbon::now()->getTimestamp(), ], - '$inc' => [ - 'attempts' => 1, - ], + '$inc' => ['attempts' => 1], ], [ 'returnDocument' => FindOneAndUpdate::RETURN_DOCUMENT_AFTER, 'sort' => ['available_at' => 1], - ] + ], ); if ($job) { @@ -96,6 +102,7 @@ protected function getNextAvailableJobAndReserve($queue) * Release the jobs that have been reserved for too long. * * @param string $queue + * * @return void */ protected function releaseJobsThatHaveBeenReservedTooLong($queue) @@ -117,7 +124,8 @@ protected function releaseJobsThatHaveBeenReservedTooLong($queue) * Release the given job ID from reservation. * * @param string $id - * @param int $attempts + * @param int $attempts + * * @return void */ protected function releaseJob($id, $attempts) @@ -129,17 +137,13 @@ protected function releaseJob($id, $attempts) ]); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function deleteReserved($queue, $id) { $this->database->collection($this->table)->where('_id', $id)->delete(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function deleteAndRelease($queue, $job, $delay) { $this->deleteReserved($queue, $job->getJobId()); diff --git a/src/Relations/BelongsTo.php b/src/Relations/BelongsTo.php index b159b3ddf..0a8cb1d9c 100644 --- a/src/Relations/BelongsTo.php +++ b/src/Relations/BelongsTo.php @@ -1,9 +1,13 @@ getOwnerKey(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function addConstraints() { if (static::$constraints) { @@ -30,9 +32,7 @@ public function addConstraints() } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function addEagerConstraints(array $models) { // We'll grab the primary key name of the related models since it could be set to @@ -43,9 +43,7 @@ public function addEagerConstraints(array $models) $this->query->whereIn($key, $this->getEagerModelKeys($models)); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { return $query; @@ -64,11 +62,11 @@ public function getOwnerKey() /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model * @param string $key + * * @return string */ - protected function whereInMethod(EloquentModel $model, $key) + protected function whereInMethod(Model $model, $key) { return 'whereIn'; } diff --git a/src/Relations/BelongsToMany.php b/src/Relations/BelongsToMany.php index 61ac4a9f2..4afa3663b 100644 --- a/src/Relations/BelongsToMany.php +++ b/src/Relations/BelongsToMany.php @@ -1,5 +1,7 @@ getForeignKey(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { return $query; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function hydratePivotRelation(array $models) { // Do nothing. @@ -39,7 +47,6 @@ protected function hydratePivotRelation(array $models) /** * Set the select clause for the relation query. * - * @param array $columns * @return array */ protected function getSelectColumns(array $columns = ['*']) @@ -47,17 +54,13 @@ protected function getSelectColumns(array $columns = ['*']) return $columns; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function shouldSelect(array $columns = ['*']) { return $columns; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function addConstraints() { if (static::$constraints) { @@ -79,9 +82,7 @@ protected function setWhere() return $this; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function save(Model $model, array $joining = [], $touch = true) { $model->save(['touch' => false]); @@ -91,9 +92,7 @@ public function save(Model $model, array $joining = [], $touch = true) return $model; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function create(array $attributes = [], array $joining = [], $touch = true) { $instance = $this->related->newInstance($attributes); @@ -108,9 +107,7 @@ public function create(array $attributes = [], array $joining = [], $touch = tru return $instance; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function sync($ids, $detaching = true) { $changes = [ @@ -158,7 +155,8 @@ public function sync($ids, $detaching = true) // touching until after the entire operation is complete so we don't fire a // ton of touch operations until we are totally done syncing the records. $changes = array_merge( - $changes, $this->attachNew($records, $current, false) + $changes, + $this->attachNew($records, $current, false), ); if (count($changes['attached']) || count($changes['updated'])) { @@ -168,17 +166,13 @@ public function sync($ids, $detaching = true) return $changes; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function updateExistingPivot($id, array $attributes, $touch = true) { // Do nothing, we have no pivot table. } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function attach($id, array $attributes = [], $touch = true) { if ($id instanceof Model) { @@ -204,14 +198,14 @@ public function attach($id, array $attributes = [], $touch = true) // Attach the new ids to the parent model. $this->parent->push($this->getRelatedKey(), (array) $id, true); - if ($touch) { - $this->touchIfTouching(); + if (! $touch) { + return; } + + $this->touchIfTouching(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function detach($ids = [], $touch = true) { if ($ids instanceof Model) { @@ -243,9 +237,7 @@ public function detach($ids = [], $touch = true) return count($ids); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function buildDictionary(Collection $results) { $foreign = $this->foreignPivotKey; @@ -264,9 +256,7 @@ protected function buildDictionary(Collection $results) return $dictionary; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function newPivotQuery() { return $this->newRelatedQuery(); @@ -292,17 +282,13 @@ public function getForeignKey() return $this->foreignPivotKey; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getQualifiedForeignPivotKeyName() { return $this->foreignPivotKey; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getQualifiedRelatedPivotKeyName() { return $this->relatedPivotKey; @@ -312,9 +298,9 @@ public function getQualifiedRelatedPivotKeyName() * Format the sync list so that it is keyed by ID. (Legacy Support) * The original function has been renamed to formatRecordsList since Laravel 5.3. * - * @param array $records - * @return array * @deprecated + * + * @return array */ protected function formatSyncList(array $records) { @@ -323,6 +309,7 @@ protected function formatSyncList(array $records) if (! is_array($attributes)) { [$id, $attributes] = [$attributes, []]; } + $results[$id] = $attributes; } @@ -342,8 +329,8 @@ public function getRelatedKey() /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model * @param string $key + * * @return string */ protected function whereInMethod(Model $model, $key) diff --git a/src/Relations/EmbedsMany.php b/src/Relations/EmbedsMany.php index 5ef9a2e6e..b97849f24 100644 --- a/src/Relations/EmbedsMany.php +++ b/src/Relations/EmbedsMany.php @@ -1,19 +1,25 @@ toCollection($this->getEmbedded()); @@ -34,14 +38,13 @@ public function getResults() /** * Save a new model and attach it to the parent model. * - * @param Model $model * @return Model|bool */ public function performInsert(Model $model) { // Generate a new key if needed. - if ($model->getKeyName() == '_id' && ! $model->getKey()) { - $model->setAttribute('_id', new ObjectID); + if ($model->getKeyName() === '_id' && ! $model->getKey()) { + $model->setAttribute('_id', new ObjectID()); } // For deeply nested documents, let the parent handle the changes. @@ -65,7 +68,6 @@ public function performInsert(Model $model) /** * Save an existing model and attach it to the parent model. * - * @param Model $model * @return Model|bool */ public function performUpdate(Model $model) @@ -80,10 +82,10 @@ public function performUpdate(Model $model) // Get the correct foreign key value. $foreignKey = $this->getForeignKeyValue($model); - $values = $this->getUpdateValues($model->getDirty(), $this->localKey.'.$.'); + $values = $this->getUpdateValues($model->getDirty(), $this->localKey . '.$.'); // Update document in database. - $result = $this->toBase()->where($this->localKey.'.'.$model->getKeyName(), $foreignKey) + $result = $this->toBase()->where($this->localKey . '.' . $model->getKeyName(), $foreignKey) ->update($values); // Attach the model to its parent. @@ -97,7 +99,6 @@ public function performUpdate(Model $model) /** * Delete an existing model and detach it from the parent model. * - * @param Model $model * @return int */ public function performDelete(Model $model) @@ -124,7 +125,6 @@ public function performDelete(Model $model) /** * Associate the model instance to the given parent, without saving it to the database. * - * @param Model $model * @return Model */ public function associate(Model $model) @@ -139,7 +139,8 @@ public function associate(Model $model) /** * Dissociate the model instance from the given parent, without saving it to the database. * - * @param mixed $ids + * @param mixed $ids + * * @return int */ public function dissociate($ids = []) @@ -168,7 +169,8 @@ public function dissociate($ids = []) /** * Destroy the embedded models for the given IDs. * - * @param mixed $ids + * @param mixed $ids + * * @return int */ public function destroy($ids = []) @@ -210,7 +212,8 @@ public function delete() /** * Destroy alias. * - * @param mixed $ids + * @param mixed $ids + * * @return int */ public function detach($ids = []) @@ -221,7 +224,6 @@ public function detach($ids = []) /** * Save alias. * - * @param Model $model * @return Model */ public function attach(Model $model) @@ -232,14 +234,15 @@ public function attach(Model $model) /** * Associate a new model instance to the given parent, without saving it to the database. * - * @param Model $model + * @param Model $model + * * @return Model */ protected function associateNew($model) { // Create a new key if needed. if ($model->getKeyName() === '_id' && ! $model->getAttribute('_id')) { - $model->setAttribute('_id', new ObjectID); + $model->setAttribute('_id', new ObjectID()); } $records = $this->getEmbedded(); @@ -253,7 +256,8 @@ protected function associateNew($model) /** * Associate an existing model instance to the given parent, without saving it to the database. * - * @param Model $model + * @param Model $model + * * @return Model */ protected function associateExisting($model) @@ -267,6 +271,7 @@ protected function associateExisting($model) // Replace the document in the parent model. foreach ($records as &$record) { + // @phpcs:ignore SlevomatCodingStandard.Operators.DisallowEqualOperators if ($record[$primaryKey] == $key) { $record = $model->getAttributes(); break; @@ -277,25 +282,26 @@ protected function associateExisting($model) } /** - * @param int|null $perPage - * @param array $columns - * @param string $pageName - * @param int|null $page + * @param int|null $perPage + * @param array $columns + * @param string $pageName + * @param int|null $page + * * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator */ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) { - $page = $page ?: Paginator::resolveCurrentPage($pageName); + $page = $page ?: Paginator::resolveCurrentPage($pageName); $perPage = $perPage ?: $this->related->getPerPage(); $results = $this->getEmbedded(); $results = $this->toCollection($results); - $total = $results->count(); - $start = ($page - 1) * $perPage; + $total = $results->count(); + $start = ($page - 1) * $perPage; $sliced = $results->slice( $start, - $perPage + $perPage, ); return new LengthAwarePaginator( @@ -305,21 +311,17 @@ public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page, [ 'path' => Paginator::resolveCurrentPath(), - ] + ], ); } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function getEmbedded() { return parent::getEmbedded() ?: []; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function setEmbedded($models) { if (! is_array($models)) { @@ -329,9 +331,7 @@ protected function setEmbedded($models) return parent::setEmbedded(array_values($models)); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function __call($method, $parameters) { if (method_exists(Collection::class, $method)) { @@ -344,11 +344,11 @@ public function __call($method, $parameters) /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model - * @param string $key + * @param string $key + * * @return string */ - protected function whereInMethod(EloquentModel $model, $key) + protected function whereInMethod(Model $model, $key) { return 'whereIn'; } diff --git a/src/Relations/EmbedsOne.php b/src/Relations/EmbedsOne.php index 6d82808d9..196415a55 100644 --- a/src/Relations/EmbedsOne.php +++ b/src/Relations/EmbedsOne.php @@ -1,9 +1,10 @@ getKeyName() == '_id' && ! $model->getKey()) { - $model->setAttribute('_id', new ObjectID); + if ($model->getKeyName() === '_id' && ! $model->getKey()) { + $model->setAttribute('_id', new ObjectID()); } // For deeply nested documents, let the parent handle the changes. @@ -63,7 +63,6 @@ public function performInsert(Model $model) /** * Save an existing model and attach it to the parent model. * - * @param Model $model * @return Model|bool */ public function performUpdate(Model $model) @@ -74,7 +73,7 @@ public function performUpdate(Model $model) return $this->parent->save(); } - $values = $this->getUpdateValues($model->getDirty(), $this->localKey.'.'); + $values = $this->getUpdateValues($model->getDirty(), $this->localKey . '.'); $result = $this->toBase()->update($values); @@ -114,7 +113,6 @@ public function performDelete() /** * Attach the model to its parent. * - * @param Model $model * @return Model */ public function associate(Model $model) @@ -145,11 +143,11 @@ public function delete() /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model - * @param string $key + * @param string $key + * * @return string */ - protected function whereInMethod(EloquentModel $model, $key) + protected function whereInMethod(Model $model, $key) { return 'whereIn'; } diff --git a/src/Relations/EmbedsOneOrMany.php b/src/Relations/EmbedsOneOrMany.php index 200cdf65e..46f4f1e72 100644 --- a/src/Relations/EmbedsOneOrMany.php +++ b/src/Relations/EmbedsOneOrMany.php @@ -1,5 +1,7 @@ query = $query; - $this->parent = $parent; - $this->related = $related; - $this->localKey = $localKey; + $this->query = $query; + $this->parent = $parent; + $this->related = $related; + $this->localKey = $localKey; $this->foreignKey = $foreignKey; - $this->relation = $relation; + $this->relation = $relation; // If this is a nested relation, we need to get the parent query instead. - if ($parentRelation = $this->getParentRelation()) { + $parentRelation = $this->getParentRelation(); + if ($parentRelation) { $this->query = $parentRelation->getQuery(); } $this->addConstraints(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function addConstraints() { if (static::$constraints) { @@ -68,17 +66,13 @@ public function addConstraints() } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function addEagerConstraints(array $models) { // There are no eager loading constraints. } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function match(array $models, Collection $results, $relation) { foreach ($models as $model) { @@ -95,7 +89,8 @@ public function match(array $models, Collection $results, $relation) /** * Shorthand to get the results of the relationship. * - * @param array $columns + * @param array $columns + * * @return Collection */ public function get($columns = ['*']) @@ -116,7 +111,6 @@ public function count() /** * Attach a model instance to the parent model. * - * @param Model $model * @return Model|bool */ public function save(Model $model) @@ -129,7 +123,8 @@ public function save(Model $model) /** * Attach a collection of models to the parent instance. * - * @param Collection|array $models + * @param Collection|array $models + * * @return Collection|array */ public function saveMany($models) @@ -144,7 +139,6 @@ public function saveMany($models) /** * Create a new instance of the related model. * - * @param array $attributes * @return Model */ public function create(array $attributes = []) @@ -164,7 +158,6 @@ public function create(array $attributes = []) /** * Create an array of new instances of the related model. * - * @param array $records * @return array */ public function createMany(array $records) @@ -181,7 +174,8 @@ public function createMany(array $records) /** * Transform single ID, single Model or array of Models into an array of IDs. * - * @param mixed $ids + * @param mixed $ids + * * @return array */ protected function getIdsArrayFrom($ids) @@ -203,27 +197,21 @@ protected function getIdsArrayFrom($ids) return $ids; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function getEmbedded() { // Get raw attributes to skip relations and accessors. $attributes = $this->parent->getAttributes(); // Get embedded models form parent attributes. - $embedded = isset($attributes[$this->localKey]) ? (array) $attributes[$this->localKey] : null; - - return $embedded; + return isset($attributes[$this->localKey]) ? (array) $attributes[$this->localKey] : null; } - /** - * @inheritdoc - */ + /** @inheritdoc */ protected function setEmbedded($records) { // Assign models to parent attributes array. - $attributes = $this->parent->getAttributes(); + $attributes = $this->parent->getAttributes(); $attributes[$this->localKey] = $records; // Set raw attributes to skip mutators. @@ -236,7 +224,8 @@ protected function setEmbedded($records) /** * Get the foreign key value for the relation. * - * @param mixed $id + * @param mixed $id + * * @return mixed */ protected function getForeignKeyValue($id) @@ -252,7 +241,6 @@ protected function getForeignKeyValue($id) /** * Convert an array of records to a Collection. * - * @param array $records * @return Collection */ protected function toCollection(array $records = []) @@ -273,7 +261,8 @@ protected function toCollection(array $records = []) /** * Create a related model instanced. * - * @param array $attributes + * @param array $attributes + * * @return Model */ protected function toModel($attributes = []) @@ -286,7 +275,7 @@ protected function toModel($attributes = []) $model = $this->related->newFromBuilder( (array) $attributes, - $connection ? $connection->getName() : null + $connection ? $connection->getName() : null, ); $model->setParentRelation($this); @@ -309,9 +298,7 @@ protected function getParentRelation() return $this->parent->getParentRelation(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getQuery() { // Because we are sharing this relation instance to models, we need @@ -319,9 +306,7 @@ public function getQuery() return clone $this->query; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function toBase() { // Because we are sharing this relation instance to models, we need @@ -336,31 +321,32 @@ public function toBase() */ protected function isNested() { - return $this->getParentRelation() != null; + return $this->getParentRelation() !== null; } /** * Get the fully qualified local key name. * - * @param string $glue + * @param string $glue + * * @return string */ protected function getPathHierarchy($glue = '.') { - if ($parentRelation = $this->getParentRelation()) { - return $parentRelation->getPathHierarchy($glue).$glue.$this->localKey; + $parentRelation = $this->getParentRelation(); + if ($parentRelation) { + return $parentRelation->getPathHierarchy($glue) . $glue . $this->localKey; } return $this->localKey; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getQualifiedParentKeyName() { - if ($parentRelation = $this->getParentRelation()) { - return $parentRelation->getPathHierarchy().'.'.$this->parent->getKeyName(); + $parentRelation = $this->getParentRelation(); + if ($parentRelation) { + return $parentRelation->getPathHierarchy() . '.' . $this->parent->getKeyName(); } return $this->parent->getKeyName(); @@ -379,8 +365,9 @@ protected function getParentKey() /** * Return update values. * - * @param $array - * @param string $prepend + * @param array $array + * @param string $prepend + * * @return array */ public static function getUpdateValues($array, $prepend = '') @@ -388,7 +375,7 @@ public static function getUpdateValues($array, $prepend = '') $results = []; foreach ($array as $key => $value) { - $results[$prepend.$key] = $value; + $results[$prepend . $key] = $value; } return $results; @@ -407,8 +394,9 @@ public function getQualifiedForeignKeyName() /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model - * @param string $key + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * * @return string */ protected function whereInMethod(EloquentModel $model, $key) diff --git a/src/Relations/HasMany.php b/src/Relations/HasMany.php index b2b4d6239..a38fba15a 100644 --- a/src/Relations/HasMany.php +++ b/src/Relations/HasMany.php @@ -1,9 +1,11 @@ getForeignKeyName(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { $foreignKey = $this->getHasCompareKey(); @@ -41,11 +41,11 @@ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model * @param string $key + * * @return string */ - protected function whereInMethod(EloquentModel $model, $key) + protected function whereInMethod(Model $model, $key) { return 'whereIn'; } diff --git a/src/Relations/HasOne.php b/src/Relations/HasOne.php index ca84e01e7..740a489d8 100644 --- a/src/Relations/HasOne.php +++ b/src/Relations/HasOne.php @@ -1,9 +1,11 @@ getForeignKeyName(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*']) { $foreignKey = $this->getForeignKeyName(); @@ -41,11 +41,11 @@ public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model * @param string $key + * * @return string */ - protected function whereInMethod(EloquentModel $model, $key) + protected function whereInMethod(Model $model, $key) { return 'whereIn'; } diff --git a/src/Relations/MorphMany.php b/src/Relations/MorphMany.php index 2bba05ecf..88f825dc0 100644 --- a/src/Relations/MorphMany.php +++ b/src/Relations/MorphMany.php @@ -1,8 +1,10 @@ createModelByType($type); @@ -47,11 +47,11 @@ public function getOwnerKey() /** * Get the name of the "where in" method for eager loading. * - * @param \Illuminate\Database\Eloquent\Model $model * @param string $key + * * @return string */ - protected function whereInMethod(EloquentModel $model, $key) + protected function whereInMethod(Model $model, $key) { return 'whereIn'; } diff --git a/src/Schema/Blueprint.php b/src/Schema/Blueprint.php index 1272b6136..2580c407f 100644 --- a/src/Schema/Blueprint.php +++ b/src/Schema/Blueprint.php @@ -1,8 +1,19 @@ connection = $connection; $this->collection = $this->connection->getCollection($collection); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function index($columns = null, $name = null, $algorithm = null, $options = []) { $columns = $this->fluent($columns); @@ -65,17 +74,13 @@ public function index($columns = null, $name = null, $algorithm = null, $options return $this; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function primary($columns = null, $name = null, $algorithm = null, $options = []) { return $this->unique($columns, $name, $algorithm, $options); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function dropIndex($indexOrColumns = null) { $indexOrColumns = $this->transformColumns($indexOrColumns); @@ -88,7 +93,8 @@ public function dropIndex($indexOrColumns = null) /** * Indicate that the given index should be dropped, but do not fail if it didn't exist. * - * @param string|array $indexOrColumns + * @param string|array $indexOrColumns + * * @return Blueprint */ public function dropIndexIfExists($indexOrColumns = null) @@ -103,7 +109,8 @@ public function dropIndexIfExists($indexOrColumns = null) /** * Check whether the given index exists. * - * @param string|array $indexOrColumns + * @param string|array $indexOrColumns + * * @return bool */ public function hasIndex($indexOrColumns = null) @@ -114,7 +121,7 @@ public function hasIndex($indexOrColumns = null) return true; } - if (is_string($indexOrColumns) && $index->getName() == $indexOrColumns) { + if (is_string($indexOrColumns) && $index->getName() === $indexOrColumns) { return true; } } @@ -123,7 +130,8 @@ public function hasIndex($indexOrColumns = null) } /** - * @param string|array $indexOrColumns + * @param string|array $indexOrColumns + * * @return string */ protected function transformColumns($indexOrColumns) @@ -137,15 +145,15 @@ protected function transformColumns($indexOrColumns) foreach ($indexOrColumns as $key => $value) { if (is_int($key)) { // There is no sorting order, use the default. - $column = $value; + $column = $value; $sorting = '1'; } else { // This is a column with sorting order e.g 'my_column' => -1. - $column = $key; + $column = $key; $sorting = $value; } - $transform[$column] = $column.'_'.$sorting; + $transform[$column] = $column . '_' . $sorting; } $indexOrColumns = implode('_', $transform); @@ -154,9 +162,7 @@ protected function transformColumns($indexOrColumns) return $indexOrColumns; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function unique($columns = null, $name = null, $algorithm = null, $options = []) { $columns = $this->fluent($columns); @@ -172,6 +178,7 @@ public function unique($columns = null, $name = null, $algorithm = null, $option * Specify a non blocking index for the collection. * * @param string|array $columns + * * @return Blueprint */ public function background($columns = null) @@ -187,7 +194,8 @@ public function background($columns = null) * Specify a sparse index for the collection. * * @param string|array $columns - * @param array $options + * @param array $options + * * @return Blueprint */ public function sparse($columns = null, $options = []) @@ -205,13 +213,14 @@ public function sparse($columns = null, $options = []) * Specify a geospatial index for the collection. * * @param string|array $columns - * @param string $index - * @param array $options + * @param string $index + * @param array $options + * * @return Blueprint */ public function geospatial($columns = null, $index = '2d', $options = []) { - if ($index == '2d' || $index == '2dsphere') { + if ($index === '2d' || $index === '2dsphere') { $columns = $this->fluent($columns); $columns = array_flip($columns); @@ -231,7 +240,8 @@ public function geospatial($columns = null, $index = '2d', $options = []) * on the given single-field index containing a date. * * @param string|array $columns - * @param int $seconds + * @param int $seconds + * * @return Blueprint */ public function expire($columns, $seconds) @@ -247,6 +257,7 @@ public function expire($columns, $seconds) * Indicate that the collection needs to be created. * * @param array $options + * * @return void */ public function create($options = []) @@ -259,17 +270,13 @@ public function create($options = []) $db->createCollection($collection, $options); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function drop() { $this->collection->drop(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function addColumn($type, $name, array $parameters = []) { $this->fluent($name); @@ -281,8 +288,11 @@ public function addColumn($type, $name, array $parameters = []) * Specify a sparse and unique index for the collection. * * @param string|array $columns - * @param array $options + * @param array $options + * * @return Blueprint + * + * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps */ public function sparse_and_unique($columns = null, $options = []) { @@ -300,24 +310,28 @@ public function sparse_and_unique($columns = null, $options = []) * Allow fluent columns. * * @param string|array $columns + * * @return string|array */ protected function fluent($columns = null) { if ($columns === null) { return $this->columns; - } elseif (is_string($columns)) { + } + + if (is_string($columns)) { return $this->columns = [$columns]; - } else { - return $this->columns = $columns; } + + return $this->columns = $columns; } /** * Allows the use of unsupported schema methods. * - * @param $method - * @param $args + * @param string $method + * @param array $args + * * @return Blueprint */ public function __call($method, $args) diff --git a/src/Schema/Builder.php b/src/Schema/Builder.php index be0b7f324..af311df6c 100644 --- a/src/Schema/Builder.php +++ b/src/Schema/Builder.php @@ -1,22 +1,25 @@ connection->getMongoDB(); $collections = iterator_to_array($db->listCollections([ - 'filter' => [ - 'name' => $name, - ], + 'filter' => ['name' => $name], ]), false); - return count($collections) ? true : false; + return count($collections) !== 0; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function hasTable($collection) { return $this->hasCollection($collection); @@ -53,8 +53,8 @@ public function hasTable($collection) * Modify a collection on the schema. * * @param string $collection - * @param Closure $callback - * @return bool + * + * @return void */ public function collection($collection, Closure $callback) { @@ -65,18 +65,14 @@ public function collection($collection, Closure $callback) } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function table($collection, Closure $callback) { - return $this->collection($collection, $callback); + $this->collection($collection, $callback); } - /** - * @inheritdoc - */ - public function create($collection, Closure $callback = null, array $options = []) + /** @inheritdoc */ + public function create($collection, ?Closure $callback = null, array $options = []) { $blueprint = $this->createBlueprint($collection); @@ -87,31 +83,23 @@ public function create($collection, Closure $callback = null, array $options = [ } } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function dropIfExists($collection) { if ($this->hasCollection($collection)) { - return $this->drop($collection); + $this->drop($collection); } - - return false; } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function drop($collection) { $blueprint = $this->createBlueprint($collection); - return $blueprint->drop(); + $blueprint->drop(); } - /** - * @inheritdoc - */ + /** @inheritdoc */ public function dropAllTables() { foreach ($this->getAllCollections() as $collection) { @@ -119,10 +107,8 @@ public function dropAllTables() } } - /** - * @inheritdoc - */ - protected function createBlueprint($collection, Closure $callback = null) + /** @inheritdoc */ + protected function createBlueprint($collection, ?Closure $callback = null) { return new Blueprint($this->connection, $collection); } @@ -131,16 +117,15 @@ protected function createBlueprint($collection, Closure $callback = null) * Get collection. * * @param string $name - * @return bool|\MongoDB\Model\CollectionInfo + * + * @return bool|CollectionInfo */ public function getCollection($name) { $db = $this->connection->getMongoDB(); $collections = iterator_to_array($db->listCollections([ - 'filter' => [ - 'name' => $name, - ], + 'filter' => ['name' => $name], ]), false); return count($collections) ? current($collections) : false; diff --git a/src/Schema/Grammar.php b/src/Schema/Grammar.php index 8124ae19c..3b86ec4a1 100644 --- a/src/Schema/Grammar.php +++ b/src/Schema/Grammar.php @@ -1,5 +1,7 @@ table($collection)->where($column, new Regex('^'.preg_quote($value).'$', '/i')); + $query = $this->table($collection)->where($column, new Regex('^' . preg_quote($value) . '$', '/i')); - if ($excludeId !== null && $excludeId != 'NULL') { + if ($excludeId !== null && $excludeId !== 'NULL') { $query->where($idColumn ?: 'id', '<>', $excludeId); } @@ -37,8 +43,9 @@ public function getCount($collection, $column, $value, $excludeId = null, $idCol * * @param string $collection * @param string $column - * @param array $values - * @param array $extra + * @param array $values + * @param array $extra + * * @return int */ public function getMultiCount($collection, $column, array $values, array $extra = []) @@ -49,7 +56,7 @@ public function getMultiCount($collection, $column, array $values, array $extra } // Generates a regex like '/^(a|b|c)$/i' which can query multiple values - $regex = new Regex('^('.implode('|', array_map(preg_quote(...), $values)).')$', 'i'); + $regex = new Regex('^(' . implode('|', array_map(preg_quote(...), $values)) . ')$', 'i'); $query = $this->table($collection)->where($column, 'regex', $regex); diff --git a/src/Validation/ValidationServiceProvider.php b/src/Validation/ValidationServiceProvider.php index 858929fd9..1095e93a3 100644 --- a/src/Validation/ValidationServiceProvider.php +++ b/src/Validation/ValidationServiceProvider.php @@ -1,5 +1,7 @@ truncate(); } @@ -50,8 +55,8 @@ function ($actualUser, $actualToken) use ($user, &$token) { $this->assertEquals($user->_id, $actualUser->_id); // Store token for later use $token = $actualToken; - } - ) + }, + ), ); $this->assertEquals(1, DB::collection('password_reset_tokens')->count()); diff --git a/tests/Casts/BinaryUuidTest.php b/tests/Casts/BinaryUuidTest.php index f6350c8d6..8a79b1500 100644 --- a/tests/Casts/BinaryUuidTest.php +++ b/tests/Casts/BinaryUuidTest.php @@ -1,13 +1,16 @@ [$uuid, $binaryUuid, $binaryUuid]; diff --git a/tests/Casts/ObjectIdTest.php b/tests/Casts/ObjectIdTest.php index fe532eae9..8d3e9daf4 100644 --- a/tests/Casts/ObjectIdTest.php +++ b/tests/Casts/ObjectIdTest.php @@ -1,5 +1,7 @@ [$objectId, $objectId]; @@ -39,7 +41,7 @@ public static function provideObjectIdCast(): Generator public function testQueryByStringDoesNotCast(): void { - $objectId = new ObjectId(); + $objectId = new ObjectId(); $stringObjectId = (string) $objectId; CastObjectId::create(['oid' => $objectId]); diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index f698b4df1..fbdbf3daf 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -13,9 +13,9 @@ class CollectionTest extends TestCase { public function testExecuteMethodCall() { - $return = ['foo' => 'bar']; - $where = ['id' => new ObjectID('56f94800911dcc276b5723dd')]; - $time = 1.1; + $return = ['foo' => 'bar']; + $where = ['id' => new ObjectID('56f94800911dcc276b5723dd')]; + $time = 1.1; $queryString = 'name-collection.findOne({"id":"56f94800911dcc276b5723dd"})'; $mongoCollection = $this->getMockBuilder(MongoCollection::class) diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index 77a2dce78..51a463c56 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -14,6 +14,8 @@ use MongoDB\Laravel\Query\Builder; use MongoDB\Laravel\Schema\Builder as SchemaBuilder; +use function spl_object_hash; + class ConnectionTest extends TestCase { public function testConnection() @@ -162,9 +164,7 @@ public function dataConnectionConfig(): Generator yield 'Database is extracted from DSN if not specified' => [ 'expectedUri' => 'mongodb://some-host:12345/tests', 'expectedDatabaseName' => 'tests', - 'config' => [ - 'dsn' => 'mongodb://some-host:12345/tests', - ], + 'config' => ['dsn' => 'mongodb://some-host:12345/tests'], ]; } @@ -172,7 +172,7 @@ public function dataConnectionConfig(): Generator public function testConnectionConfig(string $expectedUri, string $expectedDatabaseName, array $config): void { $connection = new Connection($config); - $client = $connection->getMongoClient(); + $client = $connection->getMongoClient(); $this->assertSame($expectedUri, (string) $client); $this->assertSame($expectedDatabaseName, $connection->getMongoDB()->getDatabaseName()); diff --git a/tests/Eloquent/MassPrunableTest.php b/tests/Eloquent/MassPrunableTest.php index 3426a2443..a93f864e5 100644 --- a/tests/Eloquent/MassPrunableTest.php +++ b/tests/Eloquent/MassPrunableTest.php @@ -11,6 +11,9 @@ use MongoDB\Laravel\Tests\Models\User; use MongoDB\Laravel\Tests\TestCase; +use function class_uses_recursive; +use function in_array; + class MassPrunableTest extends TestCase { public function tearDown(): void @@ -51,9 +54,7 @@ public function testPruneSoftDelete(): void $this->assertEquals(0, Soft::withTrashed()->count()); } - /** - * @see PruneCommand::isPrunable() - */ + /** @see PruneCommand::isPrunable() */ protected function isPrunable($model) { $uses = class_uses_recursive($model); diff --git a/tests/EmbeddedRelationsTest.php b/tests/EmbeddedRelationsTest.php index 231fec6dc..2dd558679 100644 --- a/tests/EmbeddedRelationsTest.php +++ b/tests/EmbeddedRelationsTest.php @@ -18,6 +18,8 @@ use MongoDB\Laravel\Tests\Models\Role; use MongoDB\Laravel\Tests\Models\User; +use function array_merge; + class EmbeddedRelationsTest extends TestCase { public function tearDown(): void @@ -35,21 +37,21 @@ public function tearDown(): void public function testEmbedsManySave() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'London']); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($address), $address) + ->with('eloquent.saving: ' . $address::class, $address) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.creating: '.get_class($address), $address) + ->with('eloquent.creating: ' . $address::class, $address) ->andReturn(true); - $events->shouldReceive('dispatch')->once()->with('eloquent.created: '.get_class($address), $address); - $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($address), $address); + $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . $address::class, $address); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . $address::class, $address); $address = $user->addresses()->save($address); $address->unsetEventDispatcher(); @@ -71,17 +73,17 @@ public function testEmbedsManySave() $this->assertEquals(['London', 'Paris'], $user->addresses->pluck('city')->all()); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($address), $address) + ->with('eloquent.saving: ' . $address::class, $address) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.updating: '.get_class($address), $address) + ->with('eloquent.updating: ' . $address::class, $address) ->andReturn(true); - $events->shouldReceive('dispatch')->once()->with('eloquent.updated: '.get_class($address), $address); - $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($address), $address); + $events->shouldReceive('dispatch')->once()->with('eloquent.updated: ' . $address::class, $address); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . $address::class, $address); $address->city = 'New York'; $user->addresses()->save($address); @@ -107,7 +109,7 @@ public function testEmbedsManySave() $user->addresses()->save(new Address(['city' => 'Bruxelles'])); $this->assertEquals(['London', 'New York', 'Bruxelles'], $user->addresses->pluck('city')->all()); - $address = $user->addresses[1]; + $address = $user->addresses[1]; $address->city = 'Manhattan'; $user->addresses()->save($address); $this->assertEquals(['London', 'Manhattan', 'Bruxelles'], $user->addresses->pluck('city')->all()); @@ -128,7 +130,7 @@ public function testEmbedsToArray() public function testEmbedsManyAssociate() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'London']); $user->addresses()->associate($address); @@ -158,7 +160,7 @@ public function testEmbedsManySaveMany() public function testEmbedsManyDuplicate() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'London']); $user->addresses()->save($address); $user->addresses()->save($address); @@ -180,7 +182,7 @@ public function testEmbedsManyDuplicate() public function testEmbedsManyCreate() { - $user = User::create([]); + $user = User::create([]); $address = $user->addresses()->create(['city' => 'Bruxelles']); $this->assertInstanceOf(Address::class, $address); $this->assertIsString($address->_id); @@ -192,7 +194,7 @@ public function testEmbedsManyCreate() $freshUser = User::find($user->id); $this->assertEquals(['Bruxelles'], $freshUser->addresses->pluck('city')->all()); - $user = User::create([]); + $user = User::create([]); $address = $user->addresses()->create(['_id' => '', 'city' => 'Bruxelles']); $this->assertIsString($address->_id); @@ -202,7 +204,7 @@ public function testEmbedsManyCreate() public function testEmbedsManyCreateMany() { - $user = User::create([]); + $user = User::create([]); [$bruxelles, $paris] = $user->addresses()->createMany([['city' => 'Bruxelles'], ['city' => 'Paris']]); $this->assertInstanceOf(Address::class, $bruxelles); $this->assertEquals('Bruxelles', $bruxelles->city); @@ -224,14 +226,14 @@ public function testEmbedsManyDestroy() $address = $user->addresses->first(); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.deleting: '.get_class($address), Mockery::type(Address::class)) + ->with('eloquent.deleting: ' . $address::class, Mockery::type(Address::class)) ->andReturn(true); $events->shouldReceive('dispatch') ->once() - ->with('eloquent.deleted: '.get_class($address), Mockery::type(Address::class)); + ->with('eloquent.deleted: ' . $address::class, Mockery::type(Address::class)); $user->addresses()->destroy($address->_id); $this->assertEquals(['Bristol', 'Bruxelles'], $user->addresses->pluck('city')->all()); @@ -276,14 +278,14 @@ public function testEmbedsManyDelete() $address = $user->addresses->first(); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.deleting: '.get_class($address), Mockery::type(Address::class)) + ->with('eloquent.deleting: ' . $address::class, Mockery::type(Address::class)) ->andReturn(true); $events->shouldReceive('dispatch') ->once() - ->with('eloquent.deleted: '.get_class($address), Mockery::type(Address::class)); + ->with('eloquent.deleted: ' . $address::class, Mockery::type(Address::class)); $address->delete(); @@ -302,7 +304,7 @@ public function testEmbedsManyDelete() public function testEmbedsManyDissociate() { - $user = User::create([]); + $user = User::create([]); $cordoba = $user->addresses()->create(['city' => 'Cordoba']); $user->addresses()->dissociate($cordoba->id); @@ -311,25 +313,25 @@ public function testEmbedsManyDissociate() $this->assertEquals(0, $user->addresses->count()); $this->assertEquals(1, $freshUser->addresses->count()); - $broken_address = Address::make(['name' => 'Broken']); + $brokenAddress = Address::make(['name' => 'Broken']); $user->update([ 'addresses' => array_merge( - [$broken_address->toArray()], - $user->addresses()->toArray() + [$brokenAddress->toArray()], + $user->addresses()->toArray(), ), ]); $curitiba = $user->addresses()->create(['city' => 'Curitiba']); $user->addresses()->dissociate($curitiba->id); - $this->assertEquals(1, $user->addresses->where('name', $broken_address->name)->count()); + $this->assertEquals(1, $user->addresses->where('name', $brokenAddress->name)->count()); $this->assertEquals(1, $user->addresses->count()); } public function testEmbedsManyAliases() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'London']); $address = $user->addresses()->attach($address); @@ -341,18 +343,18 @@ public function testEmbedsManyAliases() public function testEmbedsManyCreatingEventReturnsFalse() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'London']); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($address), $address) + ->with('eloquent.saving: ' . $address::class, $address) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.creating: '.get_class($address), $address) + ->with('eloquent.creating: ' . $address::class, $address) ->andReturn(false); $this->assertFalse($user->addresses()->save($address)); @@ -361,15 +363,15 @@ public function testEmbedsManyCreatingEventReturnsFalse() public function testEmbedsManySavingEventReturnsFalse() { - $user = User::create(['name' => 'John Doe']); - $address = new Address(['city' => 'Paris']); + $user = User::create(['name' => 'John Doe']); + $address = new Address(['city' => 'Paris']); $address->exists = true; $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($address), $address) + ->with('eloquent.saving: ' . $address::class, $address) ->andReturn(false); $this->assertFalse($user->addresses()->save($address)); @@ -378,19 +380,19 @@ public function testEmbedsManySavingEventReturnsFalse() public function testEmbedsManyUpdatingEventReturnsFalse() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'New York']); $user->addresses()->save($address); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($address), $address) + ->with('eloquent.saving: ' . $address::class, $address) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.updating: '.get_class($address), $address) + ->with('eloquent.updating: ' . $address::class, $address) ->andReturn(false); $address->city = 'Warsaw'; @@ -407,10 +409,10 @@ public function testEmbedsManyDeletingEventReturnsFalse() $address = $user->addresses->first(); $address->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($address), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $address::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.deleting: '.get_class($address), Mockery::mustBe($address)) + ->with('eloquent.deleting: ' . $address::class, Mockery::mustBe($address)) ->andReturn(false); $this->assertEquals(0, $user->addresses()->destroy($address)); @@ -421,7 +423,7 @@ public function testEmbedsManyDeletingEventReturnsFalse() public function testEmbedsManyFindOrContains() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address1 = $user->addresses()->save(new Address(['city' => 'New York'])); $address2 = $user->addresses()->save(new Address(['city' => 'Paris'])); @@ -445,13 +447,13 @@ public function testEmbedsManyEagerLoading() $user2->addresses()->save(new Address(['city' => 'Berlin'])); $user2->addresses()->save(new Address(['city' => 'Paris'])); - $user = User::find($user1->id); + $user = User::find($user1->id); $relations = $user->getRelations(); $this->assertArrayNotHasKey('addresses', $relations); $this->assertArrayHasKey('addresses', $user->toArray()); $this->assertIsArray($user->toArray()['addresses']); - $user = User::with('addresses')->get()->first(); + $user = User::with('addresses')->get()->first(); $relations = $user->getRelations(); $this->assertArrayHasKey('addresses', $relations); $this->assertEquals(2, $relations['addresses']->count()); @@ -540,21 +542,21 @@ public function testEmbedsManyCollectionMethods() public function testEmbedsOne() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $father = new User(['name' => 'Mark Doe']); $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($father), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $father::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($father), $father) + ->with('eloquent.saving: ' . $father::class, $father) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.creating: '.get_class($father), $father) + ->with('eloquent.creating: ' . $father::class, $father) ->andReturn(true); - $events->shouldReceive('dispatch')->once()->with('eloquent.created: '.get_class($father), $father); - $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($father), $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . $father::class, $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . $father::class, $father); $father = $user->father()->save($father); $father->unsetEventDispatcher(); @@ -570,17 +572,17 @@ public function testEmbedsOne() $this->assertInstanceOf(ObjectId::class, $raw['_id']); $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($father), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $father::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($father), $father) + ->with('eloquent.saving: ' . $father::class, $father) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.updating: '.get_class($father), $father) + ->with('eloquent.updating: ' . $father::class, $father) ->andReturn(true); - $events->shouldReceive('dispatch')->once()->with('eloquent.updated: '.get_class($father), $father); - $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($father), $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.updated: ' . $father::class, $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . $father::class, $father); $father->name = 'Tom Doe'; $user->father()->save($father); @@ -592,17 +594,17 @@ public function testEmbedsOne() $father = new User(['name' => 'Jim Doe']); $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($father), Mockery::any()); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $father::class, Mockery::any()); $events->shouldReceive('until') ->once() - ->with('eloquent.saving: '.get_class($father), $father) + ->with('eloquent.saving: ' . $father::class, $father) ->andReturn(true); $events->shouldReceive('until') ->once() - ->with('eloquent.creating: '.get_class($father), $father) + ->with('eloquent.creating: ' . $father::class, $father) ->andReturn(true); - $events->shouldReceive('dispatch')->once()->with('eloquent.created: '.get_class($father), $father); - $events->shouldReceive('dispatch')->once()->with('eloquent.saved: '.get_class($father), $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.created: ' . $father::class, $father); + $events->shouldReceive('dispatch')->once()->with('eloquent.saved: ' . $father::class, $father); $father = $user->father()->save($father); $father->unsetEventDispatcher(); @@ -613,12 +615,12 @@ public function testEmbedsOne() public function testEmbedsOneAssociate() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $father = new User(['name' => 'Mark Doe']); $father->setEventDispatcher($events = Mockery::mock(Dispatcher::class)); - $events->shouldReceive('dispatch')->with('eloquent.retrieved: '.get_class($father), Mockery::any()); - $events->shouldReceive('until')->times(0)->with('eloquent.saving: '.get_class($father), $father); + $events->shouldReceive('dispatch')->with('eloquent.retrieved: ' . $father::class, Mockery::any()); + $events->shouldReceive('until')->times(0)->with('eloquent.saving: ' . $father::class, $father); $father = $user->father()->associate($father); $father->unsetEventDispatcher(); @@ -635,7 +637,7 @@ public function testEmbedsOneNullAssociation() public function testEmbedsOneDelete() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $father = $user->father()->save(new User(['name' => 'Mark Doe'])); $user->father()->delete(); @@ -644,7 +646,7 @@ public function testEmbedsOneDelete() public function testEmbedsOneRefresh() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $father = new User(['name' => 'Mark Doe']); $user->father()->associate($father); @@ -658,7 +660,7 @@ public function testEmbedsOneRefresh() public function testEmbedsOneEmptyRefresh() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $father = new User(['name' => 'Mark Doe']); $user->father()->associate($father); @@ -674,8 +676,8 @@ public function testEmbedsOneEmptyRefresh() public function testEmbedsManyToArray() { - /** @var User $user */ $user = User::create(['name' => 'John Doe']); + $this->assertInstanceOf(User::class, $user); $user->addresses()->save(new Address(['city' => 'New York'])); $user->addresses()->save(new Address(['city' => 'Paris'])); $user->addresses()->save(new Address(['city' => 'Brussels'])); @@ -687,8 +689,8 @@ public function testEmbedsManyToArray() public function testEmbedsManyRefresh() { - /** @var User $user */ $user = User::create(['name' => 'John Doe']); + $this->assertInstanceOf(User::class, $user); $user->addresses()->save(new Address(['city' => 'New York'])); $user->addresses()->save(new Address(['city' => 'Paris'])); $user->addresses()->save(new Address(['city' => 'Brussels'])); @@ -703,10 +705,10 @@ public function testEmbedsManyRefresh() public function testEmbeddedSave() { - /** @var User $user */ $user = User::create(['name' => 'John Doe']); - /** @var Address $address */ + $this->assertInstanceOf(User::class, $user); $address = $user->addresses()->create(['city' => 'New York']); + $this->assertInstanceOf(Address::class, $address); $father = $user->father()->create(['name' => 'Mark Doe']); $address->city = 'Paris'; @@ -723,7 +725,7 @@ public function testEmbeddedSave() $this->assertEquals('Steve Doe', $user->father->name); $address = $user->addresses()->first(); - $father = $user->father; + $father = $user->father; $address->city = 'Ghent'; $address->save(); @@ -741,9 +743,9 @@ public function testEmbeddedSave() public function testNestedEmbedsOne() { - $user = User::create(['name' => 'John Doe']); - $father = $user->father()->create(['name' => 'Mark Doe']); - $grandfather = $father->father()->create(['name' => 'Steve Doe']); + $user = User::create(['name' => 'John Doe']); + $father = $user->father()->create(['name' => 'Mark Doe']); + $grandfather = $father->father()->create(['name' => 'Steve Doe']); $greatgrandfather = $grandfather->father()->create(['name' => 'Tom Doe']); $user->name = 'Tim Doe'; @@ -769,12 +771,12 @@ public function testNestedEmbedsOne() public function testNestedEmbedsMany() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $country1 = $user->addresses()->create(['country' => 'France']); $country2 = $user->addresses()->create(['country' => 'Belgium']); - $city1 = $country1->addresses()->create(['city' => 'Paris']); - $city2 = $country2->addresses()->create(['city' => 'Ghent']); - $city3 = $country2->addresses()->create(['city' => 'Brussels']); + $city1 = $country1->addresses()->create(['city' => 'Paris']); + $city2 = $country2->addresses()->create(['city' => 'Ghent']); + $city3 = $country2->addresses()->create(['city' => 'Brussels']); $city3->city = 'Bruges'; $city3->save(); @@ -791,8 +793,8 @@ public function testNestedEmbedsMany() public function testNestedMixedEmbeds() { - $user = User::create(['name' => 'John Doe']); - $father = $user->father()->create(['name' => 'Mark Doe']); + $user = User::create(['name' => 'John Doe']); + $father = $user->father()->create(['name' => 'Mark Doe']); $country1 = $father->addresses()->create(['country' => 'France']); $country2 = $father->addresses()->create(['country' => 'Belgium']); @@ -814,9 +816,9 @@ public function testNestedMixedEmbeds() public function testNestedEmbedsOneDelete() { - $user = User::create(['name' => 'John Doe']); - $father = $user->father()->create(['name' => 'Mark Doe']); - $grandfather = $father->father()->create(['name' => 'Steve Doe']); + $user = User::create(['name' => 'John Doe']); + $father = $user->father()->create(['name' => 'Mark Doe']); + $grandfather = $father->father()->create(['name' => 'Steve Doe']); $greatgrandfather = $grandfather->father()->create(['name' => 'Tom Doe']); $grandfather->delete(); @@ -829,11 +831,11 @@ public function testNestedEmbedsOneDelete() public function testNestedEmbedsManyDelete() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $country = $user->addresses()->create(['country' => 'France']); - $city1 = $country->addresses()->create(['city' => 'Paris']); - $city2 = $country->addresses()->create(['city' => 'Nice']); - $city3 = $country->addresses()->create(['city' => 'Lyon']); + $city1 = $country->addresses()->create(['city' => 'Paris']); + $city2 = $country->addresses()->create(['city' => 'Nice']); + $city3 = $country->addresses()->create(['city' => 'Lyon']); $city2->delete(); @@ -847,8 +849,8 @@ public function testNestedEmbedsManyDelete() public function testNestedMixedEmbedsDelete() { - $user = User::create(['name' => 'John Doe']); - $father = $user->father()->create(['name' => 'Mark Doe']); + $user = User::create(['name' => 'John Doe']); + $father = $user->father()->create(['name' => 'Mark Doe']); $country1 = $father->addresses()->create(['country' => 'France']); $country2 = $father->addresses()->create(['country' => 'Belgium']); @@ -864,7 +866,7 @@ public function testNestedMixedEmbedsDelete() public function testDoubleAssociate() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = new Address(['city' => 'Paris']); $user->addresses()->associate($address); @@ -885,14 +887,14 @@ public function testDoubleAssociate() public function testSaveEmptyModel() { $user = User::create(['name' => 'John Doe']); - $user->addresses()->save(new Address); + $user->addresses()->save(new Address()); $this->assertNotNull($user->addresses); $this->assertEquals(1, $user->addresses()->count()); } public function testIncrementEmbedded() { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $address = $user->addresses()->create(['city' => 'New York', 'visited' => 5]); $address->increment('visited'); @@ -902,7 +904,7 @@ public function testIncrementEmbedded() $user = User::where('name', 'John Doe')->first(); $this->assertEquals(6, $user->addresses()->first()->visited); - $user = User::where('name', 'John Doe')->first(); + $user = User::where('name', 'John Doe')->first(); $address = $user->addresses()->first(); $address->decrement('visited'); diff --git a/tests/HybridRelationsTest.php b/tests/HybridRelationsTest.php index 35514fe0d..5dc6b307b 100644 --- a/tests/HybridRelationsTest.php +++ b/tests/HybridRelationsTest.php @@ -4,7 +4,6 @@ namespace MongoDB\Laravel\Tests; -use Illuminate\Database\Connection; use Illuminate\Database\MySqlConnection; use Illuminate\Support\Facades\DB; use MongoDB\Laravel\Tests\Models\Book; @@ -21,7 +20,6 @@ public function setUp(): void { parent::setUp(); - /** @var Connection */ try { DB::connection('mysql')->select('SELECT 1'); } catch (PDOException) { @@ -42,7 +40,7 @@ public function tearDown(): void public function testMysqlRelations() { - $user = new MysqlUser; + $user = new MysqlUser(); $this->assertInstanceOf(MysqlUser::class, $user); $this->assertInstanceOf(MySqlConnection::class, $user->getConnection()); @@ -72,7 +70,7 @@ public function testMysqlRelations() $this->assertEquals('John Doe', $role->mysqlUser->name); // MongoDB User - $user = new User; + $user = new User(); $user->name = 'John Doe'; $user->save(); @@ -99,8 +97,8 @@ public function testMysqlRelations() public function testHybridWhereHas() { - $user = new MysqlUser; - $otherUser = new MysqlUser; + $user = new MysqlUser(); + $otherUser = new MysqlUser(); $this->assertInstanceOf(MysqlUser::class, $user); $this->assertInstanceOf(MySqlConnection::class, $user->getConnection()); $this->assertInstanceOf(MysqlUser::class, $otherUser); @@ -108,11 +106,11 @@ public function testHybridWhereHas() //MySql User $user->name = 'John Doe'; - $user->id = 2; + $user->id = 2; $user->save(); // Other user $otherUser->name = 'Other User'; - $otherUser->id = 3; + $otherUser->id = 3; $otherUser->save(); // Make sure they are created $this->assertIsInt($user->id); @@ -153,8 +151,8 @@ public function testHybridWhereHas() public function testHybridWith() { - $user = new MysqlUser; - $otherUser = new MysqlUser; + $user = new MysqlUser(); + $otherUser = new MysqlUser(); $this->assertInstanceOf(MysqlUser::class, $user); $this->assertInstanceOf(MySqlConnection::class, $user->getConnection()); $this->assertInstanceOf(MysqlUser::class, $otherUser); @@ -162,11 +160,11 @@ public function testHybridWith() //MySql User $user->name = 'John Doe'; - $user->id = 2; + $user->id = 2; $user->save(); // Other user $otherUser->name = 'Other User'; - $otherUser->id = 3; + $otherUser->id = 3; $otherUser->save(); // Make sure they are created $this->assertIsInt($user->id); diff --git a/tests/ModelTest.php b/tests/ModelTest.php index d592228ec..44e24b699 100644 --- a/tests/ModelTest.php +++ b/tests/ModelTest.php @@ -6,6 +6,7 @@ use Carbon\Carbon; use DateTime; +use Generator; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Facades\Date; @@ -26,6 +27,16 @@ use MongoDB\Laravel\Tests\Models\Soft; use MongoDB\Laravel\Tests\Models\User; +use function abs; +use function array_keys; +use function array_merge; +use function get_debug_type; +use function hex2bin; +use function sleep; +use function sort; +use function strlen; +use function time; + class ModelTest extends TestCase { public function tearDown(): void @@ -39,7 +50,7 @@ public function tearDown(): void public function testNewModel(): void { - $user = new User; + $user = new User(); $this->assertInstanceOf(Model::class, $user); $this->assertInstanceOf(Connection::class, $user->getConnection()); $this->assertFalse($user->exists); @@ -49,10 +60,10 @@ public function testNewModel(): void public function testInsert(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); @@ -74,17 +85,17 @@ public function testInsert(): void public function testUpdate(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); $raw = $user->getAttributes(); $this->assertInstanceOf(ObjectID::class, $raw['_id']); - /** @var User $check */ $check = User::find($user->_id); + $this->assertInstanceOf(User::class, $check); $check->age = 36; $check->save(); @@ -107,11 +118,11 @@ public function testUpdate(): void public function testManualStringId(): void { - $user = new User; - $user->_id = '4af9f23d8ead0e1d32000000'; - $user->name = 'John Doe'; + $user = new User(); + $user->_id = '4af9f23d8ead0e1d32000000'; + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); $this->assertTrue($user->exists); @@ -120,11 +131,11 @@ public function testManualStringId(): void $raw = $user->getAttributes(); $this->assertInstanceOf(ObjectID::class, $raw['_id']); - $user = new User; - $user->_id = 'customId'; - $user->name = 'John Doe'; + $user = new User(); + $user->_id = 'customId'; + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); $this->assertTrue($user->exists); @@ -136,11 +147,11 @@ public function testManualStringId(): void public function testManualIntId(): void { - $user = new User; - $user->_id = 1; - $user->name = 'John Doe'; + $user = new User(); + $user->_id = 1; + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); $this->assertTrue($user->exists); @@ -152,10 +163,10 @@ public function testManualIntId(): void public function testDelete(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); $this->assertTrue($user->exists); @@ -168,16 +179,16 @@ public function testDelete(): void public function testAll(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); - $user = new User; - $user->name = 'Jane Doe'; + $user = new User(); + $user->name = 'Jane Doe'; $user->title = 'user'; - $user->age = 32; + $user->age = 32; $user->save(); $all = User::all(); @@ -189,14 +200,14 @@ public function testAll(): void public function testFind(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); - /** @var User $check */ $check = User::find($user->_id); + $this->assertInstanceOf(User::class, $check); $this->assertInstanceOf(Model::class, $check); $this->assertTrue($check->exists); @@ -226,8 +237,8 @@ public function testFirst(): void ['name' => 'Jane Doe'], ]); - /** @var User $user */ $user = User::first(); + $this->assertInstanceOf(User::class, $user); $this->assertInstanceOf(Model::class, $user); $this->assertEquals('John Doe', $user->name); } @@ -253,24 +264,24 @@ public function testFindOrFail(): void public function testCreate(): void { - /** @var User $user */ $user = User::create(['name' => 'Jane Poe']); + $this->assertInstanceOf(User::class, $user); $this->assertInstanceOf(Model::class, $user); $this->assertTrue($user->exists); $this->assertEquals('Jane Poe', $user->name); - /** @var User $check */ $check = User::where('name', 'Jane Poe')->first(); + $this->assertInstanceOf(User::class, $check); $this->assertEquals($user->_id, $check->_id); } public function testDestroy(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); User::destroy((string) $user->_id); @@ -280,18 +291,18 @@ public function testDestroy(): void public function testTouch(): void { - $user = new User; - $user->name = 'John Doe'; + $user = new User(); + $user->name = 'John Doe'; $user->title = 'admin'; - $user->age = 35; + $user->age = 35; $user->save(); $old = $user->updated_at; sleep(1); $user->touch(); - /** @var User $check */ $check = User::find($user->_id); + $this->assertInstanceOf(User::class, $check); $this->assertNotEquals($old, $check->updated_at); } @@ -303,40 +314,38 @@ public function testSoftDelete(): void $this->assertEquals(2, Soft::count()); - /** @var Soft $user */ - $user = Soft::where('name', 'John Doe')->first(); - $this->assertTrue($user->exists); - $this->assertFalse($user->trashed()); - $this->assertNull($user->deleted_at); + $object = Soft::where('name', 'John Doe')->first(); + $this->assertInstanceOf(Soft::class, $object); + $this->assertTrue($object->exists); + $this->assertFalse($object->trashed()); + $this->assertNull($object->deleted_at); - $user->delete(); - $this->assertTrue($user->trashed()); - $this->assertNotNull($user->deleted_at); + $object->delete(); + $this->assertTrue($object->trashed()); + $this->assertNotNull($object->deleted_at); - $user = Soft::where('name', 'John Doe')->first(); - $this->assertNull($user); + $object = Soft::where('name', 'John Doe')->first(); + $this->assertNull($object); $this->assertEquals(1, Soft::count()); $this->assertEquals(2, Soft::withTrashed()->count()); - $user = Soft::withTrashed()->where('name', 'John Doe')->first(); - $this->assertNotNull($user); - $this->assertInstanceOf(Carbon::class, $user->deleted_at); - $this->assertTrue($user->trashed()); + $object = Soft::withTrashed()->where('name', 'John Doe')->first(); + $this->assertNotNull($object); + $this->assertInstanceOf(Carbon::class, $object->deleted_at); + $this->assertTrue($object->trashed()); - $user->restore(); + $object->restore(); $this->assertEquals(2, Soft::count()); } - /** - * @dataProvider provideId - */ + /** @dataProvider provideId */ public function testPrimaryKey(string $model, $id, $expected, bool $expectedFound): void { $model::truncate(); $expectedType = get_debug_type($expected); - $document = new $model; + $document = new $model(); $this->assertEquals('_id', $document->getKeyName()); $document->_id = $id; @@ -425,17 +434,17 @@ public static function provideId(): iterable public function testCustomPrimaryKey(): void { - $book = new Book; + $book = new Book(); $this->assertEquals('title', $book->getKeyName()); - $book->title = 'A Game of Thrones'; + $book->title = 'A Game of Thrones'; $book->author = 'George R. R. Martin'; $book->save(); $this->assertEquals('A Game of Thrones', $book->getKey()); - /** @var Book $check */ $check = Book::find('A Game of Thrones'); + $this->assertInstanceOf(Book::class, $check); $this->assertEquals('title', $check->getKeyName()); $this->assertEquals('A Game of Thrones', $check->getKey()); $this->assertEquals('A Game of Thrones', $check->title); @@ -457,7 +466,7 @@ public function testToArray(): void $item = Item::create(['name' => 'fork', 'type' => 'sharp']); $array = $item->toArray(); - $keys = array_keys($array); + $keys = array_keys($array); sort($keys); $this->assertEquals(['_id', 'created_at', 'name', 'type', 'updated_at'], $keys); $this->assertIsString($array['created_at']); @@ -651,14 +660,13 @@ public function testDates(): void ->getTimestamp(), $item->created_at->getTimestamp()); $this->assertLessThan(2, abs(time() - $item->created_at->getTimestamp())); - // test default date format for json output - /** @var Item $item */ $item = Item::create(['name' => 'sword']); + $this->assertInstanceOf(Item::class, $item); $json = $item->toArray(); $this->assertEquals($item->created_at->toISOString(), $json['created_at']); } - public static function provideDate(): \Generator + public static function provideDate(): Generator { yield 'int timestamp' => [time()]; yield 'Carbon date' => [Date::now()]; @@ -674,14 +682,12 @@ public static function provideDate(): \Generator yield 'DateTime date, time and ms before unix epoch' => [new DateTime('1965-08-08 04.08.37.324')]; } - /** - * @dataProvider provideDate - */ + /** @dataProvider provideDate */ public function testDateInputs($date): void { - /** @var User $user */ // Test with create and standard property $user = User::create(['name' => 'Jane Doe', 'birthday' => $date]); + $this->assertInstanceOf(User::class, $user); $this->assertInstanceOf(Carbon::class, $user->birthday); //Test with setAttribute and standard property @@ -747,8 +753,8 @@ public function testCarbonDateMockingWorks() public function testIdAttribute(): void { - /** @var User $user */ $user = User::create(['name' => 'John Doe']); + $this->assertInstanceOf(User::class, $user); $this->assertEquals($user->id, $user->_id); $user = User::create(['id' => 'custom_id', 'name' => 'John Doe']); @@ -757,8 +763,8 @@ public function testIdAttribute(): void public function testPushPull(): void { - /** @var User $user */ $user = User::create(['name' => 'John Doe']); + $this->assertInstanceOf(User::class, $user); $user->push('tags', 'tag1'); $user->push('tags', ['tag1', 'tag2']); @@ -826,18 +832,16 @@ public function testDotNotation(): void $this->assertEquals('Paris', $user->{'address.city'}); // Fill - $user->fill([ - 'address.city' => 'Strasbourg', - ]); + $user->fill(['address.city' => 'Strasbourg']); $this->assertEquals('Strasbourg', $user['address.city']); } public function testAttributeMutator(): void { - $username = 'JaneDoe'; + $username = 'JaneDoe'; $usernameSlug = Str::slug($username); - $user = User::create([ + $user = User::create([ 'name' => 'Jane Doe', 'username' => $username, ]); @@ -852,15 +856,13 @@ public function testAttributeMutator(): void public function testMultipleLevelDotNotation(): void { - /** @var Book $book */ $book = Book::create([ 'title' => 'A Game of Thrones', 'chapters' => [ - 'one' => [ - 'title' => 'The first chapter', - ], + 'one' => ['title' => 'The first chapter'], ], ]); + $this->assertInstanceOf(Book::class, $book); $this->assertEquals(['one' => ['title' => 'The first chapter']], $book->chapters); $this->assertEquals(['title' => 'The first chapter'], $book['chapters.one']); @@ -927,18 +929,17 @@ public function testFirstOrCreate(): void { $name = 'Jane Poe'; - /** @var User $user */ $user = User::where('name', $name)->first(); $this->assertNull($user); - /** @var User $user */ - $user = User::firstOrCreate(compact('name')); + $user = User::firstOrCreate(['name' => $name]); + $this->assertInstanceOf(User::class, $user); $this->assertInstanceOf(Model::class, $user); $this->assertTrue($user->exists); $this->assertEquals($name, $user->name); - /** @var User $check */ $check = User::where('name', $name)->first(); + $this->assertInstanceOf(User::class, $check); $this->assertEquals($user->_id, $check->_id); } @@ -946,13 +947,13 @@ public function testEnumCast(): void { $name = 'John Member'; - $user = new User(); - $user->name = $name; + $user = new User(); + $user->name = $name; $user->member_status = MemberStatus::Member; $user->save(); - /** @var User $check */ $check = User::where('name', $name)->first(); + $this->assertInstanceOf(User::class, $check); $this->assertSame(MemberStatus::Member->value, $check->getRawOriginal('member_status')); $this->assertSame(MemberStatus::Member, $check->member_status); } diff --git a/tests/Models/Address.php b/tests/Models/Address.php index 2aadabd6c..b827dc85f 100644 --- a/tests/Models/Address.php +++ b/tests/Models/Address.php @@ -9,7 +9,7 @@ class Address extends Eloquent { - protected $connection = 'mongodb'; + protected $connection = 'mongodb'; protected static $unguarded = true; public function addresses(): EmbedsMany diff --git a/tests/Models/Birthday.php b/tests/Models/Birthday.php index 0252c9a20..4131357f6 100644 --- a/tests/Models/Birthday.php +++ b/tests/Models/Birthday.php @@ -7,8 +7,6 @@ use MongoDB\Laravel\Eloquent\Model as Eloquent; /** - * Class Birthday. - * * @property string $name * @property string $birthday * @property string $time @@ -17,9 +15,7 @@ class Birthday extends Eloquent { protected $connection = 'mongodb'; protected $collection = 'birthday'; - protected $fillable = ['name', 'birthday']; + protected $fillable = ['name', 'birthday']; - protected $casts = [ - 'birthday' => 'datetime', - ]; + protected $casts = ['birthday' => 'datetime']; } diff --git a/tests/Models/Book.php b/tests/Models/Book.php index 9439ead3c..e196ec4b3 100644 --- a/tests/Models/Book.php +++ b/tests/Models/Book.php @@ -8,18 +8,16 @@ use MongoDB\Laravel\Eloquent\Model as Eloquent; /** - * Class Book. - * * @property string $title * @property string $author * @property array $chapters */ class Book extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'books'; + protected $connection = 'mongodb'; + protected $collection = 'books'; protected static $unguarded = true; - protected $primaryKey = 'title'; + protected $primaryKey = 'title'; public function author(): BelongsTo { diff --git a/tests/Models/CastBinaryUuid.php b/tests/Models/CastBinaryUuid.php index a872054d3..3d8b82941 100644 --- a/tests/Models/CastBinaryUuid.php +++ b/tests/Models/CastBinaryUuid.php @@ -9,9 +9,9 @@ class CastBinaryUuid extends Eloquent { - protected $connection = 'mongodb'; + protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = [ + protected $casts = [ 'uuid' => BinaryUuid::class, ]; } diff --git a/tests/Models/CastObjectId.php b/tests/Models/CastObjectId.php index 8daca90df..2f4e7f5d5 100644 --- a/tests/Models/CastObjectId.php +++ b/tests/Models/CastObjectId.php @@ -9,9 +9,9 @@ class CastObjectId extends Eloquent { - protected $connection = 'mongodb'; + protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = [ + protected $casts = [ 'oid' => ObjectId::class, ]; } diff --git a/tests/Models/Client.php b/tests/Models/Client.php index 2c5f17a68..7ee8cec4a 100644 --- a/tests/Models/Client.php +++ b/tests/Models/Client.php @@ -11,8 +11,8 @@ class Client extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'clients'; + protected $connection = 'mongodb'; + protected $collection = 'clients'; protected static $unguarded = true; public function users(): BelongsToMany diff --git a/tests/Models/Group.php b/tests/Models/Group.php index 4fba28493..eda017a03 100644 --- a/tests/Models/Group.php +++ b/tests/Models/Group.php @@ -9,8 +9,8 @@ class Group extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'groups'; + protected $connection = 'mongodb'; + protected $collection = 'groups'; protected static $unguarded = true; public function users(): BelongsToMany diff --git a/tests/Models/Guarded.php b/tests/Models/Guarded.php index d396d4f13..540d68996 100644 --- a/tests/Models/Guarded.php +++ b/tests/Models/Guarded.php @@ -10,5 +10,5 @@ class Guarded extends Eloquent { protected $connection = 'mongodb'; protected $collection = 'guarded'; - protected $guarded = ['foobar', 'level1->level2']; + protected $guarded = ['foobar', 'level1->level2']; } diff --git a/tests/Models/IdIsBinaryUuid.php b/tests/Models/IdIsBinaryUuid.php index f16e83a73..56ae89dca 100644 --- a/tests/Models/IdIsBinaryUuid.php +++ b/tests/Models/IdIsBinaryUuid.php @@ -9,9 +9,9 @@ class IdIsBinaryUuid extends Eloquent { - protected $connection = 'mongodb'; + protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = [ + protected $casts = [ '_id' => BinaryUuid::class, ]; } diff --git a/tests/Models/IdIsInt.php b/tests/Models/IdIsInt.php index ae3ad26e0..1243fc217 100644 --- a/tests/Models/IdIsInt.php +++ b/tests/Models/IdIsInt.php @@ -8,10 +8,8 @@ class IdIsInt extends Eloquent { - protected $keyType = 'int'; - protected $connection = 'mongodb'; + protected $keyType = 'int'; + protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = [ - '_id' => 'int', - ]; + protected $casts = ['_id' => 'int']; } diff --git a/tests/Models/IdIsString.php b/tests/Models/IdIsString.php index 9f74fc941..ed89803ca 100644 --- a/tests/Models/IdIsString.php +++ b/tests/Models/IdIsString.php @@ -8,9 +8,7 @@ class IdIsString extends Eloquent { - protected $connection = 'mongodb'; + protected $connection = 'mongodb'; protected static $unguarded = true; - protected $casts = [ - '_id' => 'string', - ]; + protected $casts = ['_id' => 'string']; } diff --git a/tests/Models/Item.php b/tests/Models/Item.php index 5b54f63d5..8aafc1446 100644 --- a/tests/Models/Item.php +++ b/tests/Models/Item.php @@ -4,19 +4,16 @@ namespace MongoDB\Laravel\Tests\Models; +use Carbon\Carbon; use Illuminate\Database\Eloquent\Relations\BelongsTo; use MongoDB\Laravel\Eloquent\Builder; use MongoDB\Laravel\Eloquent\Model as Eloquent; -/** - * Class Item. - * - * @property \Carbon\Carbon $created_at - */ +/** @property Carbon $created_at */ class Item extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'items'; + protected $connection = 'mongodb'; + protected $collection = 'items'; protected static $unguarded = true; public function user(): BelongsTo diff --git a/tests/Models/Location.php b/tests/Models/Location.php index 623699d55..e273fa455 100644 --- a/tests/Models/Location.php +++ b/tests/Models/Location.php @@ -8,7 +8,7 @@ class Location extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'locations'; + protected $connection = 'mongodb'; + protected $collection = 'locations'; protected static $unguarded = true; } diff --git a/tests/Models/MemberStatus.php b/tests/Models/MemberStatus.php index 5877125f0..9f14ce6e5 100644 --- a/tests/Models/MemberStatus.php +++ b/tests/Models/MemberStatus.php @@ -1,5 +1,7 @@ hasTable('books')) { - Schema::connection('mysql')->create('books', function (Blueprint $table) { - $table->string('title'); - $table->string('author_id')->nullable(); - $table->integer('mysql_user_id')->unsigned()->nullable(); - $table->timestamps(); - }); + if ($schema->hasTable('books')) { + return; } + + Schema::connection('mysql')->create('books', function (Blueprint $table) { + $table->string('title'); + $table->string('author_id')->nullable(); + $table->integer('mysql_user_id')->unsigned()->nullable(); + $table->timestamps(); + }); } } diff --git a/tests/Models/MysqlRole.php b/tests/Models/MysqlRole.php index 573a4503a..e4f293313 100644 --- a/tests/Models/MysqlRole.php +++ b/tests/Models/MysqlRole.php @@ -7,15 +7,18 @@ use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Schema\Blueprint; +use Illuminate\Database\Schema\MySqlBuilder; use Illuminate\Support\Facades\Schema; use MongoDB\Laravel\Eloquent\HybridRelations; +use function assert; + class MysqlRole extends EloquentModel { use HybridRelations; - protected $connection = 'mysql'; - protected $table = 'roles'; + protected $connection = 'mysql'; + protected $table = 'roles'; protected static $unguarded = true; public function user(): BelongsTo @@ -33,15 +36,17 @@ public function mysqlUser(): BelongsTo */ public static function executeSchema() { - /** @var \Illuminate\Database\Schema\MySqlBuilder $schema */ $schema = Schema::connection('mysql'); + assert($schema instanceof MySqlBuilder); - if (! $schema->hasTable('roles')) { - Schema::connection('mysql')->create('roles', function (Blueprint $table) { - $table->string('type'); - $table->string('user_id'); - $table->timestamps(); - }); + if ($schema->hasTable('roles')) { + return; } + + Schema::connection('mysql')->create('roles', function (Blueprint $table) { + $table->string('type'); + $table->string('user_id'); + $table->timestamps(); + }); } } diff --git a/tests/Models/MysqlUser.php b/tests/Models/MysqlUser.php index e25d06f51..c16a14220 100644 --- a/tests/Models/MysqlUser.php +++ b/tests/Models/MysqlUser.php @@ -12,12 +12,14 @@ use Illuminate\Support\Facades\Schema; use MongoDB\Laravel\Eloquent\HybridRelations; +use function assert; + class MysqlUser extends EloquentModel { use HybridRelations; - protected $connection = 'mysql'; - protected $table = 'users'; + protected $connection = 'mysql'; + protected $table = 'users'; protected static $unguarded = true; public function books(): HasMany @@ -40,15 +42,17 @@ public function mysqlBooks(): HasMany */ public static function executeSchema(): void { - /** @var MySqlBuilder $schema */ $schema = Schema::connection('mysql'); + assert($schema instanceof MySqlBuilder); - if (! $schema->hasTable('users')) { - Schema::connection('mysql')->create('users', function (Blueprint $table) { - $table->increments('id'); - $table->string('name'); - $table->timestamps(); - }); + if ($schema->hasTable('users')) { + return; } + + Schema::connection('mysql')->create('users', function (Blueprint $table) { + $table->increments('id'); + $table->string('name'); + $table->timestamps(); + }); } } diff --git a/tests/Models/Photo.php b/tests/Models/Photo.php index 2f584bd63..dbb92b0ff 100644 --- a/tests/Models/Photo.php +++ b/tests/Models/Photo.php @@ -9,8 +9,8 @@ class Photo extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'photos'; + protected $connection = 'mongodb'; + protected $collection = 'photos'; protected static $unguarded = true; public function hasImage(): MorphTo diff --git a/tests/Models/Role.php b/tests/Models/Role.php index d778a7d8a..2c191ac1b 100644 --- a/tests/Models/Role.php +++ b/tests/Models/Role.php @@ -9,8 +9,8 @@ class Role extends Eloquent { - protected $connection = 'mongodb'; - protected $collection = 'roles'; + protected $connection = 'mongodb'; + protected $collection = 'roles'; protected static $unguarded = true; public function user(): BelongsTo diff --git a/tests/Models/Scoped.php b/tests/Models/Scoped.php index 3a5997f4e..d728b6bec 100644 --- a/tests/Models/Scoped.php +++ b/tests/Models/Scoped.php @@ -11,7 +11,7 @@ class Scoped extends Eloquent { protected $connection = 'mongodb'; protected $collection = 'scoped'; - protected $fillable = ['name', 'favorite']; + protected $fillable = ['name', 'favorite']; protected static function boot() { diff --git a/tests/Models/Soft.php b/tests/Models/Soft.php index 7a5d25704..31b80908a 100644 --- a/tests/Models/Soft.php +++ b/tests/Models/Soft.php @@ -4,25 +4,22 @@ namespace MongoDB\Laravel\Tests\Models; +use Carbon\Carbon; use MongoDB\Laravel\Eloquent\Builder; use MongoDB\Laravel\Eloquent\MassPrunable; use MongoDB\Laravel\Eloquent\Model as Eloquent; use MongoDB\Laravel\Eloquent\SoftDeletes; -/** - * Class Soft. - * - * @property \Carbon\Carbon $deleted_at - */ +/** @property Carbon $deleted_at */ class Soft extends Eloquent { use SoftDeletes; use MassPrunable; - protected $connection = 'mongodb'; - protected $collection = 'soft'; + protected $connection = 'mongodb'; + protected $collection = 'soft'; protected static $unguarded = true; - protected $casts = ['deleted_at' => 'datetime']; + protected $casts = ['deleted_at' => 'datetime']; public function prunable(): Builder { diff --git a/tests/Models/User.php b/tests/Models/User.php index 57319f84a..945d8b074 100644 --- a/tests/Models/User.php +++ b/tests/Models/User.php @@ -4,6 +4,7 @@ namespace MongoDB\Laravel\Tests\Models; +use Carbon\Carbon; use DateTimeInterface; use Illuminate\Auth\Authenticatable; use Illuminate\Auth\Passwords\CanResetPassword; @@ -18,16 +19,14 @@ use MongoDB\Laravel\Eloquent\Model as Eloquent; /** - * Class User. - * * @property string $_id * @property string $name * @property string $email * @property string $title * @property int $age - * @property \Carbon\Carbon $birthday - * @property \Carbon\Carbon $created_at - * @property \Carbon\Carbon $updated_at + * @property Carbon $birthday + * @property Carbon $created_at + * @property Carbon $updated_at * @property string $username * @property MemberStatus member_status */ @@ -39,8 +38,8 @@ class User extends Eloquent implements AuthenticatableContract, CanResetPassword use Notifiable; use MassPrunable; - protected $connection = 'mongodb'; - protected $casts = [ + protected $connection = 'mongodb'; + protected $casts = [ 'birthday' => 'datetime', 'entry.date' => 'datetime', 'member_status' => MemberStatus::class, diff --git a/tests/Query/BuilderTest.php b/tests/Query/BuilderTest.php index b1484a6d9..556239afc 100644 --- a/tests/Query/BuilderTest.php +++ b/tests/Query/BuilderTest.php @@ -4,9 +4,14 @@ namespace MongoDB\Laravel\Tests\Query; +use ArgumentCountError; +use BadMethodCallException; +use Closure; use DateTimeImmutable; use Illuminate\Database\Eloquent\Collection; use Illuminate\Tests\Database\DatabaseQueryBuilderTest; +use InvalidArgumentException; +use LogicException; use Mockery as m; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -15,13 +20,16 @@ use MongoDB\Laravel\Query\Grammar; use MongoDB\Laravel\Query\Processor; use PHPUnit\Framework\TestCase; +use stdClass; + +use function collect; +use function now; +use function var_export; class BuilderTest extends TestCase { - /** - * @dataProvider provideQueryBuilderToMql - */ - public function testMql(array $expected, \Closure $build): void + /** @dataProvider provideQueryBuilderToMql */ + public function testMql(array $expected, Closure $build): void { $builder = $build(self::getBuilder()); $this->assertInstanceOf(Builder::class, $builder); @@ -31,6 +39,7 @@ public function testMql(array $expected, \Closure $build): void if (isset($expected['find'][1])) { $expected['find'][1]['typeMap'] = ['root' => 'array', 'document' => 'array']; } + if (isset($expected['aggregate'][1])) { $expected['aggregate'][1]['typeMap'] = ['root' => 'array', 'document' => 'array']; } @@ -82,13 +91,17 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'where with single array of conditions' => [ - ['find' => [ - ['$and' => [ - ['foo' => 1], - ['bar' => 2], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$and' => [ + ['foo' => 1], + ['bar' => 2], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder->where(['foo' => 1, 'bar' => 2]), ]; @@ -111,13 +124,17 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'orWhereIn' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['id' => ['$in' => [1, 2, 3]]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + ['id' => ['$in' => [1, 2, 3]]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder->where('id', '=', 1) ->orWhereIn('id', [1, 2, 3]), ]; @@ -129,13 +146,17 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'orWhereNotIn' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['id' => ['$nin' => [1, 2, 3]]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + ['id' => ['$nin' => [1, 2, 3]]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder->where('id', '=', 1) ->orWhereNotIn('id', [1, 2, 3]), ]; @@ -152,13 +173,17 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'where accepts $ in operators' => [ - ['find' => [ - ['$or' => [ - ['foo' => ['$type' => 2]], - ['foo' => ['$type' => 4]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['foo' => ['$type' => 2]], + ['foo' => ['$type' => 4]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('foo', '$type', 2) ->orWhere('foo', '$type', 4), @@ -166,13 +191,17 @@ public static function provideQueryBuilderToMql(): iterable /** @see DatabaseQueryBuilderTest::testBasicWhereNot() */ yield 'whereNot (multiple)' => [ - ['find' => [ - ['$and' => [ - ['$not' => ['name' => 'foo']], - ['$not' => ['name' => ['$ne' => 'bar']]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$and' => [ + ['$not' => ['name' => 'foo']], + ['$not' => ['name' => ['$ne' => 'bar']]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot('name', 'foo') ->whereNot('name', '<>', 'bar'), @@ -180,13 +209,17 @@ public static function provideQueryBuilderToMql(): iterable /** @see DatabaseQueryBuilderTest::testBasicOrWheres() */ yield 'where orWhere' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['email' => 'foo'], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + ['email' => 'foo'], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhere('email', '=', 'foo'), @@ -194,26 +227,34 @@ public static function provideQueryBuilderToMql(): iterable /** @see DatabaseQueryBuilderTest::testBasicOrWhereNot() */ yield 'orWhereNot' => [ - ['find' => [ - ['$or' => [ - ['$not' => ['name' => 'foo']], - ['$not' => ['name' => ['$ne' => 'bar']]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['$not' => ['name' => 'foo']], + ['$not' => ['name' => ['$ne' => 'bar']]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->orWhereNot('name', 'foo') ->orWhereNot('name', '<>', 'bar'), ]; yield 'whereNot orWhere' => [ - ['find' => [ - ['$or' => [ - ['$not' => ['name' => 'foo']], - ['name' => ['$ne' => 'bar']], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['$not' => ['name' => 'foo']], + ['name' => ['$ne' => 'bar']], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot('name', 'foo') ->orWhere('name', '<>', 'bar'), @@ -221,22 +262,28 @@ public static function provideQueryBuilderToMql(): iterable /** @see DatabaseQueryBuilderTest::testWhereNot() */ yield 'whereNot callable' => [ - ['find' => [ - ['$not' => ['name' => 'foo']], - [], // options - ]], + [ + 'find' => [ + ['$not' => ['name' => 'foo']], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot(fn (Builder $q) => $q->where('name', 'foo')), ]; yield 'where whereNot' => [ - ['find' => [ - ['$and' => [ - ['name' => 'bar'], - ['$not' => ['email' => 'foo']], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$and' => [ + ['name' => 'bar'], + ['$not' => ['email' => 'foo']], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('name', '=', 'bar') ->whereNot(function (Builder $q) { @@ -245,15 +292,19 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'whereNot (nested)' => [ - ['find' => [ - ['$not' => [ - '$and' => [ - ['name' => 'foo'], - ['$not' => ['email' => ['$ne' => 'bar']]], + [ + 'find' => [ + [ + '$not' => [ + '$and' => [ + ['name' => 'foo'], + ['$not' => ['email' => ['$ne' => 'bar']]], + ], + ], ], - ]], - [], // options - ]], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot(function (Builder $q) { $q->where('name', '=', 'foo') @@ -262,13 +313,17 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'orWhere orWhereNot' => [ - ['find' => [ - ['$or' => [ - ['name' => 'bar'], - ['$not' => ['email' => 'foo']], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['name' => 'bar'], + ['$not' => ['email' => 'foo']], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->orWhere('name', '=', 'bar') ->orWhereNot(function (Builder $q) { @@ -277,13 +332,17 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'where orWhereNot' => [ - ['find' => [ - ['$or' => [ - ['name' => 'bar'], - ['$not' => ['email' => 'foo']], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['name' => 'bar'], + ['$not' => ['email' => 'foo']], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('name', '=', 'bar') ->orWhereNot('email', '=', 'foo'), @@ -291,43 +350,55 @@ public static function provideQueryBuilderToMql(): iterable /** @see DatabaseQueryBuilderTest::testWhereNotWithArrayConditions() */ yield 'whereNot with arrays of single condition' => [ - ['find' => [ - ['$not' => [ - '$and' => [ - ['foo' => 1], - ['bar' => 2], + [ + 'find' => [ + [ + '$not' => [ + '$and' => [ + ['foo' => 1], + ['bar' => 2], + ], + ], ], - ]], - [], // options - ]], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot([['foo', 1], ['bar', 2]]), ]; yield 'whereNot with single array of conditions' => [ - ['find' => [ - ['$not' => [ - '$and' => [ - ['foo' => 1], - ['bar' => 2], + [ + 'find' => [ + [ + '$not' => [ + '$and' => [ + ['foo' => 1], + ['bar' => 2], + ], + ], ], - ]], - [], // options - ]], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot(['foo' => 1, 'bar' => 2]), ]; yield 'whereNot with arrays of single condition with operator' => [ - ['find' => [ - ['$not' => [ - '$and' => [ - ['foo' => 1], - ['bar' => ['$lt' => 2]], + [ + 'find' => [ + [ + '$not' => [ + '$and' => [ + ['foo' => 1], + ['bar' => ['$lt' => 2]], + ], + ], ], - ]], - [], // options - ]], + [], // options + ], + ], fn (Builder $builder) => $builder ->whereNot([ ['foo', 1], @@ -341,10 +412,19 @@ public static function provideQueryBuilderToMql(): iterable ]; yield 'where all nested operators' => [ - ['find' => [['tags' => ['$all' => [ - ['$elemMatch' => ['size' => 'M', 'num' => ['$gt' => 50]]], - ['$elemMatch' => ['num' => 100, 'color' => 'green']], - ]]], []]], + [ + 'find' => [ + [ + 'tags' => [ + '$all' => [ + ['$elemMatch' => ['size' => 'M', 'num' => ['$gt' => 50]]], + ['$elemMatch' => ['num' => 100, 'color' => 'green']], + ], + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->where('tags', 'all', [ ['$elemMatch' => ['size' => 'M', 'num' => ['$gt' => 50]]], ['$elemMatch' => ['num' => 100, 'color' => 'green']], @@ -445,10 +525,12 @@ function (Builder $builder) { /** @link https://www.mongodb.com/docs/manual/reference/method/cursor.sort/#text-score-metadata-sort */ yield 'orderBy array meta' => [ - ['find' => [ - ['$text' => ['$search' => 'operating']], - ['sort' => ['score' => ['$meta' => 'textScore']]], - ]], + [ + 'find' => [ + ['$text' => ['$search' => 'operating']], + ['sort' => ['score' => ['$meta' => 'textScore']]], + ], + ], fn (Builder $builder) => $builder ->where('$text', ['$search' => 'operating']) ->orderBy('score', ['$meta' => 'textScore']), @@ -467,10 +549,12 @@ function (Builder $builder) { $period = now()->toPeriod(now()->addMonth()); yield 'whereBetween CarbonPeriod' => [ - ['find' => [ - ['created_at' => ['$gte' => new UTCDateTime($period->start), '$lte' => new UTCDateTime($period->end)]], - [], // options - ]], + [ + 'find' => [ + ['created_at' => ['$gte' => new UTCDateTime($period->start), '$lte' => new UTCDateTime($period->end)]], + [], // options + ], + ], fn (Builder $builder) => $builder->whereBetween('created_at', $period), ]; @@ -481,13 +565,17 @@ function (Builder $builder) { /** @see DatabaseQueryBuilderTest::testOrWhereBetween() */ yield 'orWhereBetween array of numbers' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['id' => ['$gte' => 3, '$lte' => 5]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + ['id' => ['$gte' => 3, '$lte' => 5]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhereBetween('id', [3, 5]), @@ -495,86 +583,116 @@ function (Builder $builder) { /** @link https://www.mongodb.com/docs/manual/reference/bson-type-comparison-order/#arrays */ yield 'orWhereBetween nested array of numbers' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['id' => ['$gte' => [4], '$lte' => [6, 8]]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + ['id' => ['$gte' => [4], '$lte' => [6, 8]]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhereBetween('id', [[4], [6, 8]]), ]; yield 'orWhereBetween collection' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['id' => ['$gte' => 3, '$lte' => 4]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + ['id' => ['$gte' => 3, '$lte' => 4]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhereBetween('id', collect([3, 4])), ]; yield 'whereNotBetween array of numbers' => [ - ['find' => [ - ['$or' => [ - ['id' => ['$lte' => 1]], - ['id' => ['$gte' => 2]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => ['$lte' => 1]], + ['id' => ['$gte' => 2]], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder->whereNotBetween('id', [1, 2]), ]; /** @see DatabaseQueryBuilderTest::testOrWhereNotBetween() */ yield 'orWhereNotBetween array of numbers' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['$or' => [ - ['id' => ['$lte' => 3]], - ['id' => ['$gte' => 5]], - ]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + [ + '$or' => [ + ['id' => ['$lte' => 3]], + ['id' => ['$gte' => 5]], + ], + ], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhereNotBetween('id', [3, 5]), ]; yield 'orWhereNotBetween nested array of numbers' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['$or' => [ - ['id' => ['$lte' => [2, 3]]], - ['id' => ['$gte' => [5]]], - ]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + [ + '$or' => [ + ['id' => ['$lte' => [2, 3]]], + ['id' => ['$gte' => [5]]], + ], + ], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhereNotBetween('id', [[2, 3], [5]]), ]; yield 'orWhereNotBetween collection' => [ - ['find' => [ - ['$or' => [ - ['id' => 1], - ['$or' => [ - ['id' => ['$lte' => 3]], - ['id' => ['$gte' => 4]], - ]], - ]], - [], // options - ]], + [ + 'find' => [ + [ + '$or' => [ + ['id' => 1], + [ + '$or' => [ + ['id' => ['$lte' => 3]], + ['id' => ['$gte' => 4]], + ], + ], + ], + ], + [], // options + ], + ], fn (Builder $builder) => $builder ->where('id', '=', 1) ->orWhereNotBetween('id', collect([3, 4])), @@ -647,166 +765,292 @@ function (Builder $builder) { ]; yield 'where date' => [ - ['find' => [['created_at' => [ - '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), - '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), - ]], []]], + [ + 'find' => [ + [ + 'created_at' => [ + '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), + '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->whereDate('created_at', '2018-09-30'), ]; yield 'where date DateTimeImmutable' => [ - ['find' => [['created_at' => [ - '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), - '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), - ]], []]], + [ + 'find' => [ + [ + 'created_at' => [ + '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), + '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->whereDate('created_at', '=', new DateTimeImmutable('2018-09-30 15:00:00 +02:00')), ]; yield 'where date !=' => [ - ['find' => [['created_at' => [ - '$not' => [ - '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), - '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), + [ + 'find' => [ + [ + 'created_at' => [ + '$not' => [ + '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), + '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereDate('created_at', '!=', '2018-09-30'), ]; yield 'where date <' => [ - ['find' => [['created_at' => [ - '$lt' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), - ]], []]], + [ + 'find' => [ + [ + 'created_at' => [ + '$lt' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->whereDate('created_at', '<', '2018-09-30'), ]; yield 'where date >=' => [ - ['find' => [['created_at' => [ - '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), - ]], []]], + [ + 'find' => [ + [ + 'created_at' => [ + '$gte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 00:00:00.000 +00:00')), + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->whereDate('created_at', '>=', '2018-09-30'), ]; yield 'where date >' => [ - ['find' => [['created_at' => [ - '$gt' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), - ]], []]], + [ + 'find' => [ + [ + 'created_at' => [ + '$gt' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->whereDate('created_at', '>', '2018-09-30'), ]; yield 'where date <=' => [ - ['find' => [['created_at' => [ - '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), - ]], []]], + [ + 'find' => [ + [ + 'created_at' => [ + '$lte' => new UTCDateTime(new DateTimeImmutable('2018-09-30 23:59:59.999 +00:00')), + ], + ], + [], + ], + ], fn (Builder $builder) => $builder->whereDate('created_at', '<=', '2018-09-30'), ]; yield 'where day' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$dayOfMonth' => '$created_at'], - 5, + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$dayOfMonth' => '$created_at'], + 5, + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereDay('created_at', 5), ]; yield 'where day > string' => [ - ['find' => [['$expr' => [ - '$gt' => [ - ['$dayOfMonth' => '$created_at'], - 5, + [ + 'find' => [ + [ + '$expr' => [ + '$gt' => [ + ['$dayOfMonth' => '$created_at'], + 5, + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereDay('created_at', '>', '05'), ]; yield 'where month' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$month' => '$created_at'], - 10, + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$month' => '$created_at'], + 10, + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereMonth('created_at', 10), ]; yield 'where month > string' => [ - ['find' => [['$expr' => [ - '$gt' => [ - ['$month' => '$created_at'], - 5, + [ + 'find' => [ + [ + '$expr' => [ + '$gt' => [ + ['$month' => '$created_at'], + 5, + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereMonth('created_at', '>', '05'), ]; yield 'where year' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$year' => '$created_at'], - 2023, + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$year' => '$created_at'], + 2023, + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereYear('created_at', 2023), ]; yield 'where year > string' => [ - ['find' => [['$expr' => [ - '$gt' => [ - ['$year' => '$created_at'], - 2023, + [ + 'find' => [ + [ + '$expr' => [ + '$gt' => [ + ['$year' => '$created_at'], + 2023, + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereYear('created_at', '>', '2023'), ]; yield 'where time HH:MM:SS' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']], - '10:11:12', + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']], + '10:11:12', + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereTime('created_at', '10:11:12'), ]; yield 'where time HH:MM' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M']], - '10:11', + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M']], + '10:11', + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereTime('created_at', '10:11'), ]; yield 'where time HH' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$dateToString' => ['date' => '$created_at', 'format' => '%H']], - '10', + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$dateToString' => ['date' => '$created_at', 'format' => '%H']], + '10', + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereTime('created_at', '10'), ]; yield 'where time DateTime' => [ - ['find' => [['$expr' => [ - '$eq' => [ - ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']], - '10:11:12', + [ + 'find' => [ + [ + '$expr' => [ + '$eq' => [ + ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']], + '10:11:12', + ], + ], + ], + [], ], - ]], []]], - fn (Builder $builder) => $builder->whereTime('created_at', new \DateTimeImmutable('2023-08-22 10:11:12')), + ], + fn (Builder $builder) => $builder->whereTime('created_at', new DateTimeImmutable('2023-08-22 10:11:12')), ]; yield 'where time >' => [ - ['find' => [['$expr' => [ - '$gt' => [ - ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']], - '10:11:12', + [ + 'find' => [ + [ + '$expr' => [ + '$gt' => [ + ['$dateToString' => ['date' => '$created_at', 'format' => '%H:%M:%S']], + '10:11:12', + ], + ], + ], + [], ], - ]], []]], + ], fn (Builder $builder) => $builder->whereTime('created_at', '>', '10:11:12'), ]; @@ -862,18 +1106,18 @@ function (Builder $builder) { ]; yield 'groupBy' => [ - ['aggregate' => [ - [['$group' => ['_id' => ['foo' => '$foo'], 'foo' => ['$last' => '$foo']]]], - [], // options - ]], + [ + 'aggregate' => [ + [['$group' => ['_id' => ['foo' => '$foo'], 'foo' => ['$last' => '$foo']]]], + [], // options + ], + ], fn (Builder $builder) => $builder->groupBy('foo'), ]; } - /** - * @dataProvider provideExceptions - */ - public function testException($class, $message, \Closure $build): void + /** @dataProvider provideExceptions */ + public function testException($class, $message, Closure $build): void { $builder = self::getBuilder(); @@ -885,85 +1129,85 @@ public function testException($class, $message, \Closure $build): void public static function provideExceptions(): iterable { yield 'orderBy invalid direction' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Order direction must be "asc" or "desc"', fn (Builder $builder) => $builder->orderBy('_id', 'dasc'), ]; /** @see DatabaseQueryBuilderTest::testWhereBetweens */ yield 'whereBetween array too short' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Between $values must be a list with exactly two elements: [min, max]', fn (Builder $builder) => $builder->whereBetween('id', [1]), ]; yield 'whereBetween array too short (nested)' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Between $values must be a list with exactly two elements: [min, max]', fn (Builder $builder) => $builder->whereBetween('id', [[1, 2]]), ]; yield 'whereBetween array too long' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Between $values must be a list with exactly two elements: [min, max]', fn (Builder $builder) => $builder->whereBetween('id', [1, 2, 3]), ]; yield 'whereBetween collection too long' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Between $values must be a list with exactly two elements: [min, max]', fn (Builder $builder) => $builder->whereBetween('id', new Collection([1, 2, 3])), ]; yield 'whereBetween array is not a list' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Between $values must be a list with exactly two elements: [min, max]', fn (Builder $builder) => $builder->whereBetween('id', ['min' => 1, 'max' => 2]), ]; yield 'find with single string argument' => [ - \ArgumentCountError::class, + ArgumentCountError::class, 'Too few arguments to function MongoDB\Laravel\Query\Builder::where("foo"), 1 passed and at least 2 expected when the 1st is a string', fn (Builder $builder) => $builder->where('foo'), ]; yield 'where regex not starting with /' => [ - \LogicException::class, + LogicException::class, 'Missing expected starting delimiter in regular expression "^ac/me$", supported delimiters are: / # ~', fn (Builder $builder) => $builder->where('name', 'regex', '^ac/me$'), ]; yield 'where regex not ending with /' => [ - \LogicException::class, + LogicException::class, 'Missing expected ending delimiter "/" in regular expression "/foo#bar"', fn (Builder $builder) => $builder->where('name', 'regex', '/foo#bar'), ]; yield 'whereTime with invalid time' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Invalid time format, expected HH:MM:SS, HH:MM or HH, got "10:11:12:13"', fn (Builder $builder) => $builder->whereTime('created_at', '10:11:12:13'), ]; yield 'whereTime out of range' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Invalid time format, expected HH:MM:SS, HH:MM or HH, got "23:70"', fn (Builder $builder) => $builder->whereTime('created_at', '23:70'), ]; yield 'whereTime invalid type' => [ - \InvalidArgumentException::class, + InvalidArgumentException::class, 'Invalid time format, expected HH:MM:SS, HH:MM or HH, got "stdClass"', - fn (Builder $builder) => $builder->whereTime('created_at', new \stdClass()), + fn (Builder $builder) => $builder->whereTime('created_at', new stdClass()), ]; } /** @dataProvider getEloquentMethodsNotSupported */ - public function testEloquentMethodsNotSupported(\Closure $callback) + public function testEloquentMethodsNotSupported(Closure $callback) { $builder = self::getBuilder(); - $this->expectException(\BadMethodCallException::class); + $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('This method is not supported by MongoDB'); $callback($builder); @@ -1019,7 +1263,7 @@ public static function getEloquentMethodsNotSupported() private static function getBuilder(): Builder { $connection = m::mock(Connection::class); - $processor = m::mock(Processor::class); + $processor = m::mock(Processor::class); $connection->shouldReceive('getSession')->andReturn(null); $connection->shouldReceive('getQueryGrammar')->andReturn(new Grammar()); diff --git a/tests/QueryBuilderTest.php b/tests/QueryBuilderTest.php index eabdaca1c..4320e6a54 100644 --- a/tests/QueryBuilderTest.php +++ b/tests/QueryBuilderTest.php @@ -11,6 +11,7 @@ use Illuminate\Support\LazyCollection; use Illuminate\Support\Str; use Illuminate\Testing\Assert; +use InvalidArgumentException; use MongoDB\BSON\ObjectId; use MongoDB\BSON\Regex; use MongoDB\BSON\UTCDateTime; @@ -23,6 +24,14 @@ use MongoDB\Laravel\Query\Builder; use MongoDB\Laravel\Tests\Models\Item; use MongoDB\Laravel\Tests\Models\User; +use Stringable; + +use function count; +use function key; +use function md5; +use function sort; +use function strlen; +use function strtotime; class QueryBuilderTest extends TestCase { @@ -38,20 +47,20 @@ public function testDeleteWithId() ['name' => 'Jane Doe', 'age' => 20], ]); - $user_id = (string) $user; + $userId = (string) $user; DB::collection('items')->insert([ - ['name' => 'one thing', 'user_id' => $user_id], - ['name' => 'last thing', 'user_id' => $user_id], - ['name' => 'another thing', 'user_id' => $user_id], - ['name' => 'one more thing', 'user_id' => $user_id], + ['name' => 'one thing', 'user_id' => $userId], + ['name' => 'last thing', 'user_id' => $userId], + ['name' => 'another thing', 'user_id' => $userId], + ['name' => 'one more thing', 'user_id' => $userId], ]); $product = DB::collection('items')->first(); $pid = (string) ($product['_id']); - DB::collection('items')->where('user_id', $user_id)->delete($pid); + DB::collection('items')->where('user_id', $userId)->delete($pid); $this->assertEquals(3, DB::collection('items')->count()); @@ -59,9 +68,9 @@ public function testDeleteWithId() $pid = $product['_id']; - DB::collection('items')->where('user_id', $user_id)->delete($pid); + DB::collection('items')->where('user_id', $userId)->delete($pid); - DB::collection('items')->where('user_id', $user_id)->delete(md5('random-id')); + DB::collection('items')->where('user_id', $userId)->delete(md5('random-id')); $this->assertEquals(2, DB::collection('items')->count()); } @@ -215,14 +224,14 @@ public function testUpdateOperators() [ '$unset' => ['age' => 1], 'ageless' => true, - ] + ], ); DB::collection('users')->where('name', 'Jane Doe')->update( [ '$inc' => ['age' => 1], '$set' => ['pronoun' => 'she'], 'ageless' => false, - ] + ], ); $john = DB::collection('users')->where('name', 'John Doe')->first(); @@ -379,7 +388,7 @@ public function testPush() public function testPushRefuses2ndArgumentWhen1stIsAnArray() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('2nd argument of MongoDB\Laravel\Query\Builder::push() must be "null" when 1st argument is an array. Got "string" instead.'); DB::collection('users')->push(['tags' => 'tag1'], 'tag2'); @@ -584,7 +593,7 @@ public function testUpsert() DB::collection('items')->where('name', 'knife') ->update( ['amount' => 1], - ['upsert' => true] + ['upsert' => true], ); $this->assertEquals(1, DB::collection('items')->count()); @@ -592,7 +601,7 @@ public function testUpsert() Item::where('name', 'spoon') ->update( ['amount' => 1], - ['upsert' => true] + ['upsert' => true], ); $this->assertEquals(2, DB::collection('items')->count()); @@ -653,7 +662,7 @@ public function testDates() $this->assertEquals('John Doe', $user['name']); $start = new UTCDateTime(1000 * strtotime('1950-01-01 00:00:00')); - $stop = new UTCDateTime(1000 * strtotime('1981-01-01 00:00:00')); + $stop = new UTCDateTime(1000 * strtotime('1981-01-01 00:00:00')); $users = DB::collection('users')->whereBetween('birthday', [$start, $stop])->get(); $this->assertCount(2, $users); @@ -743,11 +752,11 @@ public function testOperators() $results = DB::collection('items')->where('tags', 'size', 4)->get(); $this->assertCount(1, $results); - $regex = new Regex('.*doe', 'i'); + $regex = new Regex('.*doe', 'i'); $results = DB::collection('users')->where('name', 'regex', $regex)->get(); $this->assertCount(2, $results); - $regex = new Regex('.*doe', 'i'); + $regex = new Regex('.*doe', 'i'); $results = DB::collection('users')->where('name', 'regexp', $regex)->get(); $this->assertCount(2, $results); @@ -900,12 +909,12 @@ public function testCursor() public function testStringableColumn() { DB::collection('users')->insert([ - ['name' => 'Jane Doe', 'age' => 36, 'birthday' => new UTCDateTime(new \DateTime('1987-01-01 00:00:00'))], - ['name' => 'John Doe', 'age' => 28, 'birthday' => new UTCDateTime(new \DateTime('1995-01-01 00:00:00'))], + ['name' => 'Jane Doe', 'age' => 36, 'birthday' => new UTCDateTime(new DateTime('1987-01-01 00:00:00'))], + ['name' => 'John Doe', 'age' => 28, 'birthday' => new UTCDateTime(new DateTime('1995-01-01 00:00:00'))], ]); $nameColumn = Str::of('name'); - $this->assertInstanceOf(\Stringable::class, $nameColumn, 'Ensure we are testing the feature with a Stringable instance'); + $this->assertInstanceOf(Stringable::class, $nameColumn, 'Ensure we are testing the feature with a Stringable instance'); $user = DB::collection('users')->where($nameColumn, 'John Doe')->first(); $this->assertEquals('John Doe', $user['name']); @@ -925,18 +934,17 @@ public function testStringableColumn() $user = DB::collection('users')->whereNotIn($nameColumn, ['John Doe'])->first(); $this->assertEquals('Jane Doe', $user['name']); - // whereBetween and whereNotBetween $ageColumn = Str::of('age'); + // whereBetween and whereNotBetween $user = DB::collection('users')->whereBetween($ageColumn, [30, 40])->first(); $this->assertEquals('Jane Doe', $user['name']); // whereBetween and whereNotBetween - $ageColumn = Str::of('age'); $user = DB::collection('users')->whereNotBetween($ageColumn, [30, 40])->first(); $this->assertEquals('John Doe', $user['name']); - // whereDate $birthdayColumn = Str::of('birthday'); + // whereDate $user = DB::collection('users')->whereDate($birthdayColumn, '1995-01-01')->first(); $this->assertEquals('John Doe', $user['name']); diff --git a/tests/QueryTest.php b/tests/QueryTest.php index 2a9bd4085..3d1df99f0 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -5,10 +5,13 @@ namespace MongoDB\Laravel\Tests; use DateTimeImmutable; +use LogicException; use MongoDB\Laravel\Tests\Models\Birthday; use MongoDB\Laravel\Tests\Models\Scoped; use MongoDB\Laravel\Tests\Models\User; +use function str; + class QueryTest extends TestCase { protected static $started = false; @@ -16,6 +19,7 @@ class QueryTest extends TestCase public function setUp(): void { parent::setUp(); + User::create(['name' => 'John Doe', 'age' => 35, 'title' => 'admin']); User::create(['name' => 'Jane Doe', 'age' => 33, 'title' => 'admin']); User::create(['name' => 'Harry Hoe', 'age' => 13, 'title' => 'user']); @@ -39,6 +43,7 @@ public function tearDown(): void User::truncate(); Scoped::truncate(); Birthday::truncate(); + parent::tearDown(); } @@ -422,7 +427,7 @@ public function testWhereRaw(): void $where1 = ['age' => ['$gt' => 30, '$lte' => 35]]; $where2 = ['age' => ['$gt' => 35, '$lt' => 40]]; - $users = User::whereRaw($where1)->orWhereRaw($where2)->get(); + $users = User::whereRaw($where1)->orWhereRaw($where2)->get(); $this->assertCount(6, $users); } @@ -580,7 +585,7 @@ public function testDelete(): void */ public function testDeleteException(int $limit): void { - $this->expectException(\LogicException::class); + $this->expectException(LogicException::class); $this->expectExceptionMessage('Delete limit can be 1 or null (unlimited).'); User::limit($limit)->delete(); } diff --git a/tests/QueueTest.php b/tests/QueueTest.php index 072835b32..24afcedff 100644 --- a/tests/QueueTest.php +++ b/tests/QueueTest.php @@ -10,8 +10,12 @@ use Illuminate\Support\Str; use Mockery; use MongoDB\Laravel\Queue\Failed\MongoFailedJobProvider; +use MongoDB\Laravel\Queue\MongoJob; use MongoDB\Laravel\Queue\MongoQueue; +use function app; +use function json_encode; + class QueueTest extends TestCase { public function setUp(): void @@ -36,7 +40,7 @@ public function testQueueJobLifeCycle(): void // Get and reserve the test job (next available) $job = Queue::pop('test'); - $this->assertInstanceOf(\MongoDB\Laravel\Queue\MongoJob::class, $job); + $this->assertInstanceOf(MongoJob::class, $job); $this->assertEquals(1, $job->isReserved()); $this->assertEquals(json_encode([ 'uuid' => $uuid, @@ -95,28 +99,28 @@ public function testFindFailJobNull(): void public function testIncrementAttempts(): void { - $job_id = Queue::push('test1', ['action' => 'QueueJobExpired'], 'test'); - $this->assertNotNull($job_id); - $job_id = Queue::push('test2', ['action' => 'QueueJobExpired'], 'test'); - $this->assertNotNull($job_id); + $jobId = Queue::push('test1', ['action' => 'QueueJobExpired'], 'test'); + $this->assertNotNull($jobId); + $jobId = Queue::push('test2', ['action' => 'QueueJobExpired'], 'test'); + $this->assertNotNull($jobId); $job = Queue::pop('test'); $this->assertEquals(1, $job->attempts()); $job->delete(); - $others_jobs = Queue::getDatabase() + $othersJobs = Queue::getDatabase() ->table(Config::get('queue.connections.database.table')) ->get(); - $this->assertCount(1, $others_jobs); - $this->assertEquals(0, $others_jobs[0]['attempts']); + $this->assertCount(1, $othersJobs); + $this->assertEquals(0, $othersJobs[0]['attempts']); } public function testJobRelease(): void { $queue = 'test'; - $job_id = Queue::push($queue, ['action' => 'QueueJobRelease'], 'test'); - $this->assertNotNull($job_id); + $jobId = Queue::push($queue, ['action' => 'QueueJobRelease'], 'test'); + $this->assertNotNull($jobId); $job = Queue::pop($queue); $job->release(); @@ -132,9 +136,9 @@ public function testJobRelease(): void public function testQueueDeleteReserved(): void { $queue = 'test'; - $job_id = Queue::push($queue, ['action' => 'QueueDeleteReserved'], 'test'); + $jobId = Queue::push($queue, ['action' => 'QueueDeleteReserved'], 'test'); - Queue::deleteReserved($queue, $job_id, 0); + Queue::deleteReserved($queue, $jobId, 0); $jobs = Queue::getDatabase() ->table(Config::get('queue.connections.database.table')) ->get(); @@ -149,23 +153,23 @@ public function testQueueRelease(): void $delay = 123; Queue::push($queue, ['action' => 'QueueRelease'], 'test'); - $job = Queue::pop($queue); - $released_job_id = Queue::release($queue, $job->getJobRecord(), $delay); + $job = Queue::pop($queue); + $releasedJobId = Queue::release($queue, $job->getJobRecord(), $delay); - $released_job = Queue::getDatabase() + $releasedJob = Queue::getDatabase() ->table(Config::get('queue.connections.database.table')) - ->where('_id', $released_job_id) + ->where('_id', $releasedJobId) ->first(); - $this->assertEquals($queue, $released_job['queue']); - $this->assertEquals(1, $released_job['attempts']); - $this->assertNull($released_job['reserved_at']); + $this->assertEquals($queue, $releasedJob['queue']); + $this->assertEquals(1, $releasedJob['attempts']); + $this->assertNull($releasedJob['reserved_at']); $this->assertEquals( Carbon::now()->addRealSeconds($delay)->getTimestamp(), - $released_job['available_at'] + $releasedJob['available_at'], ); - $this->assertEquals(Carbon::now()->getTimestamp(), $released_job['created_at']); - $this->assertEquals($job->getRawBody(), $released_job['payload']); + $this->assertEquals(Carbon::now()->getTimestamp(), $releasedJob['created_at']); + $this->assertEquals($job->getRawBody(), $releasedJob['payload']); } public function testQueueDeleteAndRelease(): void diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index f418bf384..214c6f506 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -144,7 +144,7 @@ public function testEasyRelation(): void $item = Item::create(['type' => 'knife']); $user->items()->save($item); - $user = User::find($user->_id); + $user = User::find($user->_id); $items = $user->items; $this->assertCount(1, $items); $this->assertInstanceOf(Item::class, $items[0]); @@ -171,7 +171,7 @@ public function testBelongsToMany(): void $user->clients()->create(['name' => 'Buffet Bar Inc.']); // Refetch - $user = User::with('clients')->find($user->_id); + $user = User::with('clients')->find($user->_id); $client = Client::with('users')->first(); // Check for relation attributes @@ -179,7 +179,7 @@ public function testBelongsToMany(): void $this->assertArrayHasKey('client_ids', $user->getAttributes()); $clients = $user->getRelation('clients'); - $users = $client->getRelation('users'); + $users = $client->getRelation('users'); $this->assertInstanceOf(Collection::class, $users); $this->assertInstanceOf(Collection::class, $clients); @@ -196,7 +196,7 @@ public function testBelongsToMany(): void $this->assertCount(1, $user->clients); // Get user and unattached client - $user = User::where('name', '=', 'Jane Doe')->first(); + $user = User::where('name', '=', 'Jane Doe')->first(); $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); // Check the models are what they should be @@ -213,7 +213,7 @@ public function testBelongsToMany(): void $user->clients()->attach($client); // Get the new user model - $user = User::where('name', '=', 'Jane Doe')->first(); + $user = User::where('name', '=', 'Jane Doe')->first(); $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); // Assert they are attached @@ -226,7 +226,7 @@ public function testBelongsToMany(): void $user->clients()->sync([]); // Get the new user model - $user = User::where('name', '=', 'Jane Doe')->first(); + $user = User::where('name', '=', 'Jane Doe')->first(); $client = Client::Where('name', '=', 'Buffet Bar Inc.')->first(); // Assert they are not attached @@ -278,7 +278,7 @@ public function testBelongsToManyAttachesExistingModels(): void public function testBelongsToManySync(): void { // create test instances - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Pork Pies Ltd.'])->_id; $client2 = Client::create(['name' => 'Buffet Bar Inc.'])->_id; @@ -296,7 +296,7 @@ public function testBelongsToManySync(): void public function testBelongsToManyAttachArray(): void { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Test 1'])->_id; $client2 = Client::create(['name' => 'Test 2'])->_id; @@ -308,8 +308,8 @@ public function testBelongsToManyAttachArray(): void public function testBelongsToManyAttachEloquentCollection(): void { User::create(['name' => 'John Doe']); - $client1 = Client::create(['name' => 'Test 1']); - $client2 = Client::create(['name' => 'Test 2']); + $client1 = Client::create(['name' => 'Test 1']); + $client2 = Client::create(['name' => 'Test 2']); $collection = new Collection([$client1, $client2]); $user = User::where('name', '=', 'John Doe')->first(); @@ -319,7 +319,7 @@ public function testBelongsToManyAttachEloquentCollection(): void public function testBelongsToManySyncAlreadyPresent(): void { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Test 1'])->_id; $client2 = Client::create(['name' => 'Test 2'])->_id; @@ -336,11 +336,11 @@ public function testBelongsToManySyncAlreadyPresent(): void public function testBelongsToManyCustom(): void { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $group = $user->groups()->create(['name' => 'Admins']); // Refetch - $user = User::find($user->_id); + $user = User::find($user->_id); $group = Group::find($group->_id); // Check for custom relation attributes @@ -356,7 +356,7 @@ public function testBelongsToManyCustom(): void public function testMorph(): void { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $client = Client::create(['name' => 'Jane Doe']); $photo = Photo::create(['url' => 'http://graph.facebook.com/john.doe/picture']); @@ -382,12 +382,12 @@ public function testMorph(): void $photo = Photo::first(); $this->assertEquals($photo->hasImage->name, $user->name); - $user = User::with('photos')->find($user->_id); + $user = User::with('photos')->find($user->_id); $relations = $user->getRelations(); $this->assertArrayHasKey('photos', $relations); $this->assertEquals(1, $relations['photos']->count()); - $photos = Photo::with('hasImage')->get(); + $photos = Photo::with('hasImage')->get(); $relations = $photos[0]->getRelations(); $this->assertArrayHasKey('hasImage', $relations); $this->assertInstanceOf(User::class, $photos[0]->hasImage); @@ -498,7 +498,7 @@ public function testNestedKeys(): void public function testDoubleSaveOneToMany(): void { $author = User::create(['name' => 'George R. R. Martin']); - $book = Book::create(['title' => 'A Game of Thrones']); + $book = Book::create(['title' => 'A Game of Thrones']); $author->books()->save($book); $author->books()->save($book); @@ -507,7 +507,7 @@ public function testDoubleSaveOneToMany(): void $this->assertEquals($author->_id, $book->author_id); $author = User::where('name', 'George R. R. Martin')->first(); - $book = Book::where('title', 'A Game of Thrones')->first(); + $book = Book::where('title', 'A Game of Thrones')->first(); $this->assertEquals(1, $author->books()->count()); $this->assertEquals($author->_id, $book->author_id); @@ -520,7 +520,7 @@ public function testDoubleSaveOneToMany(): void public function testDoubleSaveManyToMany(): void { - $user = User::create(['name' => 'John Doe']); + $user = User::create(['name' => 'John Doe']); $client = Client::create(['name' => 'Admins']); $user->clients()->save($client); @@ -531,7 +531,7 @@ public function testDoubleSaveManyToMany(): void $this->assertEquals([$user->_id], $client->user_ids); $this->assertEquals([$client->_id], $user->client_ids); - $user = User::where('name', 'John Doe')->first(); + $user = User::where('name', 'John Doe')->first(); $client = Client::where('name', 'Admins')->first(); $this->assertEquals(1, $user->clients()->count()); $this->assertEquals([$user->_id], $client->user_ids); diff --git a/tests/Seeder/DatabaseSeeder.php b/tests/Seeder/DatabaseSeeder.php index 27e4468ad..ef512b869 100644 --- a/tests/Seeder/DatabaseSeeder.php +++ b/tests/Seeder/DatabaseSeeder.php @@ -1,5 +1,7 @@ run(); $user = User::where('name', 'John Doe')->first(); diff --git a/tests/TestCase.php b/tests/TestCase.php index 0efddb4ce..f54c01405 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -13,12 +13,15 @@ use MongoDB\Laravel\Validation\ValidationServiceProvider; use Orchestra\Testbench\TestCase as OrchestraTestCase; +use function array_search; + class TestCase extends OrchestraTestCase { /** * Get application providers. * - * @param Application $app + * @param Application $app + * * @return array */ protected function getApplicationProviders($app) @@ -33,7 +36,8 @@ protected function getApplicationProviders($app) /** * Get package providers. * - * @param Application $app + * @param Application $app + * * @return array */ protected function getPackageProviders($app) @@ -49,7 +53,8 @@ protected function getPackageProviders($app) /** * Define environment setup. * - * @param Application $app + * @param Application $app + * * @return void */ protected function getEnvironmentSetUp($app) diff --git a/tests/TransactionTest.php b/tests/TransactionTest.php index 707c0b977..1086171d7 100644 --- a/tests/TransactionTest.php +++ b/tests/TransactionTest.php @@ -1,5 +1,7 @@ 'klinson', 'age' => 20, 'title' => 'admin']); + $this->assertInstanceOf(User::class, $klinson); DB::commit(); $this->assertInstanceOf(Model::class, $klinson); @@ -50,8 +52,8 @@ public function testCreateWithCommit(): void public function testCreateRollBack(): void { DB::beginTransaction(); - /** @var User $klinson */ $klinson = User::create(['name' => 'klinson', 'age' => 20, 'title' => 'admin']); + $this->assertInstanceOf(User::class, $klinson); DB::rollBack(); $this->assertInstanceOf(Model::class, $klinson); @@ -82,8 +84,8 @@ public function testInsertWithRollBack(): void public function testEloquentCreateWithCommit(): void { DB::beginTransaction(); - /** @var User $klinson */ $klinson = User::getModel(); + $this->assertInstanceOf(User::class, $klinson); $klinson->name = 'klinson'; $klinson->save(); DB::commit(); @@ -99,8 +101,8 @@ public function testEloquentCreateWithCommit(): void public function testEloquentCreateWithRollBack(): void { DB::beginTransaction(); - /** @var User $klinson */ $klinson = User::getModel(); + $this->assertInstanceOf(User::class, $klinson); $klinson->name = 'klinson'; $klinson->save(); DB::rollBack(); @@ -159,10 +161,10 @@ public function testUpdateWithRollback(): void public function testEloquentUpdateWithCommit(): void { - /** @var User $klinson */ $klinson = User::create(['name' => 'klinson', 'age' => 20, 'title' => 'admin']); - /** @var User $alcaeus */ + $this->assertInstanceOf(User::class, $klinson); $alcaeus = User::create(['name' => 'alcaeus', 'age' => 38, 'title' => 'admin']); + $this->assertInstanceOf(User::class, $alcaeus); DB::beginTransaction(); $klinson->age = 21; @@ -180,10 +182,10 @@ public function testEloquentUpdateWithCommit(): void public function testEloquentUpdateWithRollBack(): void { - /** @var User $klinson */ $klinson = User::create(['name' => 'klinson', 'age' => 20, 'title' => 'admin']); - /** @var User $alcaeus */ + $this->assertInstanceOf(User::class, $klinson); $alcaeus = User::create(['name' => 'klinson', 'age' => 38, 'title' => 'admin']); + $this->assertInstanceOf(User::class, $alcaeus); DB::beginTransaction(); $klinson->age = 21; @@ -225,8 +227,8 @@ public function testDeleteWithRollBack(): void public function testEloquentDeleteWithCommit(): void { - /** @var User $klinson */ $klinson = User::create(['name' => 'klinson', 'age' => 20, 'title' => 'admin']); + $this->assertInstanceOf(User::class, $klinson); DB::beginTransaction(); $klinson->delete(); @@ -237,8 +239,8 @@ public function testEloquentDeleteWithCommit(): void public function testEloquentDeleteWithRollBack(): void { - /** @var User $klinson */ $klinson = User::create(['name' => 'klinson', 'age' => 20, 'title' => 'admin']); + $this->assertInstanceOf(User::class, $klinson); DB::beginTransaction(); $klinson->delete(); @@ -349,7 +351,7 @@ public function testTransactionRepeatsOnTransientFailure(): void User::create(['name' => 'alcaeus', 'age' => 38, 'title' => 'admin']); // Update user outside of the session - if ($timesRun == 1) { + if ($timesRun === 1) { DB::getCollection('users')->updateOne(['name' => 'klinson'], ['$set' => ['age' => 22]]); } diff --git a/tests/ValidationTest.php b/tests/ValidationTest.php index c0521bfaa..d5122ce7b 100644 --- a/tests/ValidationTest.php +++ b/tests/ValidationTest.php @@ -18,7 +18,7 @@ public function testUnique(): void { $validator = Validator::make( ['name' => 'John Doe'], - ['name' => 'required|unique:users'] + ['name' => 'required|unique:users'], ); $this->assertFalse($validator->fails()); @@ -26,31 +26,31 @@ public function testUnique(): void $validator = Validator::make( ['name' => 'John Doe'], - ['name' => 'required|unique:users'] + ['name' => 'required|unique:users'], ); $this->assertTrue($validator->fails()); $validator = Validator::make( ['name' => 'John doe'], - ['name' => 'required|unique:users'] + ['name' => 'required|unique:users'], ); $this->assertTrue($validator->fails()); $validator = Validator::make( ['name' => 'john doe'], - ['name' => 'required|unique:users'] + ['name' => 'required|unique:users'], ); $this->assertTrue($validator->fails()); $validator = Validator::make( ['name' => 'test doe'], - ['name' => 'required|unique:users'] + ['name' => 'required|unique:users'], ); $this->assertFalse($validator->fails()); $validator = Validator::make( ['name' => 'John'], // Part of an existing value - ['name' => 'required|unique:users'] + ['name' => 'required|unique:users'], ); $this->assertFalse($validator->fails()); @@ -58,19 +58,19 @@ public function testUnique(): void $validator = Validator::make( ['email' => 'johnny.cash+200@gmail.com'], - ['email' => 'required|unique:users'] + ['email' => 'required|unique:users'], ); $this->assertTrue($validator->fails()); $validator = Validator::make( ['email' => 'johnny.cash+20@gmail.com'], - ['email' => 'required|unique:users'] + ['email' => 'required|unique:users'], ); $this->assertFalse($validator->fails()); $validator = Validator::make( ['email' => 'johnny.cash+1@gmail.com'], - ['email' => 'required|unique:users'] + ['email' => 'required|unique:users'], ); $this->assertFalse($validator->fails()); } @@ -79,7 +79,7 @@ public function testExists(): void { $validator = Validator::make( ['name' => 'John Doe'], - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertTrue($validator->fails()); @@ -88,37 +88,37 @@ public function testExists(): void $validator = Validator::make( ['name' => 'John Doe'], - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertFalse($validator->fails()); $validator = Validator::make( ['name' => 'john Doe'], - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertFalse($validator->fails()); $validator = Validator::make( ['name' => ['test name', 'john doe']], - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertFalse($validator->fails()); $validator = Validator::make( ['name' => ['test name', 'john']], // Part of an existing value - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertTrue($validator->fails()); $validator = Validator::make( ['name' => '(invalid regex{'], - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertTrue($validator->fails()); $validator = Validator::make( ['name' => ['foo', '(invalid regex{']], - ['name' => 'required|exists:users'] + ['name' => 'required|exists:users'], ); $this->assertTrue($validator->fails()); @@ -126,7 +126,7 @@ public function testExists(): void $validator = Validator::make( ['name' => []], - ['name' => 'exists:users'] + ['name' => 'exists:users'], ); $this->assertFalse($validator->fails()); } diff --git a/tests/config/database.php b/tests/config/database.php index 498e4e7e0..24fee24f4 100644 --- a/tests/config/database.php +++ b/tests/config/database.php @@ -1,5 +1,7 @@ [ 'mongodb' => [ diff --git a/tests/config/queue.php b/tests/config/queue.php index d287780e9..613e0867e 100644 --- a/tests/config/queue.php +++ b/tests/config/queue.php @@ -1,5 +1,7 @@ env('QUEUE_CONNECTION'),