file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
src/index.jsx | JavaScript (JSX) | import React from "react";
import { createRoot } from 'react-dom/client';
import App from "./App";
createRoot(document.getElementById('root')).render(<App/>)
| yairm210/base44-site-template | 17 | Create sites with base44 and use as standalone | JavaScript | yairm210 | Yair Morgenstern | |
src/lib/utils.ts | TypeScript | import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
| yairm210/base44-site-template | 17 | Create sites with base44 and use as standalone | JavaScript | yairm210 | Yair Morgenstern | |
vite.config.mjs | JavaScript | import path from "path"
import tailwindcss from "@tailwindcss/vite"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})
| yairm210/base44-site-template | 17 | Create sites with base44 and use as standalone | JavaScript | yairm210 | Yair Morgenstern | |
build.gradle.kts | Kotlin |
repositories {
mavenCentral()
gradlePluginPortal()
}
plugins {
kotlin("jvm") version "2.1.20"
`kotlin-dsl`
}
subprojects {
apply(plugin = "kotlin")
repositories {
mavenCentral()
}
dependencies {
"implementation"("org.jetbrains.kotlin:kotlin-compiler:2.1.20")
"testImplementation"("org.junit.jupiter:junit-jupiter:5.12.1")
"testRuntimeOnly"("org.junit.platform:junit-platform-launcher")
}
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
buildSrc/build.gradle.kts | Kotlin | /*
* This file was generated by the Gradle 'init' task.
* TODO move this into build.gradle.kts somehow
*/
plugins {
// Support convention plugins written in Kotlin. Convention plugins are build scripts in 'src/main' that automatically become available as plugins in the main build.
`kotlin-dsl`
}
repositories {
// Use the plugin portal to apply community plugins in convention plugins.
gradlePluginPortal()
}
//
//dependencies {
// implementation(libs.kotlin.gradle.plugin)
//}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
buildSrc/settings.gradle.kts | Kotlin | /*
* This file was generated by the Gradle 'init' task.
*
* This settings file is used to specify which projects to include in your build-logic build.
*/
//dependencyResolutionManagement {
// // Reuse version catalog from the main build.
// versionCatalogs {
// create("libs", { from(files("../gradle/libs.versions.toml")) })
// }
//}
//rootProject.name = "buildSrc"
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
core/build.gradle.kts | Kotlin | /*
* This file was generated by the Gradle 'init' task.
*/
dependencies {
"implementation"("org.jetbrains.kotlin:kotlin-compiler:2.1.20")
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
core/src/main/kotlin/github/yairm210/kotlin_ir_explorer/core/BufferingMessageCollector.kt | Kotlin | import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
/*
* Copied DIRECTLY org.jetbrains.kotlin.cli.common.messages
* (As per Apache 2.0 license terms)
* TODO: Update compiler to latest so we get can reference this directly, it's silly we need to copy it
*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
/**
* A message collector which collects all messages into a list and allows to access it.
*/
open class MessageCollectorImpl : MessageCollector {
private val _messages: MutableList<Message> = mutableListOf<Message>()
val messages: List<Message> get() = _messages
val errors: List<Message>
get() = messages.filter { it.severity.isError }
fun forward(other: MessageCollector) {
for (message in _messages) {
other.report(message.severity, message.message, message.location)
}
}
override fun clear() {
_messages.clear()
}
override fun report(
severity: CompilerMessageSeverity,
message: String,
location: CompilerMessageSourceLocation?,
) {
_messages.add(Message(severity, message, location))
}
override fun hasErrors(): Boolean =
messages.any { it.severity.isError }
override fun toString(): String = messages.joinToString("\n")
data class Message(val severity: CompilerMessageSeverity, val message: String, val location: CompilerMessageSourceLocation?) {
override fun toString(): String = buildString {
if (location != null) {
append(location)
append(": ")
}
append(severity.presentableName)
append(": ")
append(message)
}
}
} | yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
core/src/main/kotlin/github/yairm210/kotlin_ir_explorer/core/IrCompiler.kt | Kotlin | import com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.backend.jvm.JvmIrCodegenFactory
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
import org.jetbrains.kotlin.cli.jvm.compiler.EnvironmentConfigFiles
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM
import org.jetbrains.kotlin.cli.jvm.config.addJvmClasspathRoots
import org.jetbrains.kotlin.config.CommonConfigurationKeys
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.JVMConfigurationKeys
import org.jetbrains.kotlin.config.languageVersionSettings
import org.jetbrains.kotlin.diagnostics.DiagnosticReporterFactory
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
import org.jetbrains.kotlin.ir.util.dump
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import java.io.File
// Updated for Kotlin compiler 2.1.20
@OptIn(UnsafeDuringIrConstructionAPI::class)
fun main() {
val kotlinCode = """
fun main() {
var x = 5
if (x > 1 + 2) {
x += 1
listOf(1, 2)
}
}
""".trimIndent()
val compilationResult = getCompilationResult(kotlinCode)
if (compilationResult.irModuleFragment == null) println("Result is null")
else {
compilationResult.irModuleFragment.files
.forEach { file ->
file.declarations.forEach { declaration ->
println(declaration.dump())
}
}
}
for (message in compilationResult.messages)
println("${message.severity}: ${message.message} ${message.location?.let { "${it.line}:${it.column}" }}")
}
fun getCompilationResult(kotlinCode: String): CompilationResult {
// This was a pain to figure out, so if you're copying this, please attribute :D
val messageCollector = MessageCollectorImpl()
val configuration = getCompilerConfiguration(messageCollector)
val rootDisposable = Disposer.newDisposable("KotlinIrExplorer")
try {
val environment = KotlinCoreEnvironment.createForProduction(
rootDisposable,
configuration,
EnvironmentConfigFiles.JVM_CONFIG_FILES
)
val ktFile = KtPsiFactory(environment.project).createPhysicalFile("input.kt", kotlinCode)
// Analyze the code using the K1 frontend
val analysisResult = analyze(environment, listOf(ktFile))
if (analysisResult == null || !analysisResult.shouldGenerateCode) {
return CompilationResult(
irModuleFragment = null,
messages = messageCollector.messages
)
}
analysisResult.throwIfError()
// Convert to IR using JvmIrCodegenFactory
val diagnosticsReporter = DiagnosticReporterFactory.createReporter(messageCollector)
val codegenFactory = JvmIrCodegenFactory(configuration)
val backendInput = codegenFactory.convertToIr(
project = environment.project,
files = listOf(ktFile),
configuration = configuration,
module = analysisResult.moduleDescriptor,
diagnosticReporter = diagnosticsReporter,
bindingContext = analysisResult.bindingContext,
languageVersionSettings = configuration.languageVersionSettings,
ignoreErrors = false,
skipBodies = false,
)
return CompilationResult(
irModuleFragment = backendInput.irModuleFragment,
messages = messageCollector.messages
)
} finally {
Disposer.dispose(rootDisposable)
}
}
private fun analyze(
environment: KotlinCoreEnvironment,
sourceFiles: List<KtFile>
): org.jetbrains.kotlin.analyzer.AnalysisResult? {
val collector = environment.configuration.getNotNull(CommonConfigurationKeys.MESSAGE_COLLECTOR_KEY)
val analyzerWithCompilerReport = AnalyzerWithCompilerReport(
collector,
environment.configuration.languageVersionSettings,
environment.configuration.getBoolean(CLIConfigurationKeys.RENDER_DIAGNOSTIC_INTERNAL_NAME)
)
analyzerWithCompilerReport.analyzeAndReport(sourceFiles) {
val project = environment.project
val sourcesOnly = TopDownAnalyzerFacadeForJVM.newModuleSearchScope(project, sourceFiles)
@Suppress("DEPRECATION_ERROR")
TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(
project,
sourceFiles,
NoScopeRecordCliBindingTrace(project),
environment.configuration,
environment::createPackagePartProvider,
sourceModuleSearchScope = sourcesOnly,
)
}
val analysisResult = analyzerWithCompilerReport.analysisResult
return if (!analyzerWithCompilerReport.hasErrors())
analysisResult
else
null
}
data class CompilationResult(
val irModuleFragment: IrModuleFragment?,
val messages: List<MessageCollectorImpl.Message>
)
private fun getCompilerConfiguration(messageCollector: MessageCollectorImpl): CompilerConfiguration {
val configuration = CompilerConfiguration()
configuration.put(CommonConfigurationKeys.MESSAGE_COLLECTOR_KEY, messageCollector)
configuration.put(CommonConfigurationKeys.MODULE_NAME, "test-module")
// Reference set A: The JDK. This includes fundamental things like java.io.Serializable
// This means that the server needs to run with a JDK, and not just a JRE.
val sdkRoot = System.getProperty("java.home")
configuration.put(JVMConfigurationKeys.JDK_HOME, File(sdkRoot))
// Reference set B: The classes we've included in this jar. This includes e.g. Kotlin stdlib.
// Again we can get the classpath from running code, since this is Kotlin we're writing in :)
val classpath = System.getProperty("java.class.path")
val files = classpath.split(File.pathSeparatorChar).map { File(it) }
configuration.addJvmClasspathRoots(files)
return configuration
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
core/src/main/kotlin/github/yairm210/kotlin_ir_explorer/core/IrMermaidGraphConverter.kt | Kotlin | package github.yairm210.kotlin_ir_explorer.core
import org.jetbrains.kotlin.ir.IrElement
import org.jetbrains.kotlin.ir.declarations.IrClass
import org.jetbrains.kotlin.ir.declarations.IrDeclarationWithName
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.declarations.IrModuleFragment
import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.ir.visitors.IrElementVisitor
object IrMermaidGraphConverter {
fun convertToMermaidGraph(irModuleFragment: IrModuleFragment,
/** Whether to add a comment that shows the start-end positions of each element in the input text
* Note that this causes the graph to not render properly despite the comment being ostensibly valid mermaid :|
* */
withOffsetComment: Boolean = false): String {
val sb = StringBuilder()
sb.appendLine("graph TD")
irModuleFragment.files.forEach { file ->
file.accept(IrMermaidGraphListener(withOffsetComment), Triple(null, sb, 0))
}
return sb.toString()
}
}
class IrMermaidGraphListener(val withOffsetComment: Boolean) :IrElementVisitor<Unit, Triple<IrElement?, StringBuilder, Int>> {
override fun visitElement(element: IrElement, data: Triple<IrElement?, StringBuilder, Int>) {
val (parent, stringbuilder:StringBuilder, depth) = data
// Don't use stringbuilder.repeat since it's new to JVM 21
stringbuilder.append(" ".repeat(depth))
val offsetComment = if (withOffsetComment) " %% Offset: ${element.startOffset}-${element.endOffset}"
else ""
// Need to escape the rendered string to avoid issues with mermaid
val elementText = "\"${element::class.simpleName}\n" +
"${element.render()}\""
stringbuilder.appendLine("${element.hashCode()}[$elementText]$offsetComment")
// IDs of the elements are the hashcodes
if (parent != null) {
stringbuilder.append(" ".repeat(depth))
stringbuilder.appendLine("${parent.hashCode()} --> ${element.hashCode()}")
}
listOf(1,2).max()
// The subgraph should not hold the block body containing the function declaration, hence it can't be at the top of this function
if (element is IrFunction || element is IrClass) {
val name = (element as IrDeclarationWithName).name.asString()
// Autogenerated functions are wrapped in <these> so Mermaid interprets them as HTML-like tags making the text invisible
val functionNameNotHtmlLike = element.name.asString().removePrefix("<").removeSuffix(">")
// Each class has autogenerated functions with the same name - we don't want them mapping to the same subgraph
val prefix = if (parent is IrDeclarationWithName) "${parent.name.asString()}." else ""
stringbuilder.appendLine("subgraph \"$prefix$functionNameNotHtmlLike\"")
}
// User-visible text is just the classname for now
element.acceptChildren(this, Triple(element, stringbuilder, depth + 1))
if (element is IrFunction || element is IrClass) {
stringbuilder.appendLine("end")
}
}
} | yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/build.gradle.kts | Kotlin | /*
* This file was generated by the Gradle 'init' task.
*/
plugins {
application
// kotlinx serialization
kotlin("plugin.serialization") version "2.1.20"
id("com.gradleup.shadow") version "8.3.5"
}
apply(plugin = "kotlinx-serialization")
val ktorVersion = "2.3.4"
dependencies {
implementation(project(":core"))
// ktor
implementation("io.ktor:ktor-server-core:$ktorVersion")
implementation("io.ktor:ktor-server-netty:$ktorVersion")
implementation("io.ktor:ktor-server-content-negotiation:$ktorVersion")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktorVersion")
implementation("io.ktor:ktor-server-default-headers:$ktorVersion")
implementation("io.ktor:ktor-server-compression:$ktorVersion")
implementation("io.ktor:ktor-server-host-common:$ktorVersion")
implementation("io.ktor:ktor-server-config-yaml:$ktorVersion")
implementation("ch.qos.logback:logback-classic:1.5.13")
implementation("io.ktor:ktor-server-cors:$ktorVersion")
//testing
testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")
// kotlin test
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:2.1.20")
}
application { // for local development
mainClass = "io.ktor.server.netty.EngineMain"
}
// for production deployment - see https://stackoverflow.com/questions/32567167/gradle-no-main-manifest-attribute
//tasks.withType<Jar> {
// manifest {
// attributes["Main-Class"] = "github.yairm210.kotlin_ir_explorer.server.ServerKt"
// }
//} | yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/kotlin/github/yairm210/kotlin_ir_explorer/server/App.kt | Kotlin | package github.yairm210.kotlin_ir_explorer.server
import getCompilationResult
import github.yairm210.kotlin_ir_explorer.core.IrMermaidGraphConverter
import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
import org.jetbrains.kotlin.ir.util.dump
@OptIn(UnsafeDuringIrConstructionAPI::class)
fun main() {
val kotlinCode = """
fun main() {
var x = 5
if (x > 1 + 2) {
x += 1
listOf(1, 2)
}
}
""".trimIndent()
val compilationResult = getCompilationResult(kotlinCode)
if (compilationResult.irModuleFragment == null) println("Result is null")
else {
compilationResult.irModuleFragment!!.files
.forEach { file ->
file.declarations.forEach { declaration ->
println(declaration.dump())
}
}
val mermaidGraph = IrMermaidGraphConverter.convertToMermaidGraph(compilationResult.irModuleFragment!!)
println(mermaidGraph)
}
for (message in compilationResult.messages)
println("${message.severity}: ${message.message} ${message.location?.let { "${it.line}:${it.column}" }}")
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/kotlin/github/yairm210/kotlin_ir_explorer/server/Server.kt | Kotlin | package github.yairm210.kotlin_ir_explorer.server
import getCompilationResult
import github.yairm210.kotlin_ir_explorer.core.IrMermaidGraphConverter
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.plugins.cors.routing.CORS
import kotlinx.serialization.Serializable
import org.jetbrains.kotlin.ir.symbols.UnsafeDuringIrConstructionAPI
import org.jetbrains.kotlin.ir.util.dump
fun main(args: Array<String>) {
io.ktor.server.netty.EngineMain.main(args)
}
fun Application.module() {
configureRouting()
install(CORS){
anyHost()
}
install(ContentNegotiation) {
json()
}
}
@OptIn(UnsafeDuringIrConstructionAPI::class)
fun Application.configureRouting() {
routing {
get("/api/isalive") {
call.respondText("OK")
}
post("/api/kotlinToMermaid") {
// get body as code
val kotlinCode = call.receiveText()
val compilationResult = getCompilationResult(kotlinCode)
val withOffsetCommentParam = call.request.queryParameters["withOffsetComment"]
val withOffsetComment = withOffsetCommentParam != null && withOffsetCommentParam.lowercase() == "true"
@Serializable
class CompilerMessageLocation(
val line: Int,
val column: Int
)
@Serializable
class CompilerMessage(
val severity: String,
val message: String,
val location: CompilerMessageLocation?
)
@Serializable
class Response(
val mermaidGraph: String?,
val messages: List<CompilerMessage>
)
val mermaidGraph = if (compilationResult.irModuleFragment == null) null
else IrMermaidGraphConverter.convertToMermaidGraph(compilationResult.irModuleFragment!!, withOffsetComment)
if (compilationResult.irModuleFragment == null) println("Result is null")
else {
compilationResult.irModuleFragment!!.files
.forEach { file ->
file.declarations.forEach { declaration ->
println(declaration.dump())
}
}
}
val renderedMessages = compilationResult.messages
.filter { it.severity.isError || it.severity.isWarning }
// Not relevant for the user
.filterNot { it.message.contains("Classpath entry points to a non-existent location") }
.map {
CompilerMessage(
severity = it.severity.presentableName,
message = it.message,
location = it.location?.let { loc ->
CompilerMessageLocation(loc.line, loc.column)
}
)
}
val response = Response(
mermaidGraph,
renderedMessages
)
call.respond(response)
}
staticResources("/", "static/dist")
}
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/index.css | CSS | @import "tailwindcss";
@import "tw-animate-css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
}
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.646 0.222 41.116);
--chart-2: oklch(0.6 0.118 184.704);
--chart-3: oklch(0.398 0.07 227.392);
--chart-4: oklch(0.828 0.189 84.429);
--chart-5: oklch(0.769 0.188 70.08);
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.488 0.243 264.376);
--chart-2: oklch(0.696 0.17 162.48);
--chart-3: oklch(0.769 0.188 70.08);
--chart-4: oklch(0.627 0.265 303.9);
--chart-5: oklch(0.645 0.246 16.439);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/index.html | HTML | <!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="./index.css" />
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<title>Kotlin IR Explorer</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/index.jsx"></script>
</body>
</html>
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/App.jsx | JavaScript (JSX) | import React from "react";
import CodeVisualizerPage from "./CodeVisualizer";
import { Toaster } from "@/components/ui/sonner"
export default () => (
<>
<CodeVisualizerPage/>
<Toaster/>
</>
);
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/CodeEditor.jsx | JavaScript (JSX) | import React, { useEffect, useRef, useState } from 'react';
import * as monaco from 'monaco-editor';
export default function CodeEditor({ code, onChangeContent, onChangeCursorPosition: onChangeCursorOffset }) {
const containerRef = useRef(null);
const [editor, setEditor] = useState(null);
useEffect(() => {
if (!containerRef.current) return;
// Define Kotlin language
if (!monaco.languages.getLanguages().some(({ id }) => id === 'kotlin')) {
monaco.languages.register({ id: 'kotlin' });
monaco.languages.setMonarchTokensProvider('kotlin', {
tokenizer: {
root: [
[/\b(package|import|class|interface|object|fun|val|var|when|if|else|for|while|return|constructor|companion|data|sealed|enum|override|open|private|protected|public|internal|final|abstract|suspend|lateinit|inline|get|set|this|super)\b/, 'keyword'],
[/\b(Int|String|Boolean|Float|Double|Long|Short|Byte|Any|Unit|Nothing)\b/, 'type'],
[/\/\/.*$/, 'comment'],
[/\/\*/, 'comment', '@comment'],
[/"/, 'string', '@string_double'],
[/'[^']*'/, 'string'],
[/\d+/, 'number'],
[/@\w+/, 'annotation'],
],
comment: [
[/[^/*]+/, 'comment'],
[/\/\*/, 'comment', '@push'],
[/\*\//, 'comment', '@pop'],
[/[/*]/, 'comment']
],
string_double: [
[/[^\\"]+/, 'string'],
[/\\./, 'string.escape'],
[/"/, 'string', '@pop']
]
}
});
}
// Define a dark dracula-inspired theme
monaco.editor.defineTheme('kotlinDarkDracula', {
base: 'vs-dark',
inherit: true,
rules: [
{ token: 'comment', foreground: '6272a4' },
{ token: 'keyword', foreground: 'ff79c6', fontStyle: 'bold' },
{ token: 'string', foreground: 'f1fa8c' },
{ token: 'number', foreground: 'bd93f9' },
{ token: 'type', foreground: '8be9fd' },
{ token: 'annotation', foreground: '50fa7b' },
],
colors: {
'editor.background': '#1a1c25',
'editor.foreground': '#f8f8f2',
'editor.lineHighlightBackground': '#2d303e',
'editor.selectionBackground': '#44475a',
'editorCursor.foreground': '#f8f8f2',
'editorWhitespace.foreground': '#3B3A32',
'editorIndentGuide.activeBackground': '#9D550FB0',
'editor.selectionHighlightBorder': '#222218'
}
});
// Initialize Monaco editor
const editorInstance = monaco.editor.create(containerRef.current, {
value: code,
language: 'kotlin',
theme: 'kotlinDarkDracula',
automaticLayout: true,
minimap: { enabled: true },
scrollBeyondLastLine: false,
fontSize: 14,
fontFamily: "'JetBrains Mono', 'Fira Code', Menlo, Monaco, 'Courier New', monospace",
lineNumbers: 'on',
renderLineHighlight: 'all',
scrollbar: {
useShadows: true,
verticalScrollbarSize: 10,
horizontalScrollbarSize: 10
},
padding: { top: 16 },
bracketPairColorization: { enabled: true },
autoClosingBrackets: 'always'
});
// Add event listener for content changes
const disposable = editorInstance.onDidChangeModelContent(() => {
onChangeContent(editorInstance.getValue());
});
editorInstance.onDidChangeCursorPosition((e) => {
// The editor speaks in position (line/column), the IR element speaks in offset (absolute int)
// The callback is in "IrSpeak" so we need to convert it
const offset = editorInstance.getModel().getOffsetAt(e.position)
onChangeCursorOffset(offset)
})
setEditor(editorInstance);
// Clean up
return () => {
disposable.dispose();
editorInstance.dispose();
};
}, [containerRef]);
// Update editor value when code prop changes
useEffect(() => {
if (editor && code !== editor.getValue()) {
editor.setValue(code);
}
}, [code, editor]);
return (
<div
ref={containerRef}
className="h-full w-full overflow-hidden flex-grow"
style={{
backgroundColor: '#1a1c25',
border: 'none',
outline: 'none'
}}
/>
);
} | yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/CodeVisualizer.jsx | JavaScript (JSX) | import React, { useState, useEffect, useRef } from "react";
import CodeEditor from "./CodeEditor";
import GraphViewer from "./GraphViewer";
import { Loader2 } from "lucide-react";
import KotlinLogo from './KotlinLogo.svg';
import axios from "axios";
import {editor} from "monaco-editor";
export default function CodeVisualizerPage() {
// Initial example Kotlin code
const [code, setCode] = useState(`// Example Kotlin code
fun main() {
var x = 5
if (x > 1 + 2) {
x += 1
listOf(1, 2)
}
}
`);
const [mermaidGraphText, setMermaidGraphText] = useState("");
const [cursorPositionOffset, setCursorPositionOffset] = useState(0)
const [mermaidGraphTextColored, setMermaidGraphTextColored] = useState("");
const [compilerMessages, setCompilerMessages] = useState([]);
const [isProcessing, setIsProcessing] = useState(false);
const [error, setError] = useState(null);
const timerRef = useRef(null);
// GPT-generated code for resizable layout
const [leftWidth, setLeftWidth] = useState(50); // percent
const containerRef = useRef(null);
const isDragging = useRef(false);
const startDragging = (e) => {
isDragging.current = true;
document.body.style.cursor = 'col-resize';
};
const stopDragging = () => {
isDragging.current = false;
document.body.style.cursor = '';
};
const onDrag = (e) => {
if (!isDragging.current || !containerRef.current) return;
const clientX = e.touches ? e.touches[0].clientX : e.clientX;
const rect = containerRef.current.getBoundingClientRect();
let percent = ((clientX - rect.left) / rect.width) * 100;
percent = Math.max(10, Math.min(90, percent)); // clamp between 10% and 90%
setLeftWidth(percent);
};
React.useEffect(() => {
const move = (e) => onDrag(e);
const up = () => stopDragging();
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
window.addEventListener('touchmove', move);
window.addEventListener('touchend', up);
return () => {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', up);
window.removeEventListener('touchmove', move);
window.removeEventListener('touchend', up);
};
}, []);
// End of GPT-generated code
const processCode = async (codeToProcess) => {
setIsProcessing(true);
setError(null);
try {
// In a real implementation, you'd send `codeToProcess` to your backend
// which would return the Mermaid graph *text representation*.
// TODO: How can I auto-recognize when this is run via npm run start, so I can know to use the localhost? :think:
const response = await axios.post("/api/kotlinToMermaid?withOffsetComment=true", codeToProcess)
// const response = await axios.post("http://localhost:8080/api/kotlinToMermaid?withOffsetComment=true", codeToProcess)
const graphText = response.data.mermaidGraph
const messages = response.data.messages
setMermaidGraphText(graphText)
setCompilerMessages(messages)
} catch (err) {
console.error("Error processing code:", err)
setError("Failed to generate graph. Please ensure your backend is running or check the placeholder logic.")
} finally {
setIsProcessing(false)
}
};
// Debounce of 250ms, to render the graph after the user stops typing
useEffect(() => {
if (code.trim() === '') {
setMermaidGraphText('classDiagram\n Empty["Type some Kotlin code to see the diagram"]\n classDef default fill:#2a2a3f,stroke:#6272a4,stroke-width:1px,color:#f8f8f2');
return
}
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
processCode(code);
}, 250);
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
}
};
}, [code]);
const handleCodeChange = (newCode) => {
setCode(newCode);
};
const handleCursorOffsetChange = (offset) => {
setCursorPositionOffset(offset)
};
// The actual displayed graph is the graph we got plus coloring on all elements which contain the cursor position
useEffect(() => {
if (!mermaidGraphText){ // null or empty
setMermaidGraphTextColored(null)
return
}
const newMermaidGraphTextLines = mermaidGraphText.split("\n")
.map(line => {
// Offset comment looks like: " # Offset: ${element.startOffset}-${element.endOffset}"
const offsetSplit = line.split(" %% Offset: ")
if (offsetSplit.length < 2) return line // No comment
const positions = offsetSplit[1].split("-").map(num => parseInt(num))
if (cursorPositionOffset > positions[1] || cursorPositionOffset < positions[0]) return offsetSplit[0]
return offsetSplit[0] + ":::selected" // Coloring classdef
})
const newMermaidGraphText = newMermaidGraphTextLines.join("\n") + "\n\n classDef selected stroke:#f00"
setMermaidGraphTextColored(newMermaidGraphText)
},
[cursorPositionOffset, mermaidGraphText]
)
const onWarningLocationClick = (location) => {
if (!location) return;
// Use Monaco editor's API to reveal the line
const lineNumber = location.line
const columnNumber = location.column
const editorInstance = editor.getEditors()[0]; // Assuming there's only one editor instance
if (editorInstance) {
editorInstance.revealLineInCenter(lineNumber);
editorInstance.setPosition({ lineNumber, column: columnNumber });
editorInstance.focus();
}
}
return (
<div className="flex flex-col h-screen bg-[#0f1117] text-slate-100">
<header className="sticky top-0 z-10 bg-[#1a1c25] border-b border-slate-800 px-4 py-3 flex items-center justify-between shadow-md">
<div className="flex items-center">
<div className="h-6 w-6 mr-2">
<img src={KotlinLogo}/>
</div>
<h1 className="text-xl font-semibold text-slate-100 mr-4">Kotlin IR Explorer</h1>
{isProcessing && (
<div className="flex items-center text-sky-400">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
<span className="text-sm">Processing...</span>
</div>
)}
</div>
</header>
<div className="flex flex-1 overflow-hidden" ref={containerRef}>
<div style={{width: `${leftWidth}%`}} className="h-full border-r border-slate-800 bg-[#1a1c25] min-w-[100px] max-w-[90%]">
<CodeEditor code={code} onChangeContent={handleCodeChange} onChangeCursorPosition={handleCursorOffsetChange} />
</div>
<div
style={{width: '6px', cursor: 'col-resize', zIndex: 20}}
className="h-full bg-slate-900 hover:bg-slate-700 transition-colors duration-100"
onMouseDown={startDragging}
onTouchStart={startDragging}
/>
<div style={{width: `${100 - leftWidth}%`}} className="h-full bg-[#1a1c25] p-4 overflow-auto min-w-[100px] max-w-[90%]">
<GraphViewer
mermaidGraphText={mermaidGraphTextColored}
compilerMessages={compilerMessages}
isProcessing={isProcessing}
error={error}
onWarningLocationClick={onWarningLocationClick}
/>
</div>
</div>
</div>
);
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/GraphViewer.jsx | JavaScript (JSX) | import React, {useEffect, useLayoutEffect, useRef, useState} from 'react';
import { Loader2, AlertTriangle, ImageOff } from 'lucide-react';
import mermaid from 'mermaid';
import svgPanZoom from 'svg-pan-zoom';
import {toast} from "sonner";
mermaid.initialize(
{
startOnLoad: false, // We will render manually
theme: 'dark', // Apply dark theme globally
// Dark theme configuration similar to Dracula
themeVariables: {
background: '#0f1117',
primaryColor: '#1a1c25', // Node background
primaryTextColor: '#f8f8f2',
primaryBorderColor: '#6272a4',
// lineColor: '#44475a',
secondaryColor: '#2d303e',
tertiaryColor: '#2d303e',
fontSize: '14px',
fontFamily: 'JetBrains Mono, Fira Code, Menlo, Monaco, Courier New, monospace',
// Specific for class diagrams
classText: '#f8f8f2',
},
securityLevel: 'loose', // Allow clicks etc
}
)
export default function GraphViewer({ mermaidGraphText, compilerMessages, isProcessing,
error, onWarningLocationClick }) {
const svgContainerRef = useRef(null);
const [renderError, setRenderError] = useState(null);
const [svg, setSvg] = useState(null);
const graphId = `mermaid-graph-${Date.now()}`;
// Render graph when text or library readiness changes
useEffect(() => {
if (!mermaidGraphText || isProcessing) return
setRenderError(null);
try {
// mermaid.render() returns a promise with the SVG
mermaid.render(graphId, mermaidGraphText)
.then(({svg, bindFunctions}) => {
if (svgContainerRef.current) {
svgContainerRef.current.innerHTML = svg;
if (bindFunctions) {
bindFunctions(svgContainerRef.current); // For interactivity if any
}
}
setSvg(svg);
})
.catch(err => {
console.error("Mermaid rendering error:", err);
setRenderError(`Diagram error: ${err.message || 'Could not render graph.'}`);
if (svgContainerRef.current) {
svgContainerRef.current.innerHTML = `<div class="text-red-400 p-4">Error rendering diagram. Check console.</div>`;
}
});
} catch (err) {
console.error("Synchronous Mermaid error:", err);
setRenderError(`Diagram error: ${err.message || 'Critical error.'}`);
if (svgContainerRef.current) {
svgContainerRef.current.innerHTML = `<div class="text-red-400 p-4">Critical diagram rendering error.</div>`;
}
}
}, [mermaidGraphText, isProcessing]);
useLayoutEffect(() => {
if (!svgContainerRef.current || !svg) return;
const svgElement = svgContainerRef.current.children[0];
// make svg size to its current size - required so it's not a tiny thing
svgElement.style.width = '100%';
svgElement.style.height = '100%';
svgElement.style.visibility = 'hidden'; // Hide until pan-zoom is applied
svgPanZoom(svgElement, {
controlIconsEnabled: true
})
svgElement.style.visibility = 'visible'; // Show the SVG after pan-zoom is applied
})
let content;
if (isProcessing) {
content = (
<div className="h-full flex flex-col items-center justify-center text-slate-400">
<Loader2 className="h-12 w-12 animate-spin mb-4 text-sky-400"/>
<p>{isProcessing ? "Processing Code..." : "Rendering Diagram..."}</p>
</div>
);
} else if (error || renderError) {
content = (
<div className="h-full flex flex-col items-center justify-center text-red-400">
<AlertTriangle className="h-12 w-12 mb-4"/>
<p className="font-semibold">Error</p>
<p className="text-sm text-red-500 mt-1">{error || renderError}</p>
</div>
);
} else if (!mermaidGraphText || mermaidGraphText.trim() === '') {
// This condition checks for specific placeholder texts in the mermaid string
content = (
<div className="h-full w-full flex flex-col items-center justify-center text-slate-400">
<ImageOff className="h-16 w-16 mb-4 text-slate-500"/>
{compilerMessages.map(message =>
<div className="mt-4 text-sm bg-[#2d303e] p-3 rounded-md text-left max-w w-full"
style={{cursor: 'pointer'}} // as
onClick={() => onWarningLocationClick(message.location)}>
{/*<p className="font-medium text-slate-300">Try a simple class:</p>*/}
<pre className="mt-2 overflow-x-auto text-xs bg-[#0f1117] p-2 rounded-md text-sky-300">
{
message.severity
+ (message.location ? ` (${message.location.line}:${message.location.column})` : '')
+ ": " + message.message
}
</pre>
</div>
)}
</div>
);
} else {
// The div will be populated by the useEffect hook
content = (
<div ref={svgContainerRef}
dangerouslySetInnerHTML={{__html: svg}}
className="w-full h-full flex justify-center items-center overflow-auto p-2 mermaid-live-container">
</div>
);
}
const copyMermaidGraphButton = <button
onClick={() => {
navigator.clipboard.writeText(mermaidGraphText)
.then(() => toast.success("Mermaid graph copied to clipboard!"))
}}
className="absolute top-2 right-2 z-10 bg-slate-800 hover:bg-slate-700 text-slate-200 px-3 py-1 rounded shadow text-xs border border-slate-700 focus:outline-none focus:ring-2 focus:ring-sky-400"
>
Copy Mermaid Graph
</button>
return (
<div
className="h-full w-full bg-[#0f1117] rounded-lg border border-slate-800 flex justify-center items-center overflow-hidden">
{content}
{copyMermaidGraphButton}
</div>
);
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/components/ui/button.tsx | TypeScript (TSX) | import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
destructive:
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/components/ui/dialog.tsx | TypeScript (TSX) | import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/components/ui/input.tsx | TypeScript (TSX) | import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/components/ui/sonner.tsx | TypeScript (TSX) | import { useTheme } from "next-themes"
import { Toaster as Sonner, ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/index.jsx | JavaScript (JSX) | import React from "react";
import { createRoot } from 'react-dom/client';
import App from "./App";
createRoot(document.getElementById('root')).render(<App/>)
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/src/lib/utils.ts | TypeScript | import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/main/resources/static/vite.config.mjs | JavaScript | import path from "path"
import tailwindcss from "@tailwindcss/vite"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
server/src/test/kotlin/github/yairm210/kotlin_ir_explorer/server/ApplicationTest.kt | Kotlin | package github.yairm210.kotlin_ir_explorer.server
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.Test
import kotlin.test.assertEquals
class ApplicationTest {
@Test
fun testRoot() = testApplication {
application {
// do not use module since this as built in content negotiation
configureRouting()
}
client.get("/api/isalive").apply {
assertEquals(HttpStatusCode.OK, status)
}
}
}
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
settings.gradle.kts | Kotlin | /*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.14/userguide/multi_project_builds.html in the Gradle documentation.
*/
plugins {
// Apply the foojay-resolver plugin to allow automatic download of JDKs
id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0"
}
rootProject.name = "kotlin-ir-explorer"
include("server", "core")
| yairm210/kotlin-ir-explorer | 25 | Kotlin IR graph visualizer | JavaScript | yairm210 | Yair Morgenstern | |
config/address.php | PHP | <?php
use Yajra\Address\Entities\Barangay;
use Yajra\Address\Entities\City;
use Yajra\Address\Entities\Province;
use Yajra\Address\Entities\Region;
return [
/*
* --------------------------------------------------------------------------
* API Route Prefix
* --------------------------------------------------------------------------
*/
'prefix' => '/api/address',
/*
* --------------------------------------------------------------------------
* API Route Middleware
* --------------------------------------------------------------------------
*/
'middleware' => [
'web',
'auth',
],
/*
* --------------------------------------------------------------------------
* PSA Official PSGC publication
* --------------------------------------------------------------------------
* @see https://psa.gov.ph/classification/psgc/
*/
'publication' => [
'path' => base_path('vendor/yajra/laravel-address/database/seeders/publication/PSGC-4Q-2024-Publication-Datafile.xlsx'),
'sheet' => 4,
],
/*
* --------------------------------------------------------------------------
* Models mapping
* --------------------------------------------------------------------------
*/
'models' => [
'region' => Region::class,
'province' => Province::class,
'city' => City::class,
'barangay' => Barangay::class,
],
];
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
database/migrations/2018_01_01_100000_create_ph_address_tables.php | PHP | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('regions', function (Blueprint $table) {
$table->id();
$table->string('code', 9)->unique();
$table->string('name');
$table->string('region_id', 2)->index();
});
Schema::create('provinces', function (Blueprint $table) {
$table->id();
$table->string('code', 9)->unique();
$table->string('name');
$table->string('region_id', 2)->index();
$table->string('province_id', 4)->index();
$table->index(['region_id', 'province_id'], 'province_idx_1');
});
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->string('code', 9)->unique();
$table->string('name');
$table->string('region_id', 2)->index();
$table->string('province_id', 4)->index();
$table->string('city_id', 6)->index();
$table->index(['region_id', 'province_id'], 'cities_idx_1');
$table->index(['region_id', 'province_id', 'city_id'], 'cities_idx_2');
});
Schema::create('barangays', function (Blueprint $table) {
$table->id();
$table->string('code', 9)->unique();
$table->string('name');
$table->string('region_id', 2)->index();
$table->string('province_id', 4)->index();
$table->string('city_id', 6)->index();
$table->index(['region_id', 'province_id'], 'barangay_idx_1');
$table->index(['region_id', 'province_id', 'city_id'], 'barangay_idx_2');
});
}
public function down(): void
{
Schema::drop('barangays');
Schema::drop('cities');
Schema::drop('provinces');
Schema::drop('regions');
}
};
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
database/migrations/2018_01_01_100001_upgrade_ph_address_tables.php | PHP | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('regions', function (Blueprint $table) {
$table->string('code', 10)->change();
});
Schema::table('provinces', function (Blueprint $table) {
$table->string('code', 10)->change();
$table->string('province_id', 5)->change();
});
Schema::table('cities', function (Blueprint $table) {
$table->string('code', 10)->change();
$table->string('province_id', 5)->change();
$table->string('city_id', 7)->change();
});
Schema::table('barangays', function (Blueprint $table) {
$table->string('code', 10)->change();
$table->string('region_id', 2)->change();
$table->string('province_id', 5)->change();
$table->string('city_id', 7)->change();
});
}
public function down(): void
{
// touch move T_T
}
};
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
database/migrations/2018_01_01_100002_add_address_correspondence_code.php | PHP | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('regions', function (Blueprint $table) {
$table->string('correspondence_code', 9)->after('code');
});
Schema::table('provinces', function (Blueprint $table) {
$table->string('correspondence_code', 9)->after('code');
});
Schema::table('cities', function (Blueprint $table) {
$table->string('correspondence_code', 9)->after('code');
});
Schema::table('barangays', function (Blueprint $table) {
$table->string('correspondence_code', 9)->after('code');
});
}
public function down(): void
{
Schema::dropColumns('regions', ['correspondence_code']);
Schema::dropColumns('provinces', ['correspondence_code']);
Schema::dropColumns('cities', ['correspondence_code']);
Schema::dropColumns('barangays', ['correspondence_code']);
}
};
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
database/seeders/AddressSeeder.php | PHP | <?php
namespace Yajra\Address\Seeders;
use Illuminate\Database\Seeder;
use Rap2hpoutre\FastExcel\FastExcel;
use Yajra\Address\Entities\Barangay;
use Yajra\Address\Entities\City;
use Yajra\Address\Entities\Province;
use Yajra\Address\Entities\Region;
class AddressSeeder extends Seeder
{
/**
* @throws \OpenSpout\Common\Exception\IOException
* @throws \OpenSpout\Common\Exception\UnsupportedTypeException
* @throws \OpenSpout\Reader\Exception\ReaderNotOpenedException
*/
public function run(): void
{
$publication = config('address.publication.path', __DIR__.'/publication/PSGC-3Q-2024-Publication-Datafile.xlsx');
$sheet = config('address.publication.sheet', 4);
$regions = [];
$provinces = [];
$cities = [];
$barangays = [];
$this->command->info(sprintf('Parsing PSA official PSGC publication (%s).', $publication));
(new FastExcel)
->sheet($sheet)
->import($publication, function ($line) use (&$regions, &$provinces, &$cities, &$barangays) {
$attributes = [];
$attributes['code'] = $line['10-digit PSGC'];
$attributes['correspondence_code'] = $line['Correspondence Code'];
$attributes['name'] = trim($line['Name']);
$attributes['region_id'] = substr($attributes['code'], 0, 2);
$geographicLevel = $line['Geographic Level'];
$cityClass = $line['City Class'];
if ($this->hasOwnProvince($geographicLevel, $attributes['region_id'], $cityClass)) {
$attributes['province_id'] = substr($attributes['code'], 0, 5);
$name = trim($line['Name']);
$provinces[] = [...$attributes, 'name' => $name];
}
switch ($geographicLevel) {
case 'Reg':
$regions[] = $attributes;
break;
case 'Dist':
case 'Prov':
case '':
$attributes['province_id'] = substr($attributes['code'], 0, 5);
$provinces[] = $attributes;
break;
case 'Bgy':
$attributes['province_id'] = substr($attributes['code'], 0, 5);
$attributes['city_id'] = substr($attributes['code'], 0, 7);
$barangays[] = $attributes;
break;
default: // City, SubMun, Mun
// Do not insert City of Manila
if ($attributes['code'] === '1380600000') {
break;
}
$attributes['province_id'] = substr($attributes['code'], 0, 5);
$attributes['city_id'] = substr($attributes['code'], 0, 7);
$name = str_replace('City of ', '', $attributes['name']);
$cities[] = [...$attributes, 'name' => $name];
break;
}
});
$this->command->info(sprintf('Seeding %s regions.', count($regions)));
$region = config('address.models.region', Region::class);
$region::query()->insert($regions);
$this->command->info(sprintf('Seeding %s provinces.', count($provinces)));
$province = config('address.models.province', Province::class);
collect($provinces)->chunk(100)->each(function ($chunk) use ($province) {
$province::query()->insert($chunk->toArray());
});
$city = config('address.models.city', City::class);
$this->command->info(sprintf('Seeding %s cities & municipalities.', count($cities)));
collect($cities)->chunk(100)->each(function ($chunk) use ($city) {
$city::query()->insert($chunk->toArray());
});
$this->command->info(sprintf('Seeding %s barangays.', count($barangays)));
$barangay = config('address.models.barangay', Barangay::class);
collect($barangays)->chunk(100)->each(function ($chunk) use ($barangay) {
$barangay::query()->insert($chunk->toArray());
});
}
protected function isMunicipalityInNCR(string $geographicLevel, string $regionId): bool
{
return in_array($geographicLevel, ['City', 'Mun']) && $regionId === '13';
}
protected function isHUC(string $geographicLevel, string $cityClass): bool
{
return $geographicLevel === 'City' && $cityClass === 'HUC';
}
protected function hasOwnProvince(string $geographicLevel, string $regionId, string $cityClass): bool
{
return $this->isMunicipalityInNCR($geographicLevel, $regionId)
|| $this->isHUC($geographicLevel, $cityClass);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/AddressServiceProvider.php | PHP | <?php
namespace Yajra\Address;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Yajra\Address\Controllers\BarangaysController;
use Yajra\Address\Controllers\CitiesController;
use Yajra\Address\Controllers\ProvincesController;
use Yajra\Address\Controllers\RegionsController;
use Yajra\Address\Repositories\Barangays\BarangaysRepository;
use Yajra\Address\Repositories\Barangays\BarangaysRepositoryEloquent;
use Yajra\Address\Repositories\Barangays\CachingBarangaysRepository;
use Yajra\Address\Repositories\Cities\CachingCitiesRepository;
use Yajra\Address\Repositories\Cities\CitiesRepository;
use Yajra\Address\Repositories\Cities\CitiesRepositoryEloquent;
use Yajra\Address\Repositories\Provinces\CachingProvincesRepository;
use Yajra\Address\Repositories\Provinces\ProvincesRepository;
use Yajra\Address\Repositories\Provinces\ProvincesRepositoryEloquent;
use Yajra\Address\Repositories\Regions\CachingRegionsRepository;
use Yajra\Address\Repositories\Regions\RegionsRepository;
use Yajra\Address\Repositories\Regions\RegionsRepositoryEloquent;
class AddressServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->loadMigrationsFrom(__DIR__.'/../database/migrations');
$this->mergeConfigFrom($config = __DIR__.'/../config/address.php', 'address');
if ($this->app->runningInConsole()) {
$this->publishes([$config => config_path('address.php')], 'address');
}
$this->setupViews();
$this->setupRoutes();
$this->setupMacro();
}
protected function setupViews(): void
{
view()->composer('address::form', function () {
/** @var RegionsRepository $repo */
$repo = app(RegionsRepository::class);
view()->share('regions', $repo->all()->pluck('name', 'region_id'));
});
$this->loadViewsFrom(__DIR__.'/Views', 'address');
$this->publishes([
__DIR__.'/Views' => resource_path('views/vendor/address'),
], 'address');
}
protected function setupRoutes(): void
{
Route::group([
'prefix' => config('address.prefix'),
'middleware' => config('address.middleware'),
'as' => 'address.',
], function () {
// Regions routes
Route::get('regions', [RegionsController::class, 'all'])->name('regions.all');
// Provinces routes
Route::get('provinces', [ProvincesController::class, 'all'])->name('provinces.all');
Route::get(
'provinces/{regionId}',
[ProvincesController::class, 'getByRegion']
)->name('provinces.region');
// Cities routes
Route::get(
'cities/{provinceId}',
[CitiesController::class, 'getByProvince']
)->name('cities.province');
Route::get(
'cities/{regionId}/{provinceId}',
[CitiesController::class, 'getByRegionAndProvince']
)->name('cities.region.province');
// Barangays routes
Route::get(
'barangays/{cityId}',
[BarangaysController::class, 'getByCity']
)->name('barangay.city');
});
}
protected function setupMacro(): void
{
Blueprint::macro('address', function () {
/** @var Blueprint $this */
$this->string('street')->nullable();
$this->string('barangay_id', 10)->nullable()->index();
$this->string('city_id', 7)->nullable()->index();
$this->string('province_id', 5)->nullable()->index();
$this->string('region_id', 2)->nullable()->index();
});
Blueprint::macro('dropAddress', function () {
/** @var Blueprint $this */
$this->dropColumn(['region_id', 'province_id', 'city_id', 'barangay_id', 'street']);
});
}
/**
* Register services.
*/
public function register(): void
{
$this->app->singleton(RegionsRepository::class, fn () => new CachingRegionsRepository(
$this->app->make(RegionsRepositoryEloquent::class),
resolve('cache.store')
));
$this->app->singleton(ProvincesRepository::class, fn () => new CachingProvincesRepository(
$this->app->make(ProvincesRepositoryEloquent::class),
resolve('cache.store')
));
$this->app->singleton(CitiesRepository::class, fn () => new CachingCitiesRepository(
$this->app->make(CitiesRepositoryEloquent::class),
resolve('cache.store')
));
$this->app->singleton(BarangaysRepository::class, fn () => new CachingBarangaysRepository(
$this->app->make(BarangaysRepositoryEloquent::class),
resolve('cache.store')
));
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Controllers/BarangaysController.php | PHP | <?php
namespace Yajra\Address\Controllers;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Routing\Controller;
use Yajra\Address\Repositories\Barangays\BarangaysRepository;
class BarangaysController extends Controller
{
public function __construct(protected BarangaysRepository $repository) {}
public function getByCity(string $cityId): Collection
{
return $this->repository->getByCity($cityId);
}
public function getBarangaysByRegionProvinceCityId(
string $regionId,
string $provinceId,
string $cityId
): Collection {
return $this->repository->getByRegionProvinceAndCityId($regionId, $provinceId, $cityId);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Controllers/CitiesController.php | PHP | <?php
namespace Yajra\Address\Controllers;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Routing\Controller;
use Yajra\Address\Repositories\Cities\CitiesRepository;
class CitiesController extends Controller
{
public function __construct(protected CitiesRepository $repository) {}
public function getByProvince(string $provinceId): Collection
{
return $this->repository->getByProvince($provinceId);
}
public function getByRegionAndProvince(string $regionId, string $provinceId): Collection
{
return $this->repository->getByRegionAndProvince($regionId, $provinceId);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Controllers/ProvincesController.php | PHP | <?php
namespace Yajra\Address\Controllers;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Routing\Controller;
use Yajra\Address\Repositories\Provinces\ProvincesRepository;
class ProvincesController extends Controller
{
public function __construct(protected ProvincesRepository $repository) {}
public function all(): Collection
{
return $this->repository->all();
}
public function getByRegion(string $regionId): Collection
{
return $this->repository->getByRegion($regionId);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Controllers/RegionsController.php | PHP | <?php
namespace Yajra\Address\Controllers;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Routing\Controller;
use Yajra\Address\Repositories\Regions\RegionsRepository;
class RegionsController extends Controller
{
public function __construct(protected RegionsRepository $repository) {}
public function all(): Collection
{
return $this->repository->all();
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Entities/Barangay.php | PHP | <?php
namespace Yajra\Address\Entities;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $code
* @property string $region_id
* @property string $province_id
* @property string $city_id
* @property string $barangay_id
* @property string $name
*/
class Barangay extends Model
{
protected $table = 'barangays';
public $timestamps = false;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Entities/City.php | PHP | <?php
namespace Yajra\Address\Entities;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $code
* @property string $region_id
* @property string $province_id
* @property string $city_id
* @property string $name
*/
class City extends Model
{
protected $table = 'cities';
public $timestamps = false;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Entities/Province.php | PHP | <?php
namespace Yajra\Address\Entities;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $code
* @property string $region_id
* @property string $province_id
* @property string $name
*/
class Province extends Model
{
protected $table = 'provinces';
public $timestamps = false;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Entities/Region.php | PHP | <?php
namespace Yajra\Address\Entities;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $code
* @property string $region_id
* @property string $name
*/
class Region extends Model
{
protected $table = 'regions';
public $timestamps = false;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/HasAddress.php | PHP | <?php
namespace Yajra\Address;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Yajra\Address\Entities\Barangay;
use Yajra\Address\Entities\City;
use Yajra\Address\Entities\Province;
use Yajra\Address\Entities\Region;
/**
* @property string $address
* @property string $street
* @property string $region_id
* @property Region $region
* @property string $province_id
* @property Province $province
* @property string $city_id
* @property City $city
* @property string $barangay_id
* @property Barangay $barangay
*/
trait HasAddress
{
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<Region>
*/
public function region(): BelongsTo
{
return $this->belongsTo(config('address.model.region', Region::class), 'region_id', 'region_id')->withDefault();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<Province>
*/
public function province(): BelongsTo
{
return $this->belongsTo(config('address.model.province', Province::class), 'province_id', 'province_id')->withDefault();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<City>
*/
public function city(): BelongsTo
{
return $this->belongsTo(config('address.model.city', City::class), 'city_id', 'city_id')->withDefault();
}
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<Barangay>
*/
public function barangay(): BelongsTo
{
return $this->belongsTo(config('address.model.barangay', Barangay::class), 'barangay_id', 'code')->withDefault();
}
public function getAddressAttribute(): string
{
return sprintf('%s %s, %s, %s',
$this->street,
$this->barangay->name,
$this->city->name,
$this->province->name
);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Barangays/BarangaysRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Barangays;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
interface BarangaysRepository
{
/**
* Get barangays by region, province and city ID.
*
* @return \Illuminate\Database\Eloquent\Collection<\Yajra\Address\Entities\Barangay>
*/
public function getByRegionProvinceAndCityId(string $regionId, string $provinceId, string $cityId): Collection;
/**
* Get barangays by region, province and city ID.
*
* @return \Illuminate\Database\Eloquent\Collection<\Yajra\Address\Entities\Barangay>
*/
public function getByCity(string $cityId): Collection;
/**
* @return \Yajra\Address\Entities\Barangay
*/
public function getModel(): Model;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Barangays/BarangaysRepositoryEloquent.php | PHP | <?php
namespace Yajra\Address\Repositories\Barangays;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Yajra\Address\Entities\Barangay;
use Yajra\Address\Repositories\EloquentBaseRepository;
class BarangaysRepositoryEloquent extends EloquentBaseRepository implements BarangaysRepository
{
public function getByCity(string $cityId): Collection
{
return $this->getModel()
->newQuery()
->where('city_id', $cityId)
->orderBy('name', 'asc')
->get();
}
/**
* @return Barangay
*/
public function getModel(): Model
{
$class = config('address.models.barangay', Barangay::class);
$model = new $class;
if (! is_subclass_of($model, Barangay::class)) {
return new Barangay;
}
return $model;
}
public function getByRegionProvinceAndCityId(string $regionId, string $provinceId, string $cityId): Collection
{
return $this->getModel()
->newQuery()
->where('region_id', $regionId)
->where('province_id', $provinceId)
->where('city_id', $cityId)
->orderBy('name', 'asc')
->get();
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Barangays/CachingBarangaysRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Barangays;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Database\Eloquent\Collection;
class CachingBarangaysRepository extends BarangaysRepositoryEloquent implements BarangaysRepository
{
public function __construct(public BarangaysRepository $repository, public Cache $cache)
{
parent::__construct();
}
public function getByRegionProvinceAndCityId(string $regionId, string $provinceId, string $cityId): Collection
{
$key = "barangays.{$regionId}.{$provinceId}.{$cityId}";
return $this->cache->rememberForever($key,
fn () => $this->repository->getByRegionProvinceAndCityId($regionId, $provinceId, $cityId));
}
public function getByCity(string $cityId): Collection
{
return $this->cache->rememberForever("barangays.{$cityId}", fn () => $this->repository->getByCity($cityId));
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Cities/CachingCitiesRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Cities;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Database\Eloquent\Collection;
class CachingCitiesRepository extends CitiesRepositoryEloquent implements CitiesRepository
{
public function __construct(public CitiesRepository $repository, public Cache $cache)
{
parent::__construct();
}
public function getByRegionAndProvince(string $regionId, string $provinceId): Collection
{
$key = "cities.{$regionId}.{$provinceId}";
return $this->cache->rememberForever($key,
fn () => $this->repository->getByRegionAndProvince($regionId, $provinceId));
}
public function getByProvince(string $provinceId): Collection
{
$key = "cities.{$provinceId}";
return $this->cache->rememberForever($key, fn () => $this->repository->getByProvince($provinceId));
}
public function getByRegion(string $regionId): Collection
{
$key = "cities.region.{$regionId}";
return $this->cache->rememberForever($key, fn () => $this->repository->getByRegion($regionId));
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Cities/CitiesRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Cities;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
interface CitiesRepository
{
/**
* Get province by region ID.
*
* @return \Illuminate\Database\Eloquent\Collection<\Yajra\Address\Entities\City>
*/
public function getByRegionAndProvince(string $regionId, string $provinceId): Collection;
/**
* Get cities by province.
*
* @return \Illuminate\Database\Eloquent\Collection<\Yajra\Address\Entities\City>
*/
public function getByProvince(string $provinceId): Collection;
/**
* Get cities by region.
*
* @return \Illuminate\Database\Eloquent\Collection<\Yajra\Address\Entities\City>
*/
public function getByRegion(string $regionId): Collection;
/**
* @return \Yajra\Address\Entities\City
*/
public function getModel(): Model;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Cities/CitiesRepositoryEloquent.php | PHP | <?php
namespace Yajra\Address\Repositories\Cities;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Yajra\Address\Entities\City;
use Yajra\Address\Repositories\EloquentBaseRepository;
class CitiesRepositoryEloquent extends EloquentBaseRepository implements CitiesRepository
{
public function getByRegionAndProvince(string $regionId, string $provinceId): Collection
{
return $this->getModel()
->newQuery()
->where('region_id', $regionId)
->where('province_id', $provinceId)
->orderBy('name', 'asc')
->get();
}
/**
* @return City
*/
public function getModel(): Model
{
$class = config('address.models.city', City::class);
$model = new $class;
if (! is_subclass_of($model, City::class)) {
return new City;
}
return $model;
}
public function getByRegion(string $regionId): Collection
{
return $this->getModel()
->newQuery()
->where('region_id', $regionId)
->orderBy('name', 'asc')
->get();
}
public function getByProvince(string $provinceId): Collection
{
return $this->getModel()
->newQuery()
->where('province_id', $provinceId)
->orderBy('name', 'asc')
->get();
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/EloquentBaseRepository.php | PHP | <?php
namespace Yajra\Address\Repositories;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
abstract class EloquentBaseRepository extends RepositoryAbstract
{
public function __construct()
{
$this->model = $this->getModel();
}
public function all(): Collection
{
return $this->model->newQuery()->get();
}
public function paginate(int $limit = 10): LengthAwarePaginator
{
return $this->model->newQuery()->paginate($limit);
}
public function create(array $attributes): Model
{
$model = $this->model->newInstance($attributes);
$model->save();
$this->resetModel();
return $model;
}
public function resetModel(): Model
{
return $this->model = $this->getModel();
}
public function make(array $attributes): Model
{
return $this->model->forceFill($attributes);
}
public function update(array $attributes, Model|int $id): Model
{
if (is_int($id)) {
$model = $this->model->newQuery()->findOrFail($id);
} else {
$model = $id;
}
$model->fill($attributes);
$model->save();
$this->resetModel();
return $model;
}
/**
* @throws \Exception
*/
public function delete(Model|int $id): ?bool
{
if (is_int($id)) {
$model = $this->model->newQuery()->findOrFail($id);
} else {
$model = $id;
}
$this->resetModel();
return $model->delete();
}
/**
* @throws ModelNotFoundException
*/
public function find(int $id, array $columns = ['*']): Model
{
$model = $this->model->newQuery()->findOrFail($id, $columns);
$this->resetModel();
return $model;
}
public function forModel(Model $model): static
{
$this->model = $model;
return $this;
}
public function count(): int
{
return $this->model->newQuery()->count();
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Provinces/CachingProvincesRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Provinces;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Database\Eloquent\Collection;
class CachingProvincesRepository extends ProvincesRepositoryEloquent implements ProvincesRepository
{
public function __construct(public ProvincesRepository $repository, public Cache $cache)
{
parent::__construct();
}
public function getByRegion(string $regionId): Collection
{
return $this->cache->rememberForever("provinces.{$regionId}", fn () => $this->repository->getByRegion($regionId));
}
public function all(): Collection
{
return $this->cache->rememberForever('provinces', fn () => $this->repository->all());
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Provinces/ProvincesRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Provinces;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
interface ProvincesRepository
{
/**
* @return \Illuminate\Database\Eloquent\Collection<array-key, \Yajra\Address\Entities\Province>
*/
public function getByRegion(string $regionId): Collection;
/**
* @return \Illuminate\Database\Eloquent\Collection<array-key, \Yajra\Address\Entities\Province>
*/
public function all(): Collection;
/**
* @return \Yajra\Address\Entities\Province
*/
public function getModel(): Model;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Provinces/ProvincesRepositoryEloquent.php | PHP | <?php
namespace Yajra\Address\Repositories\Provinces;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Yajra\Address\Entities\Province;
use Yajra\Address\Repositories\EloquentBaseRepository;
class ProvincesRepositoryEloquent extends EloquentBaseRepository implements ProvincesRepository
{
public function getByRegion(string $regionId): Collection
{
return $this->getModel()->newQuery()->where('region_id', $regionId)->orderBy('name', 'asc')->get();
}
/**
* @return Province
*/
public function getModel(): Model
{
$class = config('address.models.province', Province::class);
$model = new $class;
if (! is_subclass_of($model, Province::class)) {
return new Province;
}
return $model;
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Regions/CachingRegionsRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Regions;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Database\Eloquent\Collection;
class CachingRegionsRepository extends RegionsRepositoryEloquent implements RegionsRepository
{
public function __construct(public RegionsRepository $repository, public Cache $cache)
{
parent::__construct();
}
/**
* @return \Illuminate\Database\Eloquent\Collection<\Yajra\Address\Entities\Region>
*/
public function all(): Collection
{
return $this->cache->rememberForever(
'regions.all',
fn () => $this->repository->getModel()->query()->orderBy('region_id', 'asc')->get()
);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Regions/RegionsRepository.php | PHP | <?php
namespace Yajra\Address\Repositories\Regions;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
interface RegionsRepository
{
/**
* @return \Illuminate\Database\Eloquent\Collection<array-key, Model>
*/
public function all(): Collection;
/**
* @return \Yajra\Address\Entities\Region
*/
public function getModel(): Model;
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/Regions/RegionsRepositoryEloquent.php | PHP | <?php
namespace Yajra\Address\Repositories\Regions;
use Illuminate\Database\Eloquent\Model;
use Yajra\Address\Entities\Region;
use Yajra\Address\Repositories\EloquentBaseRepository;
class RegionsRepositoryEloquent extends EloquentBaseRepository implements RegionsRepository
{
public function getModel(): Model
{
$class = config('address.models.region', Region::class);
$model = new $class;
if (! is_subclass_of($model, Region::class)) {
return new Region;
}
return $model;
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Repositories/RepositoryAbstract.php | PHP | <?php
namespace Yajra\Address\Repositories;
use BadMethodCallException;
use Illuminate\Database\Eloquent\Model;
abstract class RepositoryAbstract
{
protected Model $model;
/**
* Handle dynamic static method calls into the method.
*
* @return mixed
*/
public static function __callStatic(string $method, array $parameters)
{
$instance = new static;
$class = $instance->getModel()::class;
$model = new $class;
$callback = [$model, $method];
if (! is_callable($callback)) {
throw new BadMethodCallException("Method [{$method}] does not exist.");
}
return call_user_func_array($callback, $parameters);
}
/**
* Get repository model.
*/
abstract public function getModel(): Model;
/**
* Handle dynamic method calls into the model.
*
* @return mixed
*/
public function __call(string $method, array $parameters)
{
$callback = [$this->getModel(), $method];
if (! is_callable($callback)) {
throw new BadMethodCallException("Method [{$method}] does not exist.");
}
return call_user_func_array($callback, $parameters);
}
}
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Views/form.blade.php | PHP | <div class="form-group {{$errors->has('region_id')}}">
<label>Region:</label>
{{html()->select('region_id', $regions)->class('form-control')}}
{{$errors->first('region_id')}}
</div>
<div class="form-group {{$errors->has('province_id')}}">
<label>Province:</label>
{{html()->select('province_id')->class('form-control')}}
{{$errors->first('province_id')}}
</div>
<div class="form-group {{$errors->has('city_id')}}">
<label>City:</label>
{{html()->select('city_id')->class('form-control')}}
{{$errors->first('city_id')}}
</div>
<div class="form-group {{$errors->has('barangay_id')}}">
<label>Barangay:</label>
{{html()->select('barangay_id')->class('form-control')}}
{{$errors->first('barangay_id')}}
</div>
<div class="form-group {{$errors->has('street')}}">
<label>Street:</label>
{{html()->text('street')->class('form-control')}}
{{$errors->first('street')}}
</div>
@push('scripts')
<script>
$(function () {
var address = {
province: '{{old('province_id', $model->province_id)}}',
city: '{{old('city_id', $model->city_id)}}',
barangay: '{{old('barangay_id', $model->barangay_id)}}',
};
$('#region_id').on('change', function () {
$.getJSON('{{config('address.prefix')}}/provinces/' + this.value, function (data) {
var options = '';
$.each(data, function (index, data) {
var selected = '';
if (data.province_id == address.province) {
selected = ' selected ';
}
options += '<option value="' + data.province_id + '"' + selected + '>' + data.name + '</option>';
});
$('#province_id').html(options);
$('#province_id').change();
});
});
$('#province_id').on('change', function () {
$.getJSON('{{config('address.prefix')}}/cities/' + this.value, function (data) {
var options = '';
$.each(data, function (index, data) {
var selected = '';
if (data.city_id == address.city) {
selected = ' selected ';
}
options += '<option value="' + data.city_id + '"' + selected + '>' + data.name + '</option>';
});
$('#city_id').html(options);
$('#city_id').change();
});
});
$('#city_id').on('change', function () {
$.getJSON('{{config('address.prefix')}}/barangays/' + this.value, function (data) {
var options = '';
$.each(data, function (index, data) {
var selected = '';
if (data.code == address.barangay) {
selected = ' selected ';
}
options += '<option value="' + data.code + '"' + selected + '>' + data.name + '</option>';
});
$('#barangay_id').html(options);
$('#barangay_id').change();
});
});
$('#region_id').change();
});
</script>
@endpush
| yajra/laravel-address | 40 | Philippines Regions, Provinces, Cities and Barangays Address Lookup API for Laravel. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/DataTables.php | PHP | <?php
namespace Yajra\DataTables\Ui;
use Laravel\Ui\Presets\Preset;
class DataTables extends Preset
{
/**
* Install the preset.
*
* @return void
*/
public static function install()
{
static::updatePackages();
static::updateSass();
static::updateBootstrapping();
static::removeNodeModules();
}
/**
* Update the Sass files for the application.
*
* @return void
*/
protected static function updateSass()
{
copy(__DIR__ . '/stubs/_variables.scss', resource_path('sass/_variables.scss'));
copy(__DIR__ . '/stubs/app.scss', resource_path('sass/app.scss'));
}
/**
* Update the bootstrapping files.
*
* @return void
*/
protected static function updateBootstrapping()
{
copy(__DIR__ . '/stubs/app.js', resource_path('js/app.js'));
copy(__DIR__ . '/stubs/bootstrap.js', resource_path('js/bootstrap.js'));
if (! is_dir(resource_path('js/vendor'))) {
mkdir(resource_path('js/vendor'));
}
copy(__DIR__ . '/stubs/dataTables.default.js', resource_path('js/vendor/dataTables.default.js'));
copy(
base_path('vendor/yajra/laravel-datatables-buttons/src/resources/assets/buttons.server-side.js'),
resource_path('js/vendor/buttons.server-side.js')
);
}
/**
* Update the given package array.
*
* @param array $packages
* @return array
*/
protected static function updatePackageArray(array $packages)
{
return [
"@fortawesome/fontawesome-free" => "^5.13.0",
"bootstrap" => "^4.0.0",
"datatables.net-autofill-bs4" => "^2.3.2",
"datatables.net-bs4" => "^1.10.21",
"datatables.net-buttons-bs4" => "^1.6.2",
"datatables.net-colreorder-bs4" => "^1.5.2",
"datatables.net-editor" => "^1.6.5",
"datatables.net-editor-bs4" => "^1.6.3",
"datatables.net-fixedcolumns-bs4" => "^3.3.1",
"datatables.net-fixedheader-bs4" => "^3.1.7",
"datatables.net-keytable-bs4" => "^2.5.2",
"datatables.net-plugins" => "^1.10.20",
"datatables.net-responsive-bs4" => "^2.2.5",
"datatables.net-rowgroup-bs4" => "^1.1.2",
"datatables.net-rowreorder-bs4" => "^1.2.7",
"datatables.net-scroller-bs4" => "^2.0.2",
"datatables.net-select-bs4" => "^1.3.1",
"jquery" => "^3.2",
"laravel-datatables-assets" => "https://github.com/yajra/laravel-datatables-assets",
"popper.js" => "^1.12",
] + $packages;
}
}
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/UiServiceProvider.php | PHP | <?php
namespace Yajra\DataTables\Ui;
use Laravel\Ui\UiCommand;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
class UiServiceProvider extends ServiceProvider
{
public function boot()
{
$this->registerCommand();
$this->registerViews();
Blade::include('datatables-ui::data-table', 'dataTable');
}
protected function registerCommand(): void
{
UiCommand::macro('dt', function (UiCommand $command) {
DataTables::install();
$command->info('DataTables scaffolding installed successfully.');
$command->comment('When using Editor, you must add this script on package.json: "postinstall": "node ./node_modules/datatables.net-editor/install.js ./path-to/Editor.zip".');
$command->comment('Please run "npm install && npm run dev" to compile your fresh scaffolding.');
});
}
protected function registerViews(): void
{
$this->loadViewsFrom(__DIR__ . '/views', 'datatables-ui');
if ($this->app->runningInConsole()) {
$this->publishes([__DIR__ . '/views' => resource_path('views/vendor/datatables-ui')], 'datatables-ui');
}
}
}
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/stubs/_variables.scss | SCSS | // Body
$body-bg: #f8fafc;
// Typography
$font-family-sans-serif: 'Nunito', sans-serif;
$font-size-base: 0.9rem;
$line-height-base: 1.6;
// Colors
$blue: #3490dc;
$indigo: #6574cd;
$purple: #9561e2;
$pink: #f66d9b;
$red: #e3342f;
$orange: #f6993f;
$yellow: #ffed4a;
$green: #38c172;
$teal: #4dc0b5;
$cyan: #6cb2eb;
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/stubs/app.js | JavaScript | /**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/
require('./bootstrap');
require('./vendor/dataTables.default');
/**
* When using DataTable Editor, it is advisable to use the assets below than the buttons.server-side.js script.
* Note: buttons.server-side.js have a conflict create button for Editor.
*/
require('./vendor/buttons.server-side');
// require('laravel-datatables-assets/js/dataTables.buttons');
// require('laravel-datatables-assets/js/dataTables.renderers');
// require('laravel-datatables-assets/js/dataTables.callbacks');
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/stubs/app.scss | SCSS | // Fonts
@import url('https://fonts.googleapis.com/css?family=Nunito');
// Variables
@import 'variables';
// Bootstrap
@import '~bootstrap/scss/bootstrap';
// DataTables
@import "~datatables.net-bs4/css/dataTables.bootstrap4.css";
@import "~datatables.net-buttons-bs4/css/buttons.bootstrap4.css";
@import "~datatables.net-responsive-bs4/css/responsive.bootstrap4.css";
@import "~datatables.net-editor-bs4/css/editor.bootstrap4.css";
@import "~datatables.net-select-bs4/css/select.bootstrap4.css";
@import "~datatables.net-keytable-bs4/css/keyTable.bootstrap4.css";
@import "~datatables.net-fixedcolumns-bs4/css/fixedColumns.bootstrap4.css";
@import "~datatables.net-autofill-bs4/css/autoFill.bootstrap4.css";
// FontAwesome
@import '~@fortawesome/fontawesome-free/scss/brands';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/stubs/bootstrap.js | JavaScript | window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
window.$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': window.$('meta[name="csrf-token"]').attr('content')
}
});
require('bootstrap');
require('datatables.net-bs4');
// require('datatables.net-editor-bs4');
require('datatables.net-autofill-bs4');
require('datatables.net-buttons-bs4');
require('datatables.net-buttons/js/buttons.colVis.js');
require('datatables.net-colreorder-bs4');
require('datatables.net-fixedcolumns-bs4');
require('datatables.net-fixedheader-bs4');
require('datatables.net-keytable-bs4');
require('datatables.net-responsive-bs4');
require('datatables.net-rowgroup-bs4');
require('datatables.net-rowreorder-bs4');
require('datatables.net-scroller-bs4');
require('datatables.net-select-bs4');
} catch (e) {}
/**
* We'll load the axios HTTP library which allows us to easily issue requests
* to our Laravel back-end. This library automatically handles sending the
* CSRF token as a header based on the value of the "XSRF" token cookie.
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from 'laravel-echo';
// window.Pusher = require('pusher-js');
// window.Echo = new Echo({
// broadcaster: 'pusher',
// key: process.env.MIX_PUSHER_APP_KEY,
// cluster: process.env.MIX_PUSHER_APP_CLUSTER,
// forceTLS: true
// });
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/stubs/dataTables.default.js | JavaScript | /* Set the defaults for DataTables initialisation */
$.extend(true, $.fn.dataTable.defaults, {
dom:
"<'row'<'col-md-12'B>>" +
"<'row mt-2'<'col-sm-12 col-md-6'i><'col-sm-12 col-md-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row mt-2'<'col-sm-12 col-md-5'l><'col-sm-12 col-md-7'p>>",
searchDelay: 1500,
deferRender: true,
autoWidth: false, // disable fixed width and enable fluid table
pageLength: 25, // default records per page
buttons: [],
pagingType: 'full_numbers'
});
$.fn.dataTable.ext.errMode = 'none';
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/views/data-table.blade.php | PHP | {{ isset($table) ? $table->table($attributes ?? []) : $dataTable->table($attributes ?? []) }}
@push('scripts')
{{ isset($table) ? $table->scripts() : $dataTable->scripts() }}
@endpush
| yajra/laravel-datatables-ui | 10 | Laravel DataTables UI Preset | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/ControlFileBuilder.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use LogicException;
use Stringable;
class ControlFileBuilder implements Stringable
{
public function __construct(public SQLLoader $loader) {}
public function __toString(): string
{
return $this->build();
}
public function build(): string
{
$template = File::get($this->getStub());
$sql = Str::of($template)
->replace('$OPTIONS', $this->options())
->replace('$FILES', $this->inputFiles())
->replace('$METHOD', $this->method())
->replace('$INSERTS', $this->inserts())
->replace("\$BEGINDATA\n", $this->beginData())
->toString();
if ($this->loader->beginData) {
// remove last new line from the $sql when beginData is set.
$sql = substr($sql, 0, -1);
}
return $sql;
}
protected function getStub(): string
{
return __DIR__.'/stubs/control.stub';
}
protected function options(): string
{
return implode(', ', $this->loader->options);
}
protected function inputFiles(): string
{
$inputFiles = implode(PHP_EOL, $this->loader->inputFiles);
return Str::replace("'*'", '*', $inputFiles);
}
protected function method(): string
{
return in_array($this->loader->mode, [
Mode::INSERT,
Mode::TRUNCATE,
]) ? Mode::TRUNCATE->value : $this->loader->mode->value;
}
protected function inserts(): string
{
return implode(PHP_EOL, $this->loader->tables);
}
protected function beginData(): string
{
$sql = '';
if ($this->loader->beginData) {
$sql .= 'BEGINDATA'.PHP_EOL;
$sql .= $this->arrayToCsv($this->loader->beginData);
}
return $sql;
}
protected function arrayToCsv(
array $data,
string $delimiter = ',',
string $enclosure = '"',
string $escape_char = '\\'
): string {
$f = fopen('php://memory', 'r+');
if (! $f) {
throw new LogicException('Failed to open memory stream');
}
foreach ($data as $item) {
fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
}
rewind($f);
$contents = stream_get_contents($f);
if (! $contents) {
throw new LogicException('Failed to read memory stream');
}
return $contents;
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/CsvFile.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
use Illuminate\Support\Facades\File;
final class CsvFile
{
/**
* @param resource $stream
*/
private function __construct(public string $file, public $stream) {}
/**
* A list of possible modes. The default is 'w' (open for writing).:
*
* 'r' - Open for reading only; place the file pointer at the beginning of the file.
* 'r+' - Open for reading and writing; place the file pointer at the beginning of the file.
* 'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
* 'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
* 'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
* 'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
* 'x' - Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen call will fail by returning false and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
* 'x+' - Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen call will fail by returning false and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
*
* @see https://www.php.net/manual/en/function.fopen.php
*/
public static function make(string $filename, string $mode = 'w'): CsvFile
{
$csv = self::create($filename);
$stream = fopen($csv, $mode);
if ($stream === false) {
throw new \RuntimeException("Failed to open file [{$csv}].");
}
return new self($csv, $stream);
}
public static function create(string $file): string
{
$directory = File::dirname($file);
if (! File::isDirectory($directory)) {
File::makeDirectory($directory, 0755, true, true);
}
if (! File::exists($file)) {
File::append($file, '');
}
return $file;
}
public function append(
array $fields,
string $separator = ',',
string $enclosure = '"',
string $escape = '\\',
string $eol = PHP_EOL
): CsvFile {
fputcsv($this->stream, $fields, $separator, $enclosure, $escape, $eol);
return $this;
}
public static function blank(string $file): string
{
if (File::exists($file)) {
File::delete($file);
}
return self::create($file);
}
public function close(): void
{
$this->__destruct();
}
public function __destruct()
{
if (is_resource($this->stream)) {
fclose($this->stream);
}
}
public function headers(array $fields): CsvFile
{
if ($this->isEmpty()) {
$this->append($fields);
}
return $this;
}
public function isEmpty(): bool
{
clearstatcache(true, $this->file);
return filesize($this->file) === 0;
}
public function insert(array $updates): CsvFile
{
foreach ($updates as $row) {
$this->append($row);
}
return $this;
}
public function get(): string
{
$contents = file_get_contents($this->file);
if ($contents === false) {
return '';
}
return $contents;
}
/**
* @param null|int<0, max> $length
*/
public function getHeaders(?int $length = null): array
{
$headers = fgetcsv($this->stream, $length);
if ($headers === false) {
return [];
}
return array_map(fn ($header) => str_replace(["\r", "\n"], '', $header), $headers);
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/InputFile.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
use Stringable;
class InputFile implements Stringable
{
public function __construct(
public string $path,
public ?string $badFile = null,
public ?string $discardFile = null,
public ?string $discardMax = null,
public ?string $osFileProcClause = null,
) {}
public function __toString(): string
{
$sql = "INFILE '{$this->path}'";
if ($this->osFileProcClause) {
$sql .= " \"{$this->osFileProcClause}\"";
}
if ($this->badFile) {
$sql .= " BADFILE '{$this->badFile}'";
}
if ($this->discardFile) {
$sql .= " DISCARDFILE '{$this->discardFile}'";
}
if ($this->discardMax) {
$sql .= " DISCARDMAX {$this->discardMax}";
}
return $sql;
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/Mode.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
enum Mode: string
{
case INSERT = 'INSERT';
case APPEND = 'APPEND';
case REPLACE = 'REPLACE';
case TRUNCATE = 'TRUNCATE';
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/SQLLoader.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Contracts\Process\ProcessResult;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use InvalidArgumentException;
use LogicException;
class SQLLoader
{
/** @var InputFile[] */
public array $inputFiles = [];
/** @var TableDefinition[] */
public array $tables = [];
public Mode $mode = Mode::APPEND;
public ?string $controlFile = null;
public array $beginData = [];
public ?string $connection = null;
protected array $defaultColumns = [];
public array $constants = [];
protected ?string $disk = null;
protected ?string $logPath = null;
protected ?ProcessResult $result = null;
protected bool $deleteFiles = false;
protected string $logs = '';
protected string $dateFormat = 'YYYY-MM-DD"T"HH24:MI:SS."000000Z"';
public function __construct(public array $options = []) {}
/**
* Define mode to use.
*/
public function mode(Mode $mode): static
{
$this->mode = $mode;
return $this;
}
/**
* Define table to load data into.
*/
public function into(
string $table,
array $columns = [],
?string $terminatedBy = ',',
?string $enclosedBy = '"',
bool $trailing = true,
array $formatOptions = [],
?string $when = null,
bool $csv = false,
bool $withEmbedded = true,
): static {
if (! $columns && $this->defaultColumns) {
$columns = $this->createColumnsFromHeaders($table, $this->defaultColumns);
}
if (! $formatOptions) {
$formatOptions = [
"DATE FORMAT '".$this->dateFormat."'",
"TIMESTAMP FORMAT '".$this->dateFormat."'",
"TIMESTAMP WITH TIME ZONE '".$this->dateFormat."'",
"TIMESTAMP WITH LOCAL TIME ZONE '".$this->dateFormat."'",
];
}
$columns = array_merge($columns, $this->constants);
$table = DB::connection($this->getConnection())->getQueryGrammar()->wrapTable($table);
$this->tables[] = new TableDefinition(
$table, $columns, $terminatedBy, $enclosedBy, $trailing, $formatOptions, $when, $csv, $withEmbedded
);
return $this;
}
public function createColumnsFromHeaders(string $table, array $columns): array
{
$columns = array_map('strtolower', $columns);
$schemaColumns = collect(Schema::connection($this->getConnection())->getColumns($table));
$dates = $schemaColumns->filter(fn ($column) => in_array($column['type'], [
'date',
'datetime',
'timestamp',
'timestamp(6)',
]))->pluck('name')->toArray();
$booleans = $schemaColumns->filter(
fn ($column) => $column['nullable'] === false && $column['type'] === 'char' && $column['length'] === 1
)->pluck('name')->toArray();
foreach ($columns as $key => $column) {
$escapedColumn = '"'.strtoupper((string) $column).'"';
if (in_array($column, $dates)) {
$columns[$key] = "{$escapedColumn} DATE";
continue;
}
if (in_array($column, $booleans)) {
$default = trim((string) $schemaColumns->where('name', $column)->first()['default']);
$default = $default ?: "'0'"; // set value to 0 if default is empty since column is not nullable
$columns[$key] = "{$escapedColumn} \"DECODE(:{$column}, '', {$default}, :{$column})\"";
continue;
}
if (! $schemaColumns->contains('name', $column)) {
$columns[$key] = "{$escapedColumn} FILLER";
continue;
}
$columns[$key] = "{$escapedColumn}";
}
return $columns;
}
public function connection(string $connection): static
{
$this->connection = $connection;
return $this;
}
/**
* Execute SQL Loader command.
*/
public function execute(int $timeout = 3600): ProcessResult
{
if (! $this->tables) {
throw new InvalidArgumentException('At least one table definition is required.');
}
if (! $this->inputFiles) {
throw new InvalidArgumentException('Input file is required.');
}
$this->result = Process::timeout($timeout)->run($this->buildCommand());
if ($this->deleteFiles) {
if ($this->logPath && File::exists($this->logPath)) {
$this->logs = File::get($this->logPath);
}
$this->deleteGeneratedFiles();
}
return $this->result; // @phpstan-ignore-line
}
/**
* Build SQL Loader command.
*/
protected function buildCommand(): string
{
$filesystem = $this->getDisk();
$file = $this->getControlFile();
$filesystem->put($file, $this->buildControlFile());
$tns = $this->buildTNS();
$binary = $this->getSqlLoaderBinary();
$filePath = $filesystem->path($file);
$command = "$binary userid=$tns control={$filePath}";
if (! $this->logPath) {
$this->logPath = str_replace('.ctl', '.log', (string) $filePath);
$command .= " log={$this->logPath}";
}
return $command;
}
/**
* Get the disk to use for control file.
*/
public function getDisk(): Filesystem
{
if ($this->disk) {
return Storage::disk($this->disk);
}
return Storage::disk(config('sql-loader.disk', 'local'));
}
/**
* Set the disk to use for control file.
*/
public function disk(string $disk): static
{
$this->disk = $disk;
return $this;
}
/**
* Get the control file name.
*/
protected function getControlFile(): string
{
if (! $this->controlFile) {
$this->controlFile = Str::uuid().'.ctl';
}
return $this->controlFile;
}
/**
* Build SQL Loader control file.
*/
public function buildControlFile(): string
{
return (new ControlFileBuilder($this))->build();
}
/**
* Build TNS connection string.
*/
protected function buildTNS(): string
{
return TnsBuilder::make($this->getConnection());
}
/**
* Create a new SQL Loader instance.
*/
public static function make(array $options = []): SQLLoader
{
return new self($options);
}
public function getConnection(): string
{
return $this->connection ?? config('sql-loader.connection', 'oracle');
}
/**
* Get the SQL Loader binary path.
*/
public function getSqlLoaderBinary(): string
{
return config('sql-loader.sqlldr', 'sqlldr');
}
/**
* Delete generated files after execution.
*/
protected function deleteGeneratedFiles(): void
{
if ($this->logPath && File::exists($this->logPath)) {
File::delete($this->logPath);
}
foreach ($this->inputFiles as $inputFile) {
if ($inputFile->path !== '*') {
File::delete($inputFile->path);
}
if ($inputFile->badFile && File::exists($inputFile->badFile)) {
File::delete($inputFile->badFile);
}
if ($inputFile->discardFile && File::exists($inputFile->discardFile)) {
File::delete($inputFile->discardFile);
}
}
$filesystem = $this->getDisk();
if ($this->controlFile && $filesystem->exists($this->controlFile)) {
$filesystem->delete($this->controlFile);
}
}
/**
* Set the control file name.
*/
public function as(string $controlFile): static
{
if (! Str::endsWith($controlFile, '.ctl')) {
$controlFile .= '.ctl';
}
$this->controlFile = $controlFile;
return $this;
}
/**
* Set the log file path.
*/
public function logsTo(string $path): static
{
$this->logPath = $path;
return $this;
}
/**
* Check if SQL Loader execution was successful.
*/
public function successful(): bool
{
if (is_null($this->result)) {
return false;
}
return $this->result->successful();
}
/**
* Get the SQL Loader command, file path and result details.
*/
public function debug(): string
{
$debug = 'Command:'.PHP_EOL.$this->buildCommand().PHP_EOL.PHP_EOL;
$debug .= 'Control File:'.PHP_EOL.$this->buildControlFile().PHP_EOL;
if ($this->result) {
$debug .= 'Output:'.$this->result->output().PHP_EOL.PHP_EOL;
$debug .= 'Error Output:'.PHP_EOL.$this->result->errorOutput().PHP_EOL;
$debug .= 'Exit Code: '.$this->result->exitCode().PHP_EOL.PHP_EOL;
}
return $debug;
}
/**
* Get the SQL Loader output.
*/
public function output(): string
{
if (is_null($this->result)) {
return 'No output available';
}
return $this->result->output();
}
/**
* Get the SQL Loader error output.
*/
public function errorOutput(): string
{
if (is_null($this->result)) {
return 'No error output available';
}
return $this->result->errorOutput();
}
/**
* Set the flag to delete generated files after execution.
*/
public function deleteFilesAfterRun(bool $delete = true): static
{
$this->deleteFiles = $delete;
return $this;
}
/**
* Get the SQL Loader execution logs.
*/
public function logs(): string
{
if ($this->logs) {
return $this->logs;
}
if ($this->logPath && File::exists($this->logPath)) {
return File::get($this->logPath);
}
return 'No log file available';
}
/**
* Get the SQL Loader process result.
*/
public function result(): ProcessResult
{
if (! $this->result) {
throw new LogicException('Please run execute method first.');
}
return $this->result;
}
/**
* Set the data to be loaded.
*/
public function beginData(array $data): static
{
$this->inputFiles = [];
$this->inFile('*');
$this->beginData = $data;
return $this;
}
/**
* Define input file to load data from.
*/
public function inFile(
string $path,
?string $badFile = null,
?string $discardFile = null,
?string $discardMax = null,
?string $osFileProcClause = null,
): static {
if (! File::exists($path) && ! Str::contains($path, ['*', '?'])) {
throw new InvalidArgumentException("File [{$path}] does not exist.");
}
$this->inputFiles[] = new InputFile($path, $badFile, $discardFile, $discardMax, $osFileProcClause);
return $this;
}
public function withHeaders(): static
{
$this->options(['skip=1']);
$path = $this->inputFiles[0]->path;
if (Str::contains($path, ['*', '?'])) {
$files = File::allFiles(dirname($path));
$headers = CsvFile::make($files[0]->getPathname(), 'r')->getHeaders();
} else {
$headers = CsvFile::make($this->inputFiles[0]->path, 'r')->getHeaders();
}
$this->defaultColumns = $headers;
return $this;
}
/**
* Set SQL Loader options.
*/
public function options(array $options): static
{
$this->options = $options;
return $this;
}
public function dateFormat(string $format): static
{
$this->dateFormat = $format;
return $this;
}
public function constants(array $constants): static
{
$this->constants = $constants;
return $this;
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/SQLLoaderServiceProvider.php | PHP | <?php
namespace Yajra\SQLLoader;
use Illuminate\Support\ServiceProvider;
class SQLLoaderServiceProvider extends ServiceProvider
{
public function boot(): void
{
$this->mergeConfigFrom(__DIR__.'/config/sql-loader.php', 'sql-loader');
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/config/sql-loader.php' => config_path('sql-loader.php'),
], 'config');
}
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/TableDefinition.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
use Stringable;
class TableDefinition implements Stringable
{
public function __construct(
public string $table,
public array $columns,
public ?string $terminatedBy = null,
public ?string $enclosedBy = null,
public bool $trailing = false,
public array $formatOptions = [],
public ?string $when = null,
public bool $csv = false,
public bool $withEmbedded = true,
) {}
public function __toString(): string
{
$sql = "INTO TABLE {$this->table}".PHP_EOL;
if ($this->when) {
$sql .= "WHEN {$this->when}".PHP_EOL;
}
$sql .= $this->delimiterSpecification();
if ($this->formatOptions) {
$sql .= implode(PHP_EOL, $this->formatOptions).PHP_EOL;
}
if ($this->trailing) {
$sql .= 'TRAILING NULLCOLS'.PHP_EOL;
}
$sql .= '('.PHP_EOL;
if ($this->columns) {
$sql .= implode(
','.PHP_EOL,
array_map(fn ($column) => str_repeat(' ', 2).$column, $this->columns)
).PHP_EOL;
}
$sql .= ')'.PHP_EOL;
return $sql;
}
private function delimiterSpecification(): string
{
$specs = ['FIELDS'];
if ($this->csv) {
$specs[] = 'CSV';
$specs[] = $this->withEmbedded ? 'WITH EMBEDDED' : 'WITHOUT EMBEDDED';
}
if ($this->terminatedBy) {
$specs[] = "TERMINATED BY '{$this->terminatedBy}'";
}
if ($this->enclosedBy) {
$specs[] = "OPTIONALLY ENCLOSED BY '{$this->enclosedBy}'";
}
if (count($specs) > 1) {
return implode(' ', $specs).PHP_EOL;
}
return '';
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/TnsBuilder.php | PHP | <?php
declare(strict_types=1);
namespace Yajra\SQLLoader;
class TnsBuilder
{
public static function make(?string $connection = null): string
{
$connection ??= config('sql-loader.connection', 'oracle');
$username = config('database.connections.'.$connection.'.username');
$password = config('database.connections.'.$connection.'.password');
$host = config('database.connections.'.$connection.'.host');
$port = config('database.connections.'.$connection.'.port');
$database = config('database.connections.'.$connection.'.database');
return $username.'/'.$password.'@'.$host.':'.$port.'/'.$database;
}
}
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
src/config/sql-loader.php | PHP | <?php
return [
/* ------------------------------------------------------
* Oracle database connection name.
* ------------------------------------------------------
*/
'connection' => env('SQL_LOADER_CONNECTION', 'oracle'),
/* ------------------------------------------------------
* SQL Loader binary path.
* ------------------------------------------------------
*/
'sqlldr' => env('SQL_LOADER_PATH', '/usr/local/bin/sqlldr'),
/* ------------------------------------------------------
* Disk storage to store control files.
* ------------------------------------------------------
*/
'disk' => env('SQL_LOADER_DISK', 'local'),
];
| yajra/laravel-sql-loader | 9 | Oracle SQL*Loader for Laravel | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Console/Commands/GenerateSitemap.php | PHP | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Psr\Http\Message\UriInterface;
use Spatie\Sitemap\SitemapGenerator;
use Spatie\Sitemap\SitemapIndex;
use Spatie\Sitemap\Tags\Url;
class GenerateSitemap extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sitemap:generate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate the sitemap.';
/**
* Execute the console command.
*/
public function handle(): int
{
$appUrl = Config::string('app.url');
SitemapGenerator::create($appUrl)
->shouldCrawl(function (UriInterface $url) {
// Crawl everything without "docs" in the path, as we'll crawl the docs separately...
return ! Str::contains($url->getPath(), 'docs');
})
->hasCrawled(function (Url $url) {
if ($url->segment(1) === 'team') {
$url->setPriority(0.5);
}
return $url;
})
->writeToFile(public_path('sitemap_pages.xml'));
$sitemapIndex = SitemapIndex::create()
->add('sitemap_pages.xml');
foreach (Config::array('docs.packages') as $package => $options) {
foreach ($options['versions'] as $version => $versionOptions) {
SitemapGenerator::create($appUrl.'/docs/'.$package.'/'.$version)
->shouldCrawl(function (UriInterface $url) {
return Str::contains($url->getPath(), 'docs');
})
->writeToFile(public_path('sitemap_'.$package.'_'.$version.'.xml'));
$sitemapIndex->add('sitemap_'.$package.'_'.$version.'.xml');
}
}
$sitemapIndex->writeToFile(public_path('sitemap.xml'));
return 0;
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Documentation.php | PHP | <?php
namespace App;
use App\Markdown\GithubFlavoredMarkdownConverter;
use Carbon\CarbonInterval;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use League\CommonMark\Output\RenderedContentInterface;
class Documentation
{
public function __construct(
protected Filesystem $files,
protected Cache $cache
) {}
/**
* Get the publicly available versions of the documentation
*/
public static function getDefaultVersion(string $package): string
{
return Config::string('docs.packages.'.$package.'.default', DEFAULT_VERSION);
}
/**
* Get the documentation index page.
*/
public function getIndex(string $package, string $version): string
{
return $this->cache->remember($package.'.docs.'.$version.'.index', 5,
function () use ($package, $version) {
$path = $this->getBasePath($package, $version).'/documentation.md';
if (! $this->files->exists($path)) {
return '';
}
$content = file_get_contents($path);
if (! $content) {
return '';
}
$content = $this->replaceLinks($package, $version, $content);
return $this->convertToMarkdown($content);
}
);
}
/**
* Get base path of the package docs.
*/
protected function getBasePath(string $package, string $version): string
{
return resource_path('docs/'.$package.'/'.$version);
}
/**
* Check if documentation exists for the given package.
*/
public static function exists(string $package): bool
{
return (bool) config('docs.packages.'.$package);
}
/**
* Replace the version place-holder in links.
*/
public static function replaceLinks(string $package, string $version, string $content): string
{
$content = str_replace('{{package}}', $package, $content);
return str_replace('{{version}}', $version, $content);
}
public function convertToMarkdown(string $content): RenderedContentInterface
{
return (new GithubFlavoredMarkdownConverter)->convert($content);
}
/**
* Get the array based index representation of the documentation.
*/
public function indexArray(string $package, string $version): array
{
return $this->cache->remember('docs.{'.$package.':'.$version.'}.index', CarbonInterval::hour(1),
function () use ($package, $version) {
$path = resource_path("docs/$package/$version/documentation.md");
if (! $this->files->exists($path)) {
return [];
}
return [
'pages' => collect(explode(PHP_EOL,
$this->replaceLinks($package, $version, $this->files->get($path))))
->filter(fn ($line) => Str::contains($line, "/docs/$package/$version/"))
->map(fn ($line) => resource_path(Str::of($line)->afterLast('(/')->before(')')
->replace('{{version}}', $version)->append('.md')))
->filter(fn ($path) => $this->files->exists($path))
->mapWithKeys(function ($path) {
$contents = $this->files->get($path);
preg_match('/\# (?<title>[^\\n]+)/', $contents, $page);
preg_match_all('/<a name="(?<fragments>[^"]+)"><\\/a>\n#+ (?<titles>[^\\n]+)/', $contents,
$section);
return [
(string) Str::of($path)->afterLast('/')->before('.md') => [
'title' => $page['title'] ?? Config::string('app.name'),
'sections' => collect($section['fragments'])
->combine($section['titles'])
->map(fn ($title) => ['title' => $title]),
],
];
}),
];
});
}
/**
* Get the given documentation page.
*/
public function get(string $package, string $version, string $page): string
{
return $this->cache->remember($package.'.docs.'.$version.'.'.$page, 5,
function () use ($package, $version, $page) {
$path = $this->getBasePath($package, $version).'/'.$page.'.md';
if (! $this->files->exists($path)) {
return '';
}
$content = file_get_contents($path);
if (! $content) {
return '';
}
$content = $this->replaceLinks($package, $version, $content);
return $this->convertToMarkdown($content);
}
);
}
/**
* Determine which versions a page exists in.
*/
public function versionsContainingPage(string $package, string $page): Collection
{
return collect(static::getDocVersions($package))
->filter(function ($version) use ($package, $page) {
return $this->pageExists($package, $version, $page);
});
}
/**
* Get the publicly available versions of the documentation
*/
public static function getDocVersions(string $package): array
{
return Config::array('docs.packages.'.$package.'.versions', []);
}
/**
* Check if the given section exists.
*/
public function pageExists(string $package, string $version, string $page): bool
{
$path = resource_path("docs/$package/$version/$page.md");
return $this->files->exists($path);
}
public static function getRepositoryLink(string $package, string $version, string $sectionPage): string
{
$gitBasePath = 'https://github.com/yajra';
return $gitBasePath.'/'.$package.'-docs/edit/'.$version.'/'.$sectionPage.'.md';
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Http/Controllers/Controller.php | PHP | <?php
namespace App\Http\Controllers;
abstract class Controller
{
//
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Http/Controllers/DocsController.php | PHP | <?php
namespace App\Http\Controllers;
use App\Documentation;
use Illuminate\Support\Str;
use Symfony\Component\DomCrawler\Crawler;
class DocsController extends Controller
{
public function __construct(protected Documentation $docs) {}
/**
* Show the root documentation page (/docs).
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function showRootPage(?string $package = null)
{
$package = $package ?: DEFAULT_PACKAGE;
if (Str::contains($package, 'datatables')) {
$package = 'laravel-datatables';
}
if (Str::contains($package, 'oci8')) {
$package = 'laravel-oci8';
}
$defaultVersion = Documentation::getDefaultVersion($package);
return redirect("docs/$package/".$defaultVersion);
}
/**
* Show a documentation page.
*
* @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Routing\Redirector
*/
public function show(string $package, ?string $version = null, ?string $page = null)
{
$defaultVersion = Documentation::getDefaultVersion($package);
if (is_null($version) || ! $this->isVersion($package, $version)) {
return redirect("docs/$package/".$defaultVersion.'/'.$version, 301);
}
if (! defined('CURRENT_VERSION')) {
define('CURRENT_VERSION', $version);
}
$sectionPage = $page ?: 'installation';
$content = $this->docs->get($package, $version, $sectionPage);
if (empty($content)) {
$otherVersions = $this->docs->versionsContainingPage($package, $sectionPage);
return response()->view('docs.show', [
'title' => 'Page not found',
'index' => $this->docs->getIndex($package, $version),
'package' => $package,
'content' => view('docs.missing', [
'otherVersions' => $otherVersions,
'package' => $package,
'page' => $page,
]),
'currentVersion' => $version,
'defaultVersion' => $defaultVersion,
'versions' => Documentation::getDocVersions($package),
'currentSection' => $otherVersions->isEmpty() ? '' : '/'.$page,
'canonical' => null,
], 404);
}
$title = (new Crawler($content))->filterXPath('//h1');
$section = '';
if ($this->docs->pageExists($package, $version, $sectionPage)) {
$section .= '/'.$sectionPage;
} elseif (! is_null($page)) {
return redirect("/docs/$package/$version");
}
$canonical = null;
return view('docs.show', [
'title' => count($title) ? $title->text() : null,
'index' => $this->docs->getIndex($package, $version),
'package' => $package,
'content' => $content,
'currentVersion' => $version,
'defaultVersion' => $defaultVersion,
'versions' => Documentation::getDocVersions($package),
'currentSection' => $section,
'canonical' => $canonical,
'repositoryLink' => Documentation::getRepositoryLink($package, $version, $sectionPage),
]);
}
/**
* Determine if the given URL segment is a valid version.
*/
protected function isVersion(string $package, string $version): bool
{
return in_array($version, array_keys(Documentation::getDocVersions($package)));
}
/**
* Show the documentation index JSON representation.
*
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
public function index(string $package, string $version, Documentation $docs)
{
$major = Str::before($version, '.');
$versions = Documentation::getDocVersions($package);
$defaultVersion = Documentation::getDefaultVersion($package);
if ((int) Str::before(array_values($versions)[1], '.') + 1 === (int) $major) {
$version = $major = 'master';
}
if (! $this->isVersion($package, $version)) {
return redirect("docs/$package/".$defaultVersion.'/index.json', 301);
}
if ($major !== 'master' && $major < 9) {
return response()->json([]);
}
return response()->json($docs->indexArray($package, $version));
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Markdown/GithubFlavoredMarkdownConverter.php | PHP | <?php
namespace App\Markdown;
use Laravel\Unfenced\UnfencedExtension;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Environment\EnvironmentInterface;
use League\CommonMark\Extension\Attributes\AttributesExtension;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\MarkdownConverter;
use Torchlight\Commonmark\V2\TorchlightExtension;
/**
* Converts GitHub Flavored Markdown to HTML.
*/
class GithubFlavoredMarkdownConverter extends MarkdownConverter
{
/**
* Create a new Markdown converter pre-configured for GFM
*
* @param array<string, mixed> $config
*/
public function __construct(array $config = [])
{
$environment = new Environment($config);
$environment->addExtension(new CommonMarkCoreExtension);
$environment->addExtension(new GithubFlavoredMarkdownExtension);
$environment->addExtension(new AttributesExtension);
$environment->addExtension(new UnfencedExtension);
$environment->addExtension(new TorchlightExtension);
parent::__construct($environment);
}
public function getEnvironment(): EnvironmentInterface
{
return $this->environment;
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Markdown/GithubFlavoredMarkdownExtension.php | PHP | <?php
namespace App\Markdown;
use League\CommonMark\Environment\EnvironmentBuilderInterface;
use League\CommonMark\Extension\Autolink\AutolinkExtension;
use League\CommonMark\Extension\ExtensionInterface;
use League\CommonMark\Extension\Strikethrough\StrikethroughExtension;
use League\CommonMark\Extension\Table\TableExtension;
use League\CommonMark\Extension\TaskList\TaskListExtension;
final class GithubFlavoredMarkdownExtension implements ExtensionInterface
{
public function register(EnvironmentBuilderInterface $environment): void
{
$environment->addExtension(new AutolinkExtension);
$environment->addExtension(new StrikethroughExtension);
$environment->addExtension(new TableExtension);
$environment->addExtension(new TaskListExtension);
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Models/User.php | PHP | <?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var list<string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/Providers/AppServiceProvider.php | PHP | <?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/View/Components/AppLayout.php | PHP | <?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.app');
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
app/View/Components/GuestLayout.php | PHP | <?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.guest');
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bin/checkout_latest_docs.sh | Shell | #!/bin/bash
DATATABLES=(
master
12.0
11.0
10.0
9.0
8.0
7.0
6.0
)
for v in "${DATATABLES[@]}"; do
if [ -d "resources/docs/laravel-datatables/$v" ]; then
echo "Pulling latest laravel-datatables documentation updates for $v..."
(cd resources/docs/laravel-datatables/$v && git pull)
else
echo "Cloning $v..."
git clone --single-branch --branch "$v" https://github.com/yajra/laravel-datatables-docs "resources/docs/laravel-datatables/$v"
fi;
done
ACL=(
master
12.0
11.0
10.0
9.0
5.0
6.0
4.0
3.0
)
for v in "${ACL[@]}"; do
if [ -d "resources/docs/laravel-acl/$v" ]; then
echo "Pulling latest laravel-acl documentation updates for $v..."
(cd resources/docs/laravel-acl/$v && git pull)
else
echo "Cloning $v..."
git clone --single-branch --branch "$v" https://github.com/yajra/laravel-acl-docs "resources/docs/laravel-acl/$v"
fi;
done
OCI8=(
master
12.0
11.0
10.0
9.0
8.0
7.0
6.0
5.3
)
for v in "${OCI8[@]}"; do
if [ -d "resources/docs/laravel-oci8/$v" ]; then
echo "Pulling latest laravel-oci8 documentation updates for $v..."
(cd resources/docs/laravel-oci8/$v && git pull)
else
echo "Cloning $v..."
git clone --single-branch --branch "$v" https://github.com/yajra/laravel-oci8-docs "resources/docs/laravel-oci8/$v"
fi;
done
AUDITABLE=(
master
12.0
11.0
4.0
3.0
2.0
)
for v in "${AUDITABLE[@]}"; do
if [ -d "resources/docs/laravel-auditable/$v" ]; then
echo "Pulling latest laravel-auditable documentation updates for $v..."
(cd resources/docs/laravel-auditable/$v && git pull)
else
echo "Cloning $v..."
git clone --single-branch --branch "$v" https://github.com/yajra/laravel-auditable-docs "resources/docs/laravel-auditable/$v"
fi;
done
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bin/deploy.sh | Shell | #!/bin/bash
if [ ! -f composer.json ]; then
echo "Please make sure to run this script from the root directory of this repo."
exit 1
fi
git pull
composer install
php artisan optimize
npm ci
npm run build
source "$(dirname "$0")/checkout_latest_docs.sh"
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bin/setup.sh | Shell | #!/bin/bash
if [ ! -f composer.json ]; then
echo "Please make sure to run this script from the root directory of this repo."
exit 1
fi
composer install
touch database/database.sqlite
cp .env.example .env
php artisan key:generate
php artisan migrate
source "$(dirname "$0")/checkout_latest_docs.sh"
npm install
npm run dev
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bin/update.sh | Shell | #!/bin/bash
if [ ! -f composer.json ]; then
echo "Please make sure to run this script from the root directory of this repo."
exit 1
fi
composer install
source "$(dirname "$0")/checkout_latest_docs.sh"
npm install
npm run dev
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bootstrap/app.php | PHP | <?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bootstrap/helpers.php | PHP | <?php
use Illuminate\Support\Str;
/**
* SVG helper
*/
if (! function_exists('svg')) {
function svg(string $src): string
{
$contents = file_get_contents(public_path('assets/svg/'.$src.'.svg'));
if ($contents === false) {
return '';
}
return $contents;
}
}
/**
* Fetch github repo information.
*/
if (! function_exists('github')) {
function github(string $repo): array
{
return app('cache.store')->remember($repo.':stats', now()->addDay(), function () use ($repo) {
return app('github')->repositories()->show('yajra', $repo);
});
}
}
/**
* Convert package name to title.
*/
if (! function_exists('package_to_title')) {
function package_to_title(string $package): string
{
$title = implode(' ', array_map('ucwords', explode('-', $package)));
if (Str::contains($title, 'Datatables')) {
return str_replace('Datatables', 'DataTables', $title);
}
return $title;
}
}
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
bootstrap/providers.php | PHP | <?php
return [
App\Providers\AppServiceProvider::class,
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/algolia.php | PHP | <?php
/*
* This file is part of Laravel Algolia.
*
* (c) Vincent Klaiber <hello@vinkla.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the connections below you wish to use as
| your default connection for all work. Of course, you may use many
| connections at once using the manager class.
|
*/
'default' => 'main',
/*
|--------------------------------------------------------------------------
| Algolia Connections
|--------------------------------------------------------------------------
|
| Here are each of the connections setup for your application. Example
| configuration has been included, but you may add as many connections as
| you would like.
|
*/
'connections' => [
'main' => [
'id' => env('ALGOLIA_ID'),
'search_key' => env('ALGOLIA_SEARCH_KEY'),
'key' => env('ALGOLIA_KEY'),
],
],
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/app.php | PHP | <?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => env('APP_TIMEZONE', 'UTC'),
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/auth.php | PHP | <?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/cache.php | PHP | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel'), '_').'_cache_'),
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/database.php | PHP | <?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/docs.php | PHP | <?php
return [
'username' => 'yajra',
'packages' => [
'laravel-auditable' => [
'default' => '12.0',
'versions' => [
'master' => 'Master',
'12.0' => '12.0',
'11.0' => '11.0',
'4.0' => '4.0',
'3.0' => '3.0',
'2.0' => '2.0',
],
],
'laravel-acl' => [
'default' => '12.0',
'versions' => [
'master' => 'Master',
'12.0' => '12.0',
'11.0' => '11.0',
'10.0' => '10.0',
'9.0' => '9.0',
'6.0' => '6.0',
'5.0' => '5.0',
'4.0' => '4.0',
'3.0' => '3.0',
],
],
'laravel-datatables' => [
'default' => '12.0',
'versions' => [
'master' => 'Master',
'12.0' => '12.0',
'11.0' => '11.0',
'10.0' => '10.0',
'9.0' => '9.0',
'8.0' => '8.0',
'7.0' => '7.0',
'6.0' => '6.0',
],
],
'laravel-oci8' => [
'default' => '12.0',
'versions' => [
'master' => 'Master',
'12.0' => '12.0',
'11.0' => '11.0',
'10.0' => '10.0',
'9.0' => '9.0',
'8.0' => '8.0',
'7.0' => '7.0',
'6.0' => '6.0',
'5.3' => '5.3 - 5.8',
],
],
],
'links' => [
'laravel-auditable' => [],
'laravel-acl' => [],
'laravel-oci8' => [],
'laravel-datatables' => [
'datatables' => [
'title' => 'DataTables.net',
'icon' => 'nav-datatables',
'url' => 'https://datatables.net',
],
],
],
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/filesystems.php | PHP | <?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
config/github.php | PHP | <?php
declare(strict_types=1);
/*
* This file is part of Laravel GitHub.
*
* (c) Graham Campbell <hello@gjcampbell.co.uk>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
return [
/*
|--------------------------------------------------------------------------
| Default Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the connections below you wish to use as
| your default connection for all work. Of course, you may use many
| connections at once using the manager class.
|
*/
'default' => 'main',
/*
|--------------------------------------------------------------------------
| GitHub Connections
|--------------------------------------------------------------------------
|
| Here are each of the connections setup for your application. Example
| configuration has been included, but you may add as many connections as
| you would like. Note that the 5 supported authentication methods are:
| "application", "jwt", "none", "private", and "token".
|
*/
'connections' => [
'main' => [
'method' => 'token',
'token' => env('GITHUB_TOKEN', 'your-token'),
// 'backoff' => false,
// 'cache' => false,
// 'version' => 'v3',
// 'enterprise' => false,
],
'app' => [
'method' => 'application',
'clientId' => 'your-client-id',
'clientSecret' => 'your-client-secret',
// 'backoff' => false,
// 'cache' => false,
// 'version' => 'v3',
// 'enterprise' => false,
],
'jwt' => [
'method' => 'jwt',
'token' => 'your-jwt-token',
// 'backoff' => false,
// 'cache' => false,
// 'version' => 'v3',
// 'enterprise' => false,
],
'private' => [
'method' => 'private',
'appId' => 'your-github-app-id',
'keyPath' => 'your-private-key-path',
// 'key' => 'your-private-key-content',
// 'passphrase' => 'your-private-key-passphrase'
// 'backoff' => false,
// 'cache' => false,
// 'version' => 'v3',
// 'enterprise' => false,
],
'none' => [
'method' => 'none',
// 'backoff' => false,
// 'cache' => false,
// 'version' => 'v3',
// 'enterprise' => false,
],
],
/*
|--------------------------------------------------------------------------
| HTTP Cache
|--------------------------------------------------------------------------
|
| Here are each of the cache configurations setup for your application.
| Only the "illuminate" driver is provided out of the box. Example
| configuration has been included.
|
*/
'cache' => [
'main' => [
'driver' => 'illuminate',
'connector' => null, // null means use default driver
// 'min' => 43200,
// 'max' => 172800
],
'bar' => [
'driver' => 'illuminate',
'connector' => 'redis', // config/cache.php
// 'min' => 43200,
// 'max' => 172800
],
],
];
| yajra/yajrabox.com | 10 | Source code of yajrabox.com website. | PHP | yajra | Arjay Angeles | ObjectBright, Inc. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.