Guest User

Untitled

a guest
Feb 17th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. <?php
  2. /**
  3. * Automatically locates and loads files based on their namespaces and their
  4. * file names whenever they are instantiated.
  5. *
  6. * @package WerdsWords
  7. */
  8. spl_autoload_register(function( $filename ) {
  9.  
  10. // First, separate the components of the incoming file.
  11. $file_path = explode( '\\', $filename );
  12.  
  13. /**
  14. * - The first index will always be the namespace since it's part of the plugin.
  15. * - All but the last index will be the path to the file.
  16. * - The final index will be the filename. If it doesn't begin with 'I' then it's a class.
  17. */
  18.  
  19. // Get the last index of the array. This is the class we're loading.
  20. $file_name = '';
  21. if ( isset( $file_path[ count( $file_path ) - 1 ] ) ) {
  22.  
  23. $file_name = strtolower(
  24. $file_path[ count( $file_path ) - 1 ]
  25. );
  26.  
  27. $file_name = str_ireplace( '_', '-', $file_name );
  28. $file_name_parts = explode( '-', $file_name );
  29.  
  30. // Use array_search() to handle both Interface_Foo or Foo_Interface.
  31. $index = array_search( 'interface', $file_name_parts );
  32.  
  33. if ( false !== $index ) {
  34. unset( $file_name_parts[ $index ] );
  35.  
  36. // Rebuild the file name.
  37. $file_name = implode( '-', $file_name_parts );
  38.  
  39. $file_name = "interface-{$file_name}.php";
  40. } else {
  41. $file_name = "class-$file_name.php";
  42. }
  43. }
  44.  
  45. /**
  46. * Find the fully qualified path to the class file by iterating through the $file_path array.
  47. * We ignore the first index since it's always the top-level package. The last index is always
  48. * the file so we append that at the end.
  49. */
  50. $fully_qualified_path = trailingslashit(
  51. dirname(
  52. dirname( __FILE__ )
  53. )
  54. );
  55.  
  56. for ( $i = 1; $i < count( $file_path ) - 1; $i++ ) {
  57.  
  58. $dir = strtolower( $file_path[ $i ] );
  59. $fully_qualified_path .= trailingslashit( $dir );
  60. }
  61. $fully_qualified_path .= $file_name;
  62.  
  63. // Now include the file.
  64. if ( stream_resolve_include_path( $fully_qualified_path ) ) {
  65. include_once $fully_qualified_path;
  66. }
  67. } );
Add Comment
Please, Sign In to add comment