Backend for songs.zachdecook.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

namespace App\Http\Controllers;

use App\Song;
use Illuminate\Http\Request;

class SongController extends Controller
{

    public function show( $songNumber )
    {
        $song = Song::where('number', $songNumber )->first();
        $lines = explode( "\n", $song['text'] );
        $newText = '';
        foreach( $lines as $line ){
            $line = htmlspecialchars( $line );
            if ( $this->chordline( $line ) ) {
                $transp = 0;
                $class = "tabs chord$transp";
                $line = str_replace(
                    array('{','}'),
                    array('</b>{', "}<b class='$class'>" ),
                    $line );
                $newText .= "<b class='$class'>" . $line . "</b>\n";
            } else {
            $newText .= "$line\n";
            }
        }
        $song['escapedText'] = $newText;
        return view('song', ['song' => $song, 'transp' => 0 ] );
    }

    /**
     * @brief Determine whether or not this line contains chords.
     */
    private function chordline($line)
    {
        $chords =
            array( "C","C#","D","D#","E","F","F#","G","G#","A#","B",//"A",
            "Db", "Eb", "Gb", "Bb",//"Ab",
            "Cm", "Dm", "Fm", "Gm", "Bm",  //"Em", "Am",
            );
        $ambiguous = array( "Ab", "Em", "Am", "A" );
        $line = str_replace(array('/','7', "\n", '2', '4'), ' ', $line);
        $tokens = array_filter(explode(' ', $line));

        $badtokens = 0;
        $ambtokens = 0;
        $goodtokens = 0;
        foreach ($tokens as $token) {
            if( in_array( substr($token, 0,2), $chords ) ) $goodtokens++;
            else if ( in_array( substr( $token, 0,2), $ambiguous) ) $ambtokens++;
            else if( $badtokens > 10 ) return FALSE;
            else $badtokens++;
        }
        return ($goodtokens *2)+ $ambtokens >= $badtokens;
    }

}