CreatesUserProviders.php 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Illuminate\Auth;
  3. use InvalidArgumentException;
  4. trait CreatesUserProviders
  5. {
  6. /**
  7. * The registered custom provider creators.
  8. *
  9. * @var array
  10. */
  11. protected $customProviderCreators = [];
  12. /**
  13. * Create the user provider implementation for the driver.
  14. *
  15. * @param string|null $provider
  16. * @return \Illuminate\Contracts\Auth\UserProvider|null
  17. *
  18. * @throws \InvalidArgumentException
  19. */
  20. public function createUserProvider($provider = null)
  21. {
  22. if (is_null($config = $this->getProviderConfiguration($provider))) {
  23. return;
  24. }
  25. if (isset($this->customProviderCreators[$driver = ($config['driver'] ?? null)])) {
  26. return call_user_func(
  27. $this->customProviderCreators[$driver], $this->app, $config
  28. );
  29. }
  30. switch ($driver) {
  31. case 'database':
  32. return $this->createDatabaseProvider($config);
  33. case 'eloquent':
  34. return $this->createEloquentProvider($config);
  35. default:
  36. throw new InvalidArgumentException(
  37. "Authentication user provider [{$driver}] is not defined."
  38. );
  39. }
  40. }
  41. /**
  42. * Get the user provider configuration.
  43. *
  44. * @param string|null $provider
  45. * @return array|null
  46. */
  47. protected function getProviderConfiguration($provider)
  48. {
  49. if ($provider = $provider ?: $this->getDefaultUserProvider()) {
  50. return $this->app['config']['auth.providers.'.$provider];
  51. }
  52. }
  53. /**
  54. * Create an instance of the database user provider.
  55. *
  56. * @param array $config
  57. * @return \Illuminate\Auth\DatabaseUserProvider
  58. */
  59. protected function createDatabaseProvider($config)
  60. {
  61. $connection = $this->app['db']->connection();
  62. return new DatabaseUserProvider($connection, $this->app['hash'], $config['table']);
  63. }
  64. /**
  65. * Create an instance of the Eloquent user provider.
  66. *
  67. * @param array $config
  68. * @return \Illuminate\Auth\EloquentUserProvider
  69. */
  70. protected function createEloquentProvider($config)
  71. {
  72. return new EloquentUserProvider($this->app['hash'], $config['model']);
  73. }
  74. /**
  75. * Get the default user provider name.
  76. *
  77. * @return string
  78. */
  79. public function getDefaultUserProvider()
  80. {
  81. return $this->app['config']['auth.defaults.provider'];
  82. }
  83. }