BsdFindAdapter.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Finder\Adapter;
  11. use Symfony\Component\Finder\Shell\Shell;
  12. use Symfony\Component\Finder\Shell\Command;
  13. use Symfony\Component\Finder\Iterator\SortableIterator;
  14. use Symfony\Component\Finder\Expression\Expression;
  15. /**
  16. * Shell engine implementation using BSD find command.
  17. *
  18. * @author Jean-François Simon <contact@jfsimon.fr>
  19. */
  20. class BsdFindAdapter extends AbstractFindAdapter
  21. {
  22. /**
  23. * {@inheritdoc}
  24. */
  25. public function getName()
  26. {
  27. return 'bsd_find';
  28. }
  29. /**
  30. * {@inheritdoc}
  31. */
  32. protected function canBeUsed()
  33. {
  34. return in_array($this->shell->getType(), array(Shell::TYPE_BSD, Shell::TYPE_DARWIN)) && parent::canBeUsed();
  35. }
  36. /**
  37. * {@inheritdoc}
  38. */
  39. protected function buildFormatSorting(Command $command, $sort)
  40. {
  41. switch ($sort) {
  42. case SortableIterator::SORT_BY_NAME:
  43. $command->ins('sort')->add('| sort');
  44. return;
  45. case SortableIterator::SORT_BY_TYPE:
  46. $format = '%HT';
  47. break;
  48. case SortableIterator::SORT_BY_ACCESSED_TIME:
  49. $format = '%a';
  50. break;
  51. case SortableIterator::SORT_BY_CHANGED_TIME:
  52. $format = '%c';
  53. break;
  54. case SortableIterator::SORT_BY_MODIFIED_TIME:
  55. $format = '%m';
  56. break;
  57. default:
  58. throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort));
  59. }
  60. $command
  61. ->add('-print0 | xargs -0 stat -f')
  62. ->arg($format.'%t%N')
  63. ->add('| sort | cut -f 2');
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. protected function buildFindCommand(Command $command, $dir)
  69. {
  70. parent::buildFindCommand($command, $dir)->addAtIndex('-E', 1);
  71. return $command;
  72. }
  73. /**
  74. * {@inheritdoc}
  75. */
  76. protected function buildContentFiltering(Command $command, array $contains, $not = false)
  77. {
  78. foreach ($contains as $contain) {
  79. $expr = Expression::create($contain);
  80. // todo: avoid forking process for each $pattern by using multiple -e options
  81. $command
  82. ->add('| grep -v \'^$\'')
  83. ->add('| xargs -I{} grep -I')
  84. ->add($expr->isCaseSensitive() ? null : '-i')
  85. ->add($not ? '-L' : '-l')
  86. ->add('-Ee')->arg($expr->renderPattern())
  87. ->add('{}')
  88. ;
  89. }
  90. }
  91. }