    001    package org.hamcrest.core;
    002
    003    import org.hamcrest.Description;
    004    import org.hamcrest.Factory;
    005    import org.hamcrest.Matcher;
    006    import org.hamcrest.TypeSafeDiagnosingMatcher;
    007
    008    public class Every<T> extends TypeSafeDiagnosingMatcher<Iterable<T>> {
    009        private final Matcher<? super T> matcher;
    010
    011        public Every(Matcher<? super T> matcher) {
    012            this.matcher= matcher;
    013        }
    014
    015        @Override
    016        public boolean matchesSafely(Iterable<T> collection, Description mismatchDescription) {
    017            for (T t : collection) {
    018                if (!matcher.matches(t)) {
    019                    mismatchDescription.appendText("an item ");
    020                    matcher.describeMismatch(t, mismatchDescription);
    021                    return false;
    022                }
    023            }
    024            return true;
    025        }
    026
    027        @Override
    028        public void describeTo(Description description) {
    029            description.appendText("every item is ").appendDescriptionOf(matcher);
    030        }
    031
    032        /**
    033         * Creates a matcher for {@link Iterable}s that only matches when a single pass over the
    034         * examined {@link Iterable} yields items that are all matched by the specified
    035         * <code>itemMatcher</code>.
    036         * <p/>
    037         * For example:
    038         * <pre>assertThat(Arrays.asList("bar", "baz"), everyItem(startsWith("ba")))</pre>
    039         *
    040         * @param itemMatcher
    041         *     the matcher to apply to every item provided by the examined {@link Iterable}
    042         */
    043        @Factory
    044        public static <U> Matcher<Iterable<U>> everyItem(final Matcher<U> itemMatcher) {
    045            return new Every<U>(itemMatcher);
    046        }
    047    }