Fale / isbn

PHP ISBN library
GNU Affero General Public License v3.0
84 stars 16 forks source link

Validate ISBN with EAN-2 or EAN-5 add-on. #13

Open dac514 opened 8 years ago

dac514 commented 8 years ago

ISBN supports a 2 or 5 digit add-on, example: 978-1-873671-00-9 54499

Valid ISBN Number

Can you improve your library to validate this?

Thanks.

Source:

Fale commented 6 years ago

Are there machine-parsable set of rules for those?

dac514 commented 6 years ago

Here they are:

https://www.activebarcode.com/codes/ean5_ean2.html

Valid characters: 01234567890 Length: 2 bzw. 5 Check digit: none Type#: EAN-5 - #03 - CODEEAN5, EAN-2 - #04 - CODEEAN2

Fale commented 6 years ago

It seems like they "add" stuff to EAN codes, and that sometimes are used with ISBN but they are not part of the ISBN standard. What kind of output would you expect?

dac514 commented 6 years ago

Well, this ticket is from 2015 so we already have this working, heh.

We use your library and our code looks something like this:

    /**
     * Validate an ISBN string
     *
     * @param $isbn_number
     *
     * @return bool
     */
    function validateIsbnNumber( $isbn_number ) {
        // Regex to split a string only by the last whitespace character
        @list( $isbn_number, $addon ) = preg_split( '/\s+(?=\S*+$)/', trim( $isbn_number ) ); // @codingStandardsIgnoreLine
        $is_valid_isbn = ( new \Isbn\Isbn() )->validation->isbn( $isbn_number );
        $is_valid_addon = true;
        if ( $addon ) {
            if ( ! preg_match( '/^([0-9]{2}|[0-9]{5})$/', $addon ) ) {
                $is_valid_addon = false;
            }
        }
        return $is_valid_isbn && $is_valid_addon;
    }

The PHPUnit @dataProvider looks like this:

    /**
     *  [ $isbnNumber, $expected ]
     *
     * @return array
     */
    public function validateIsbnNumberProvider() {
        return [
            [ '978-1-873671-00-9 54499', true ],
            [ '978-1-873671-00-9 59', true ],
            [ '978-1-873671-00-9', true ],
            [ '9781873671009', true ],
            [ '1-86074-271-8', true ],
            [ '   1-86074-271-8   ', true ],
            [ '   1-86074-271-8    88888', true ],
            [ '   1-86074-271-8    88888   ', true ],
            [ '978-1-873671-00-9 111', false ],
            [ '111-1-873671-00-9', false ],
            [ '1111111111111', false ],
            [ 'abc', false ],
            [ '', false ],
            [ '1-86074-271-2', false ], // We do not support automatically upgrading ISBN-10 to ISBN-13
            [ '978-1-873671-00', false ], // We do not support ISBN without a trailing check digit
        ];
    }

Does this help?